llm-large-files 0.4.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/CHANGELOG.md +1400 -338
  2. package/README.md +217 -49
  3. package/dist/analyze.d.ts +5 -0
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +96 -47
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +117 -0
  8. package/dist/anthropic/adapter.d.ts.map +1 -0
  9. package/dist/anthropic/adapter.js +542 -0
  10. package/dist/anthropic/adapter.js.map +1 -0
  11. package/dist/anthropic/index.d.ts +3 -0
  12. package/dist/anthropic/index.d.ts.map +1 -0
  13. package/dist/anthropic/index.js +2 -0
  14. package/dist/anthropic/index.js.map +1 -0
  15. package/dist/ask.d.ts +200 -0
  16. package/dist/ask.d.ts.map +1 -0
  17. package/dist/ask.js +1402 -0
  18. package/dist/ask.js.map +1 -0
  19. package/dist/budget.d.ts +23 -0
  20. package/dist/budget.d.ts.map +1 -0
  21. package/dist/budget.js +64 -0
  22. package/dist/budget.js.map +1 -0
  23. package/dist/encoding.d.ts +17 -0
  24. package/dist/encoding.d.ts.map +1 -0
  25. package/dist/encoding.js +852 -0
  26. package/dist/encoding.js.map +1 -0
  27. package/dist/errors.d.ts +4 -0
  28. package/dist/errors.d.ts.map +1 -1
  29. package/dist/errors.js +15 -0
  30. package/dist/errors.js.map +1 -1
  31. package/dist/events.d.ts +333 -0
  32. package/dist/events.d.ts.map +1 -0
  33. package/dist/events.js +159 -0
  34. package/dist/events.js.map +1 -0
  35. package/dist/evidence.d.ts +42 -0
  36. package/dist/evidence.d.ts.map +1 -0
  37. package/dist/evidence.js +138 -0
  38. package/dist/evidence.js.map +1 -0
  39. package/dist/extract.d.ts +35 -3
  40. package/dist/extract.d.ts.map +1 -1
  41. package/dist/extract.js +626 -58
  42. package/dist/extract.js.map +1 -1
  43. package/dist/gemini/adapter.d.ts +59 -0
  44. package/dist/gemini/adapter.d.ts.map +1 -0
  45. package/dist/gemini/adapter.js +226 -0
  46. package/dist/gemini/adapter.js.map +1 -0
  47. package/dist/gemini/chat.d.ts +53 -77
  48. package/dist/gemini/chat.d.ts.map +1 -1
  49. package/dist/gemini/chat.js +42 -300
  50. package/dist/gemini/chat.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +16 -0
  52. package/dist/gemini/errors.d.ts.map +1 -0
  53. package/dist/gemini/errors.js +46 -0
  54. package/dist/gemini/errors.js.map +1 -0
  55. package/dist/gemini/generate.d.ts +18 -21
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +49 -92
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +6 -4
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +4 -3
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -2
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -38
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/http.d.ts +136 -0
  68. package/dist/http.d.ts.map +1 -0
  69. package/dist/http.js +401 -0
  70. package/dist/http.js.map +1 -0
  71. package/dist/index.d.ts +18 -2
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +13 -4
  74. package/dist/index.js.map +1 -1
  75. package/dist/library.d.ts +96 -8
  76. package/dist/library.d.ts.map +1 -1
  77. package/dist/library.js +414 -96
  78. package/dist/library.js.map +1 -1
  79. package/dist/map-reduce.d.ts +37 -1
  80. package/dist/map-reduce.d.ts.map +1 -1
  81. package/dist/map-reduce.js +255 -61
  82. package/dist/map-reduce.js.map +1 -1
  83. package/dist/model.d.ts +278 -0
  84. package/dist/model.d.ts.map +1 -0
  85. package/dist/model.js +222 -0
  86. package/dist/model.js.map +1 -0
  87. package/dist/node/handlers.d.ts +20 -4
  88. package/dist/node/handlers.d.ts.map +1 -1
  89. package/dist/node/handlers.js +122 -20
  90. package/dist/node/handlers.js.map +1 -1
  91. package/dist/node/index.d.ts +2 -0
  92. package/dist/node/index.d.ts.map +1 -1
  93. package/dist/node/index.js +1 -0
  94. package/dist/node/index.js.map +1 -1
  95. package/dist/node/sse.d.ts +59 -0
  96. package/dist/node/sse.d.ts.map +1 -0
  97. package/dist/node/sse.js +174 -0
  98. package/dist/node/sse.js.map +1 -0
  99. package/dist/openai/adapter.d.ts +109 -0
  100. package/dist/openai/adapter.d.ts.map +1 -0
  101. package/dist/openai/adapter.js +567 -0
  102. package/dist/openai/adapter.js.map +1 -0
  103. package/dist/openai/index.d.ts +3 -0
  104. package/dist/openai/index.d.ts.map +1 -0
  105. package/dist/openai/index.js +2 -0
  106. package/dist/openai/index.js.map +1 -0
  107. package/dist/output-limit.d.ts +42 -0
  108. package/dist/output-limit.d.ts.map +1 -0
  109. package/dist/output-limit.js +121 -0
  110. package/dist/output-limit.js.map +1 -0
  111. package/dist/pause.d.ts +24 -0
  112. package/dist/pause.d.ts.map +1 -0
  113. package/dist/pause.js +38 -0
  114. package/dist/pause.js.map +1 -0
  115. package/dist/pdf-pages.d.ts +32 -2
  116. package/dist/pdf-pages.d.ts.map +1 -1
  117. package/dist/pdf-pages.js +275 -14
  118. package/dist/pdf-pages.js.map +1 -1
  119. package/dist/pdf-pictures.d.ts +30 -3
  120. package/dist/pdf-pictures.d.ts.map +1 -1
  121. package/dist/pdf-pictures.js +50 -8
  122. package/dist/pdf-pictures.js.map +1 -1
  123. package/dist/pdf-work.d.ts +40 -0
  124. package/dist/pdf-work.d.ts.map +1 -0
  125. package/dist/pdf-work.js +734 -0
  126. package/dist/pdf-work.js.map +1 -0
  127. package/dist/plan.d.ts +22 -4
  128. package/dist/plan.d.ts.map +1 -1
  129. package/dist/plan.js +61 -12
  130. package/dist/plan.js.map +1 -1
  131. package/dist/retry.d.ts +76 -0
  132. package/dist/retry.d.ts.map +1 -0
  133. package/dist/retry.js +141 -0
  134. package/dist/retry.js.map +1 -0
  135. package/dist/search.d.ts +8 -2
  136. package/dist/search.d.ts.map +1 -1
  137. package/dist/search.js +60 -10
  138. package/dist/search.js.map +1 -1
  139. package/dist/sse.d.ts +36 -0
  140. package/dist/sse.d.ts.map +1 -0
  141. package/dist/sse.js +153 -0
  142. package/dist/sse.js.map +1 -0
  143. package/dist/stores.d.ts.map +1 -1
  144. package/dist/stores.js +5 -2
  145. package/dist/stores.js.map +1 -1
  146. package/dist/text-index.d.ts +6 -0
  147. package/dist/text-index.d.ts.map +1 -1
  148. package/dist/text-index.js +25 -8
  149. package/dist/text-index.js.map +1 -1
  150. package/dist/text.d.ts +62 -2
  151. package/dist/text.d.ts.map +1 -1
  152. package/dist/text.js +314 -14
  153. package/dist/text.js.map +1 -1
  154. package/dist/tools.d.ts +72 -1
  155. package/dist/tools.d.ts.map +1 -1
  156. package/dist/tools.js +341 -60
  157. package/dist/tools.js.map +1 -1
  158. package/dist/types.d.ts +128 -4
  159. package/dist/types.d.ts.map +1 -1
  160. package/dist/zip-directory.d.ts +43 -0
  161. package/dist/zip-directory.d.ts.map +1 -0
  162. package/dist/zip-directory.js +130 -0
  163. package/dist/zip-directory.js.map +1 -0
  164. package/docs/README.md +288 -0
  165. package/docs/api.md +58 -184
  166. package/docs/configuration.md +34 -490
  167. package/docs/getting-started.md +412 -177
  168. package/docs/guides/anthropic.md +590 -0
  169. package/docs/guides/conversations.md +629 -0
  170. package/docs/guides/costs-and-limits.md +726 -0
  171. package/docs/guides/deployment.md +654 -0
  172. package/docs/guides/errors-and-reliability.md +735 -0
  173. package/docs/guides/explorer-model.md +399 -0
  174. package/docs/guides/openai-compatible.md +602 -0
  175. package/docs/guides/own-adapter-and-loop.md +1169 -0
  176. package/docs/guides/pdfs.md +971 -0
  177. package/docs/guides/storage.md +731 -0
  178. package/docs/guides/testing.md +1199 -0
  179. package/docs/guides/vertex-and-gemini.md +717 -0
  180. package/docs/guides/web-app.md +1589 -0
  181. package/docs/how-it-works.md +1022 -138
  182. package/docs/measurements.md +881 -0
  183. package/docs/publishing.md +274 -46
  184. package/docs/reference/anthropic.md +427 -0
  185. package/docs/reference/ask.md +892 -0
  186. package/docs/reference/errors-and-retries.md +758 -0
  187. package/docs/reference/events.md +993 -0
  188. package/docs/reference/gemini.md +823 -0
  189. package/docs/reference/library.md +1467 -0
  190. package/docs/reference/node.md +528 -0
  191. package/docs/reference/openai.md +385 -0
  192. package/docs/reference/tools.md +883 -0
  193. package/docs/security.md +902 -90
  194. package/docs/troubleshooting.md +1390 -0
  195. package/package.json +22 -4
  196. package/src/analyze.ts +93 -42
  197. package/src/anthropic/adapter.ts +611 -0
  198. package/src/anthropic/index.ts +2 -0
  199. package/src/ask.ts +1560 -0
  200. package/src/budget.ts +71 -0
  201. package/src/encoding.ts +850 -0
  202. package/src/errors.ts +17 -0
  203. package/src/events.ts +442 -0
  204. package/src/evidence.ts +165 -0
  205. package/src/extract.ts +602 -62
  206. package/src/gemini/adapter.ts +271 -0
  207. package/src/gemini/chat.ts +87 -355
  208. package/src/gemini/errors.ts +48 -0
  209. package/src/gemini/generate.ts +67 -94
  210. package/src/gemini/index.ts +6 -4
  211. package/src/gemini/sse.ts +1 -34
  212. package/src/http.ts +434 -0
  213. package/src/index.ts +55 -4
  214. package/src/library.ts +497 -97
  215. package/src/map-reduce.ts +266 -59
  216. package/src/model.ts +433 -0
  217. package/src/node/handlers.ts +137 -22
  218. package/src/node/index.ts +2 -0
  219. package/src/node/sse.ts +198 -0
  220. package/src/openai/adapter.ts +613 -0
  221. package/src/openai/index.ts +2 -0
  222. package/src/output-limit.ts +135 -0
  223. package/src/pause.ts +41 -0
  224. package/src/pdf-pages.ts +268 -15
  225. package/src/pdf-pictures.ts +56 -9
  226. package/src/pdf-work.ts +722 -0
  227. package/src/plan.ts +68 -12
  228. package/src/retry.ts +176 -0
  229. package/src/search.ts +63 -10
  230. package/src/sse.ts +159 -0
  231. package/src/stores.ts +5 -2
  232. package/src/text-index.ts +26 -7
  233. package/src/text.ts +323 -13
  234. package/src/tools.ts +338 -62
  235. package/src/types.ts +129 -5
  236. package/src/zip-directory.ts +136 -0
package/src/text-index.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  * It is built from the bytes of the text, in one pass, at ingest (and written next to the text
7
7
  * with `putIndex`), or the first time an older document without one is used.
8
8
  */
9
+ import type { TimeSlicer } from "./pause.js";
9
10
  import type { DocumentMeta } from "./types.js";
10
11
 
11
12
  /** A passage, for keyword search, is a run of lines of about this many characters... */
@@ -126,18 +127,36 @@ export class TextIndexBuilder {
126
127
  /** The index of a text held as a string, built from its UTF-8 bytes a slice at a time. */
127
128
  export function buildTextIndex(text: string): TextIndex {
128
129
  const builder = new TextIndexBuilder();
129
- const slice = 1 << 20;
130
+ for (let at = 0; at < text.length;) at = pushSlice(builder, text, at);
131
+ return builder.finish();
132
+ }
133
+
134
+ /**
135
+ * `buildTextIndex`, the same index, with pauses for other requests while a large text is indexed.
136
+ * `onProgress` is told the characters indexed so far, after each slice.
137
+ */
138
+ export async function buildTextIndexInSlices(text: string, slicer: TimeSlicer, onProgress?: (done: number, total: number) => void): Promise<TextIndex> {
139
+ const builder = new TextIndexBuilder();
130
140
  for (let at = 0; at < text.length;) {
131
- let end = Math.min(text.length, at + slice);
132
- // Never cut between the two halves of a surrogate pair: each half alone encodes as U+FFFD.
133
- const last = text.charCodeAt(end - 1);
134
- if (end < text.length && last >= 0xd800 && last <= 0xdbff) end++;
135
- builder.push(Buffer.from(text.slice(at, end), "utf8"));
136
- at = end;
141
+ at = pushSlice(builder, text, at);
142
+ onProgress?.(at, text.length);
143
+ await slicer.maybePause();
137
144
  }
138
145
  return builder.finish();
139
146
  }
140
147
 
148
+ /** Pushes the next slice of `text`, from `at`, as UTF-8; returns where the slice ended. */
149
+ function pushSlice(builder: TextIndexBuilder, text: string, at: number): number {
150
+ let end = Math.min(text.length, at + (1 << 18));
151
+ // Never cut between the two halves of a surrogate pair: each half alone encodes as U+FFFD. Only
152
+ // a real pair is kept whole: a first half followed by anything else is one U+FFFD either way.
153
+ const last = text.charCodeAt(end - 1);
154
+ const next = text.charCodeAt(end);
155
+ if (end < text.length && last >= 0xd800 && last <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) end++;
156
+ builder.push(Buffer.from(text.slice(at, end), "utf8"));
157
+ return end;
158
+ }
159
+
141
160
  // The file: a 40-byte header, then the lists of 32-bit numbers (line starts in bytes, line starts
142
161
  // in characters, passage starts, page starts), all little-endian.
143
162
  // 0 "LLFI" 4 version 8 lineCount 12 passages 16 pages 20 unused
package/src/text.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { TimeSlicer } from "./pause.js";
2
+
1
3
  /** Lines longer than this are split so line-based tools always return bounded output. */
2
4
  export const MAX_LINE_CHARACTERS = 2_000;
3
5
 
@@ -7,20 +9,176 @@ export const MAX_LINE_CHARACTERS = 2_000;
7
9
  * ("ESC 7", "ESC c"). Coloured logs are full of them. An "ESC ]" whose end is not on its line is
8
10
  * not a sequence: only those two characters go. Otherwise one stray "ESC ]", a cut-off window title
9
11
  * or two bytes in a logged user agent, would take every line after it.
12
+ * U+009B, the one-character form of "ESC [", starts a sequence only with a parameter ("\x9b31m"),
13
+ * and not right after U+0080-U+00FF: there it is the end of a letter of UTF-8 read as Latin-1
14
+ * ("ś" is C5 9B, so "Coś? Tak" holds "\xc5\x9b? Tak"), and what follows it is text. `INVISIBLE`
15
+ * removes the U+009B alone then.
16
+ */
17
+ // eslint-disable-next-line no-control-regex
18
+ const ANSI_ESCAPE = /\x1b(?:\[[0-?]*[ -\/]*[@-~]|\][^\x07\x1b\n]*(?:\x07|\x1b\\)|[ -\/]+[0-~]|[0-~])|(?<![\x80-\xff])\x9b[0-?]+[ -\/]*[@-~]/g;
19
+
20
+ /**
21
+ * Characters that show nothing, that no script needs, and that can hide text from a person who
22
+ * reads the file while a model reads it:
23
+ * - control characters other than tab and line breaks: C0 (U+0000-U+001F, U+007F) and C1
24
+ * (U+0080-U+009F);
25
+ * - Unicode tag characters (U+E0000-U+E007F). Each spells out one ASCII character, which a model
26
+ * reads and a person does not see. The three flags written with them (England, Scotland,
27
+ * Wales) are kept;
28
+ * - the text-direction controls that change the order a person sees: embeddings and overrides
29
+ * (U+202A-U+202E) and isolates (U+2066-U+2069). The marks that right-to-left text needs
30
+ * (U+200E, U+200F, U+061C) are kept;
31
+ * - the zero-width space (U+200B), the word joiner and invisible operators (U+2060-U+2064), the
32
+ * deprecated format characters (U+206A-U+206F), a byte order mark inside the text (U+FEFF), and
33
+ * the soft hyphen (U+00AD), but not one before a line break: there it shows, as a hyphen.
34
+ * Zero-width joiners and non-joiners (U+200C, U+200D) are kept: emoji and some scripts need them.
35
+ * Tab, "\n" and "\r" are not among them, so removing them moves no line. U+0085 goes with the other
36
+ * C1 characters, except where it ends lines (see `NEXT_LINE`).
10
37
  */
11
38
  // eslint-disable-next-line no-control-regex
12
- const ANSI_ESCAPE = /\x1b(?:\[[0-?]*[ -\/]*[@-~]|\][^\x07\x1b\n]*(?:\x07|\x1b\\)|[ -\/]+[0-~]|[0-~])/g;
39
+ const INVISIBLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F\u200B\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF]+|\xAD(?!\n)|\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|(?:\uDB40[\uDC00-\uDC7F])+/g;
40
+ /** A flag written with tag characters starts with U+1F3F4, whose first half is this. */
41
+ const FLAG_START = 0xd83c;
42
+ /**
43
+ * U+0085 (next line) ends each record of a mainframe file converted to UTF-8, which has no other
44
+ * line break: in such a text it becomes a line break (see `breaksAtNextLine`). Not one right after
45
+ * U+0080-U+00FF: there it is the last byte of a UTF-8 letter read as Latin-1 ("ą" is C4 85), and a
46
+ * line break would split the word. `INVISIBLE` removes that one, and those of other texts.
47
+ */
48
+ const NEXT_LINE = /(?<![\x80-\xFF])\x85/g;
49
+ /** A run of U+0085, to go past it in one step. */
50
+ const NEXT_LINE_RUN = /\x85+/y;
51
+
52
+ /** `text` without the characters of `INVISIBLE`. */
53
+ export function removeInvisible(text: string): string {
54
+ return text.replace(INVISIBLE, (found) => (found.charCodeAt(0) === FLAG_START ? found : ""));
55
+ }
56
+
57
+ /** A word for a count: "line" for 1, "lines" for any other. */
58
+ export const plural = (count: number, word: string): string => (count === 1 ? word : `${word}s`);
59
+
60
+ /**
61
+ * Whether the U+0085 of `text` end lines: only when it has no other line break, one at its very end
62
+ * aside. A mainframe file converted to UTF-8 has none. In a text that has them, a U+0085 is more
63
+ * often in a JSON string or a CSV field, or a windows-1252 "…" read as Latin-1, and a line break
64
+ * there would split a record and move every line after it.
65
+ */
66
+ export function breaksAtNextLine(text: string): boolean {
67
+ let end = text.length;
68
+ if (text.charCodeAt(end - 1) === 10) end--;
69
+ if (text.charCodeAt(end - 1) === 13) end--;
70
+ const lineFeed = text.indexOf("\n");
71
+ if (lineFeed !== -1 && lineFeed < end) return false;
72
+ const carriageReturn = text.indexOf("\r");
73
+ return carriageReturn === -1 || carriageReturn >= end;
74
+ }
75
+
76
+ /** `removeInvisible`, after each U+0085 that ends a line is made a line break, when `nextLines`. */
77
+ function cleanLines(text: string, nextLines: boolean): string {
78
+ return removeInvisible(nextLines && text.includes("\x85") ? text.replace(NEXT_LINE, "\n") : text);
79
+ }
13
80
 
14
81
  /**
15
- * Strips a BOM, unifies line endings, and removes terminal escape sequences and control characters
16
- * other than tab and newline.
82
+ * Strips a BOM, unifies line endings, and removes terminal escape sequences, control characters
83
+ * other than tab and newline, and the invisible characters of `INVISIBLE`. In a text with no other
84
+ * line break, a U+0085 becomes one (see `NEXT_LINE`).
17
85
  */
18
86
  export function normalizeText(raw: string): string {
19
- let text = raw.replace(/^/, "").replace(/\r\n?/g, "\n");
87
+ const text = raw.replace(/^/, "");
88
+ return normalizeLines(text, breaksAtNextLine(text));
89
+ }
90
+
91
+ /**
92
+ * `normalizeText` without the BOM: the same on a whole text as on pieces of it cut after line
93
+ * breaks, given `breaksAtNextLine` of the whole text as `nextLines`.
94
+ */
95
+ function normalizeLines(raw: string, nextLines: boolean): string {
96
+ return cleanLines(withoutEscapes(raw.replace(/\r\n?/g, "\n")), nextLines);
97
+ }
98
+
99
+ /** `text` without terminal escape sequences. */
100
+ function withoutEscapes(text: string): string {
20
101
  // Remove whole sequences first. Dropping only the ESC byte would leave "[31mERROR[0m" behind.
21
- if (text.includes("\x1b")) text = text.replace(ANSI_ESCAPE, "");
22
- // eslint-disable-next-line no-control-regex
23
- return text.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, "");
102
+ // U+009B is the one-character form of "ESC [".
103
+ return text.includes("\x1b") || text.includes("\x9b") ? text.replace(ANSI_ESCAPE, "") : text;
104
+ }
105
+
106
+ /**
107
+ * `withoutEscapes`, with a pause after each `piece` characters or so. The sequences are found one
108
+ * after the other, as `replace` finds them, so the result is the same.
109
+ */
110
+ async function withoutEscapesInPieces(text: string, slicer: TimeSlicer, piece: number): Promise<string> {
111
+ if (!text.includes("\x1b") && !text.includes("\x9b")) return text;
112
+ // A copy of its own: during a pause, another ingest may use `ANSI_ESCAPE`, which moves its lastIndex.
113
+ const escape = new RegExp(ANSI_ESCAPE.source, "g");
114
+ const done: string[] = [];
115
+ let parts: string[] = [];
116
+ // Where the text after the last sequence starts, and where the last pause was.
117
+ let kept = 0;
118
+ let paused = 0;
119
+ for (let found = escape.exec(text); found !== null; found = escape.exec(text)) {
120
+ parts.push(text.slice(kept, found.index));
121
+ kept = escape.lastIndex;
122
+ if (kept - paused >= piece) {
123
+ done.push(parts.join(""));
124
+ parts = [];
125
+ paused = kept;
126
+ await slicer.maybePause();
127
+ }
128
+ }
129
+ parts.push(text.slice(kept));
130
+ done.push(parts.join(""));
131
+ return done.length === 1 ? done[0]! : done.join("");
132
+ }
133
+
134
+ /**
135
+ * `normalizeLines`, a piece of about `piece` characters at a time, with a pause between pieces. A
136
+ * line with no break for megabytes can hold millions of characters or escape sequences to remove,
137
+ * which take seconds in one go. The escape sequences are found in order, as in one go, and the
138
+ * pieces of the last step (`cleanLines`) end where `cutsCleanly` says, so the result is the same.
139
+ */
140
+ export async function normalizeInPieces(raw: string, slicer: TimeSlicer, nextLines: boolean, piece = SLICE_CHARACTERS): Promise<string> {
141
+ const text = await withoutEscapesInPieces(raw.replace(/\r\n?/g, "\n"), slicer, piece);
142
+ const parts: string[] = [];
143
+ for (let from = 0; from < text.length;) {
144
+ let to = Math.min(text.length, from + piece);
145
+ // Where the next piece starts.
146
+ let next = to;
147
+ while (to < text.length && !cutsCleanly(text, to)) {
148
+ if (text.charCodeAt(to) === 0x85) {
149
+ // A run of U+0085 after U+0080-U+00FF, which no place may cut. `cleanLines` removes all of
150
+ // it, and gives the same on the text before it and after it alone: the run is left out.
151
+ NEXT_LINE_RUN.lastIndex = to;
152
+ NEXT_LINE_RUN.test(text);
153
+ next = NEXT_LINE_RUN.lastIndex;
154
+ break;
155
+ }
156
+ next = ++to;
157
+ }
158
+ parts.push(cleanLines(text.slice(from, to), nextLines));
159
+ from = next;
160
+ await slicer.maybePause();
161
+ }
162
+ return parts.length === 1 ? parts[0]! : parts.join("");
163
+ }
164
+
165
+ /**
166
+ * Whether `cleanLines` gives the same result on `text` cut before `at` as on it whole. It does
167
+ * unless the cut is between the two halves of a character outside the basic plane, inside a flag,
168
+ * between a soft hyphen and a line break, or before a U+0085 right after U+0080-U+00FF. Only
169
+ * these places are kept whole: a rule that never cut after a soft hyphen or half of a pair would
170
+ * never cut a line of soft hyphens, or of tag characters and emoji in turn, and such a line
171
+ * would be cleaned in one go again.
172
+ */
173
+ function cutsCleanly(text: string, at: number): boolean {
174
+ const before = text.charCodeAt(at - 1);
175
+ const after = text.charCodeAt(at);
176
+ if (isHighSurrogate(before) && isLowSurrogate(after)) return false;
177
+ if (before === 0xad && after === 0x0a) return false;
178
+ if (after === 0x85 && before >= 0x80 && before <= 0xff) return false;
179
+ // A flag is 14 units: U+1F3F4, then tag characters, each a pair that starts with U+DB40.
180
+ if (after === 0xdb40 && text.slice(Math.max(0, at - 12), at).includes("\uD83C\uDFF4")) return false;
181
+ return true;
24
182
  }
25
183
 
26
184
  /**
@@ -45,11 +203,72 @@ export function foldCase(text: string): string {
45
203
  const isHighSurrogate = (code: number) => code >= 0xd800 && code <= 0xdbff;
46
204
  const isLowSurrogate = (code: number) => code >= 0xdc00 && code <= 0xdfff;
47
205
 
206
+ /**
207
+ * The first `end` UTF-16 units of `text`, one fewer when the last of them would be the first half
208
+ * of a character outside the basic plane (an emoji). Half of one is not text: JSON writes it as
209
+ * `\ud83d`, and an API that checks its input (Claude's) refuses the request.
210
+ */
211
+ export function sliceWhole(text: string, end: number): string {
212
+ const at = Math.max(0, Math.min(text.length, Math.trunc(end)));
213
+ return at > 0 && at < text.length && isHighSurrogate(text.charCodeAt(at - 1)) ? text.slice(0, at - 1) : text.slice(0, at);
214
+ }
215
+
216
+ /** Half of a character outside the basic plane, on its own. */
217
+ const LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
218
+
219
+ /**
220
+ * `text` with each half of a character that is on its own (an emoji cut in two) made a replacement
221
+ * character, as `String.prototype.toWellFormed` does. 0.5.0 cut some strings that way, and kept them:
222
+ * log templates in the metadata, and search windows in tool rounds. Claude's API refuses a request
223
+ * that holds one. Text that is whole comes back as it is.
224
+ */
225
+ export function wellFormed(text: string): string {
226
+ return /[\ud800-\udfff]/.test(text) ? text.replace(LONE_SURROGATE, "\ufffd") : text;
227
+ }
228
+
229
+ /**
230
+ * A JSON value with `wellFormed` applied to every string in it, keys included. The same value, not
231
+ * a copy, when nothing in it needed that.
232
+ */
233
+ export function wellFormedJson<T>(value: T): T {
234
+ if (typeof value === "string") return wellFormed(value) as T;
235
+ if (Array.isArray(value)) {
236
+ let changed = false;
237
+ const items = value.map((item: unknown) => {
238
+ const fixed = wellFormedJson(item);
239
+ if (fixed !== item) changed = true;
240
+ return fixed;
241
+ });
242
+ return (changed ? items : value) as T;
243
+ }
244
+ if (value !== null && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
245
+ let changed = false;
246
+ const entries = Object.entries(value).map(([key, item]): [string, unknown] => {
247
+ const fixedKey = wellFormed(key);
248
+ const fixed = wellFormedJson(item);
249
+ if (fixedKey !== key || fixed !== item) changed = true;
250
+ return [fixedKey, fixed];
251
+ });
252
+ return (changed ? Object.fromEntries(entries) : value) as T;
253
+ }
254
+ return value;
255
+ }
256
+
48
257
  /**
49
258
  * Splits lines longer than `limit`, preferring a break after whitespace or punctuation near the
50
259
  * end of each piece. Minified JSON or a PDF paragraph becomes many addressable lines.
51
260
  */
52
261
  export function wrapLongLines(text: string, limit = MAX_LINE_CHARACTERS): { text: string; wrapped: number } {
262
+ // Most files have no long line: then the text is used as it is, without splitting and joining it.
263
+ let longest = 0;
264
+ let start = 0;
265
+ for (let end = text.indexOf("\n"); ; end = text.indexOf("\n", start)) {
266
+ const stop = end === -1 ? text.length : end;
267
+ if (stop - start > longest) longest = stop - start;
268
+ if (end === -1 || longest > limit) break;
269
+ start = end + 1;
270
+ }
271
+ if (longest <= limit) return { text, wrapped: 0 };
53
272
  let wrapped = 0;
54
273
  const lines = text.split("\n");
55
274
  const out: string[] = [];
@@ -113,13 +332,20 @@ const SYMBOL = 1; // Dashes, quotes, arrows, box drawing, and anything unclassif
113
332
  * of random letters in a single case with no digits (about 70% of the real count).
114
333
  */
115
334
  export function estimateTokens(text: string): number {
116
- let tokens = 0;
335
+ return Math.ceil(tokensIn(text, 0, text.length, 0));
336
+ }
337
+
338
+ /**
339
+ * The tokens of `text` from `from` to `to`, added to `tokens`. Every count starts again after a line
340
+ * break, so a text cut after line breaks gives, piece by piece, the sum it gives whole.
341
+ */
342
+ function tokensIn(text: string, from: number, to: number, tokens: number): number {
117
343
  // The current run of ASCII letters: its length since the last case change, and its casing.
118
344
  let piece = 0;
119
345
  let capitalsInARow = 0;
120
346
  let previousWasLower = false;
121
347
  let previous = 0; // 1 = space, 2 = ASCII punctuation, 0 = anything else
122
- for (let index = 0; index < text.length; index++) {
348
+ for (let index = from; index < to; index++) {
123
349
  const code = text.charCodeAt(index);
124
350
  if ((code >= 97 && code <= 122) || (code >= 65 && code <= 90)) {
125
351
  const capital = code <= 90;
@@ -176,7 +402,7 @@ export function estimateTokens(text: string): number {
176
402
  else if (code < 0xff00) tokens += OTHER_SCRIPT;
177
403
  else tokens += KANA;
178
404
  }
179
- return Math.ceil(tokens);
405
+ return tokens;
180
406
  }
181
407
 
182
408
  /**
@@ -187,9 +413,15 @@ export function estimateTokens(text: string): number {
187
413
  * quarter or more, a novel by a hundredth.
188
414
  */
189
415
  export function textSizes(text: string): { utf8: number; json: number } {
416
+ const { utf8, escapes } = sizesIn(text, 0, text.length);
417
+ return { utf8, json: utf8 + escapes + 2 };
418
+ }
419
+
420
+ /** UTF-8 bytes and JSON escapes of `text` from `from` to `to`, which must not split a surrogate pair. */
421
+ function sizesIn(text: string, from: number, to: number): { utf8: number; escapes: number } {
190
422
  let utf8 = 0;
191
423
  let escapes = 0;
192
- for (let index = 0; index < text.length; index++) {
424
+ for (let index = from; index < to; index++) {
193
425
  const code = text.charCodeAt(index);
194
426
  if (code < 0x80) {
195
427
  utf8 += 1;
@@ -197,7 +429,7 @@ export function textSizes(text: string): { utf8: number; json: number } {
197
429
  else if (code < 0x20) escapes += code === 0x0a || code === 0x09 || code === 0x0d || code === 0x08 || code === 0x0c ? 1 : 5;
198
430
  } else if (code < 0x800) {
199
431
  utf8 += 2;
200
- } else if (isHighSurrogate(code) && isLowSurrogate(text.charCodeAt(index + 1))) {
432
+ } else if (isHighSurrogate(code) && index + 1 < to && isLowSurrogate(text.charCodeAt(index + 1))) {
201
433
  utf8 += 4;
202
434
  index++;
203
435
  } else {
@@ -206,7 +438,85 @@ export function textSizes(text: string): { utf8: number; json: number } {
206
438
  if (code >= 0xd800 && code <= 0xdfff) escapes += 3;
207
439
  }
208
440
  }
209
- return { utf8, json: utf8 + escapes + 2 };
441
+ return { utf8, escapes };
442
+ }
443
+
444
+ /** Characters worked on between two looks at the clock while ingesting. */
445
+ const SLICE_CHARACTERS = 1 << 18;
446
+
447
+ /**
448
+ * The text cut into slices of about 256K characters, each ending after a line break (the last
449
+ * one at the end of the text), as `[from, to)` offsets.
450
+ */
451
+ function* lineSlices(text: string): Generator<[number, number]> {
452
+ for (let from = 0; from < text.length;) {
453
+ let to = Math.min(text.length, from + SLICE_CHARACTERS);
454
+ if (to < text.length) {
455
+ const newline = text.indexOf("\n", to - 1);
456
+ to = newline === -1 ? text.length : newline + 1;
457
+ }
458
+ yield [from, to];
459
+ from = to;
460
+ }
461
+ }
462
+
463
+ /**
464
+ * `estimateTokens` and `textSizes` of a text, the same numbers, worked out a slice at a time so
465
+ * that other requests get a turn while a large upload is measured. Slices end after a line break.
466
+ */
467
+ export async function measureText(text: string, slicer: TimeSlicer): Promise<{ tokens: number; utf8: number; json: number }> {
468
+ let tokens = 0;
469
+ let utf8 = 0;
470
+ let escapes = 0;
471
+ for (const [from, to] of lineSlices(text)) {
472
+ tokens = tokensIn(text, from, to, tokens);
473
+ const sizes = sizesIn(text, from, to);
474
+ utf8 += sizes.utf8;
475
+ escapes += sizes.escapes;
476
+ await slicer.maybePause();
477
+ }
478
+ return { tokens: Math.ceil(tokens), utf8, json: utf8 + escapes + 2 };
479
+ }
480
+
481
+ /**
482
+ * What ingest makes of extracted text, a slice at a time: `normalizeText`, then `wrapLongLines`,
483
+ * then the lines (a line break at the very end does not start another line). The same results as
484
+ * doing each in one go: no step of `normalizeText` reaches across a line break, and whether a U+0085
485
+ * ends lines is decided once, for the whole text. A slice that runs far past its size holds a long
486
+ * line: it is cleaned in pieces too. `onProgress` is told the characters of `raw` cleaned so far,
487
+ * after each slice; splitting the lines after that is quick, and is not counted.
488
+ */
489
+ export async function prepareText(
490
+ raw: string,
491
+ slicer: TimeSlicer,
492
+ onProgress?: (done: number, total: number) => void,
493
+ ): Promise<{ text: string; wrapped: number; lines: string[] }> {
494
+ const start = raw.charCodeAt(0) === 0xfeff ? 1 : 0;
495
+ const body = start === 1 ? raw.slice(1) : raw;
496
+ const nextLines = breaksAtNextLine(body);
497
+ const parts: string[] = [];
498
+ // A clean text (most logs) comes back as it is: joining its slices would copy all of it.
499
+ let changed = false;
500
+ for (const [from, to] of lineSlices(body)) {
501
+ const slice = body.slice(from, to);
502
+ const normalized = slice.length > 2 * SLICE_CHARACTERS ? await normalizeInPieces(slice, slicer, nextLines) : normalizeLines(slice, nextLines);
503
+ if (normalized !== slice) changed = true;
504
+ parts.push(normalized);
505
+ onProgress?.(start + to, raw.length);
506
+ await slicer.maybePause();
507
+ }
508
+ const { text, wrapped } = wrapLongLines(!changed ? body : parts.length === 1 ? parts[0]! : parts.join(""));
509
+ parts.length = 0;
510
+ await slicer.maybePause();
511
+ const lines: string[] = [];
512
+ for (const [from, to] of lineSlices(text)) {
513
+ const piece = text.slice(from, to).split("\n");
514
+ // A slice that ends with a line break splits into one empty string too many.
515
+ if (text.charCodeAt(to - 1) === 10) piece.pop();
516
+ for (const line of piece) lines.push(line);
517
+ await slicer.maybePause();
518
+ }
519
+ return { text, wrapped, lines };
210
520
  }
211
521
 
212
522
  /** UTF-8 byte length without allocating an encoded copy. */