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/dist/library.js CHANGED
@@ -1,26 +1,20 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { buildLogProfile, buildOutline, looksLikeLog } from "./analyze.js";
2
+ import { buildLogProfileInSlices, buildOutlineInSlices, looksLikeLog } from "./analyze.js";
3
+ import { givenBudget, resolveBudget } from "./budget.js";
3
4
  import { DocumentCache, documentVersion } from "./cache.js";
4
- import { DocumentStoreError } from "./errors.js";
5
+ import { DocumentStoreError, noteStoreWriteFailure } from "./errors.js";
6
+ import { EventEmitter, eventErrorOf, newRunId } from "./events.js";
5
7
  import { detectFormat, extractText } from "./extract.js";
6
8
  import { Limiter } from "./limiter.js";
9
+ import { TimeSlicer } from "./pause.js";
7
10
  import { canBeReadWhole, CARD_LINES, documentToolsInstruction, formatBytes, planDocuments, renderCard, renderInline } from "./plan.js";
8
11
  import { openRangedDocument, pieceKey } from "./ranged.js";
9
12
  import { numberLines, SearchableDocument } from "./search.js";
10
13
  import { DOCUMENT_ID_PATTERN } from "./stores.js";
11
- import { buildTextIndex, canSerialize, serializeTextIndex } from "./text-index.js";
12
- import { estimateTokens, normalizeText, textSizes, wrapLongLines } from "./text.js";
14
+ import { buildTextIndexInSlices, canSerialize, serializeTextIndex } from "./text-index.js";
15
+ import { measureText, prepareText, removeInvisible, sliceWhole, wellFormed } from "./text.js";
13
16
  import { createDocumentTools } from "./tools.js";
14
- /** Defaults sized for a 1M-token model behind a 10 MB request limit. */
15
- export const DEFAULT_BUDGET = {
16
- contextTokens: 1_000_000,
17
- maxRequestBytes: 10_000_000,
18
- inlineTokens: 200_000,
19
- reservedTokens: 64_000,
20
- mapChunkTokens: 100_000,
21
- maxMapChunks: 30,
22
- toolResultCharacters: 24_000,
23
- };
17
+ export { DEFAULT_BUDGET } from "./budget.js";
24
18
  export function isDocumentId(value) {
25
19
  return typeof value === "string" && DOCUMENT_ID_PATTERN.test(value);
26
20
  }
@@ -35,22 +29,72 @@ export function toDocumentSummary(meta) {
35
29
  lines: meta.lines,
36
30
  estimatedTokens: meta.estimatedTokens,
37
31
  ...(meta.pages ? { pages: meta.pages } : {}),
32
+ ...(meta.encoding ? { encoding: meta.encoding } : {}),
33
+ ...(meta.replacedCharacters ? { replacedCharacters: meta.replacedCharacters } : {}),
38
34
  expiresAt: meta.expiresAt,
39
35
  };
40
36
  }
37
+ /** An encoding's name as TextDecoder gives it ("windows-1255"): an extractor of your own may name another. */
38
+ const ENCODING_NAME = /^[a-z0-9][a-z0-9._:-]{0,39}$/i;
41
39
  /**
42
- * A file name as one printable line: the last path segment, without control characters, line
43
- * breaks, or text-direction overrides. Names are shown to the model and in UIs, so a name must
44
- * not be able to start a new line of the prompt or disguise its extension.
40
+ * Whether the name is an older encoding, as `DocumentMeta.encoding` records: not UTF-8 or UTF-16,
41
+ * under any of their names ("utf8", "unicode"). The model is told the file is not in UTF-8.
42
+ */
43
+ function olderEncoding(name) {
44
+ if (typeof name !== "string" || !ENCODING_NAME.test(name))
45
+ return false;
46
+ let known;
47
+ try {
48
+ known = new TextDecoder(name).encoding;
49
+ }
50
+ catch {
51
+ // A name TextDecoder does not know: the extractor read the file itself.
52
+ return true;
53
+ }
54
+ return known !== "utf-8" && known !== "utf-16le" && known !== "utf-16be";
55
+ }
56
+ /** How the text of a file was read, as its extractor said, in the fields of `DocumentMeta`. */
57
+ function readingOf(extracted) {
58
+ const { encoding, replacedCharacters } = extracted;
59
+ return {
60
+ ...(olderEncoding(encoding) ? { encoding } : {}),
61
+ ...(typeof replacedCharacters === "number" && Number.isSafeInteger(replacedCharacters) && replacedCharacters > 0 ? { replacedCharacters } : {}),
62
+ };
63
+ }
64
+ /**
65
+ * A file name as one printable line: the last path segment. Control characters, line and paragraph
66
+ * separators, and text-direction controls (the marks of right-to-left text included) become a space.
67
+ * Names are shown to the model and in UIs, so a name must not be able to start a new line of the
68
+ * prompt, or disguise its extension. Most characters that show nothing are removed (tag characters,
69
+ * zero-width spaces); the variation selectors and joiners that scripts and emoji need are kept, and
70
+ * can still carry data a person does not see.
45
71
  */
46
72
  export function cleanFileName(raw) {
47
73
  const base = raw.split(/[\\/]/).at(-1) ?? "";
48
- return base
49
- // Control characters, line and paragraph separators, and text-direction controls.
50
- .replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]+/gu, " ")
51
- .replace(/\s+/g, " ")
52
- .trim()
53
- .slice(0, 255) || "file";
74
+ // Control characters, line and paragraph separators, and text-direction controls become a space.
75
+ const spaced = base.replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]+/gu, " ");
76
+ const name = removeInvisible(spaced).replace(/\s+/g, " ").trim();
77
+ // At most 255 characters, never half of an emoji. A flag cut short loses the tags left of it.
78
+ return (name.length > 255 ? removeInvisible(sliceWhole(name, 255)) : name) || "file";
79
+ }
80
+ /**
81
+ * Metadata with a whole file name. 0.5.0 and earlier cut a long name at 255 UTF-16 units, at times
82
+ * inside an emoji, and stored it: half of a character is sent as a replacement character, never on
83
+ * its own (Claude's API refuses it). Metadata whose name is whole comes back as it is.
84
+ */
85
+ function wholeName(meta) {
86
+ const name = wellFormed(meta.name);
87
+ return name === meta.name ? meta : { ...meta, name };
88
+ }
89
+ /**
90
+ * Refuses an owner that every caller without a user would share: an empty string (what
91
+ * `user?.id ?? ""` gives), one of spaces only, or null. Undefined is no owner. A number is let
92
+ * through, as before, for JavaScript code that passes numeric user IDs.
93
+ */
94
+ export function checkOwner(owner) {
95
+ if (owner === undefined || (typeof owner === "string" && owner.trim() !== "") || (typeof owner === "number" && Number.isFinite(owner)))
96
+ return;
97
+ throw new TypeError("owner must be a string that is not empty or only spaces, such as the signed-in user's ID. To let anyone with the document's ID use it, leave owner out.");
54
98
  }
55
99
  /**
56
100
  * A read of the store. Whatever it throws is passed on as a `DocumentStoreError`: a store that
@@ -74,12 +118,152 @@ function allowed(meta, access) {
74
118
  }
75
119
  /** Default for `cacheBytes`. */
76
120
  export const DEFAULT_CACHE_BYTES = 256 * 1024 * 1024;
121
+ /** The refusal of a file whose text is larger than `maxTextBytes`. */
122
+ const tooMuchText = (name, maxTextBytes) => new Error(`${name} holds more than ${formatBytes(maxTextBytes)} of text, more than is kept from one file. Split it, and attach the part you need.`);
123
+ /** Default for `maxPdfPages`. */
124
+ export const DEFAULT_MAX_PDF_PAGES = 5_000;
125
+ /** Default for `maxTextBytes`, when `maxUploadBytes` is not larger: 100 MB. */
126
+ export const DEFAULT_MAX_TEXT_BYTES = 100 * 1024 * 1024;
127
+ /** Default for `ingestTimeoutMs`: 2 minutes. */
128
+ export const DEFAULT_INGEST_TIMEOUT_MS = 120_000;
129
+ /** The longest a Node.js timer waits: a longer one fires at once. A limit past it is no limit. */
130
+ const LONGEST_TIMER_MS = 2 ** 31 - 1;
131
+ /** A time limit in the words of a message: "500 ms", "45 s", "2 min". */
132
+ function formatDuration(ms) {
133
+ if (ms < 1_000)
134
+ return `${Math.max(1, Math.round(ms))} ms`;
135
+ if (ms < 120_000)
136
+ return `${Number((ms / 1_000).toFixed(1))} s`;
137
+ return `${Number((ms / 60_000).toFixed(1))} min`;
138
+ }
139
+ /**
140
+ * The signal one ingest runs under: aborted when the caller's is, or when `timeoutMs` has passed
141
+ * (with an error that says the file took too long). `dispose` stops the timer.
142
+ */
143
+ function ingestSignal(name, caller, timeoutMs) {
144
+ const controller = new AbortController();
145
+ const onAbort = () => controller.abort(caller.reason);
146
+ if (caller?.aborted)
147
+ controller.abort(caller.reason);
148
+ else
149
+ caller?.addEventListener("abort", onAbort, { once: true });
150
+ const timer = timeoutMs > 0 && timeoutMs <= LONGEST_TIMER_MS
151
+ ? setTimeout(() => controller.abort(new Error(`${name} took too long to read (more than ${formatDuration(timeoutMs)}). Split it, or save it as plain text, and attach that.`)), timeoutMs)
152
+ : undefined;
153
+ return {
154
+ signal: controller.signal,
155
+ dispose() {
156
+ clearTimeout(timer);
157
+ caller?.removeEventListener("abort", onAbort);
158
+ },
159
+ };
160
+ }
161
+ /**
162
+ * `work`, or the signal's reason as soon as it is aborted: an extractor of your own that does not
163
+ * look at the signal is no longer waited for (though the work it does cannot be stopped).
164
+ */
165
+ function untilAborted(work, signal) {
166
+ if (signal.aborted)
167
+ return Promise.reject(signal.reason);
168
+ return new Promise((resolve, reject) => {
169
+ const onAbort = () => reject(signal.reason);
170
+ signal.addEventListener("abort", onAbort, { once: true });
171
+ work.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
172
+ });
173
+ }
174
+ /** The message of `ingest.error` when the store failed to write the document. */
175
+ const STORE_WRITE_FAILED = "The document could not be stored. Try again later.";
176
+ /** The least time between two `ingest.progress` events of one stage, in milliseconds: a slice of `TimeSlicer`. */
177
+ const PROGRESS_MS = 12;
178
+ const EXTRACT_STAGES = new Set(["extract", "check", "pictures", "decode"]);
179
+ const EXTRACT_UNITS = new Set(["pages", "parts", "bytes"]);
180
+ const isCount = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
181
+ /** What `ingest.start` says of an ingest, worked out from whatever it was given: the checks come after it. */
182
+ function startOf(input) {
183
+ try {
184
+ const name = typeof input?.name === "string" ? cleanFileName(input.name) : "";
185
+ const mimeType = (typeof input?.mimeType === "string" ? input.mimeType.trim() : "") || "application/octet-stream";
186
+ const bytes = input?.bytes?.byteLength;
187
+ return { name, format: detectFormat(name, mimeType), bytes: isCount(bytes) ? bytes : 0 };
188
+ }
189
+ catch {
190
+ return { name: "", format: "text", bytes: 0 };
191
+ }
192
+ }
193
+ /**
194
+ * Sends the `ingest.progress` events of one ingest: at most one every `PROGRESS_MS` for each stage,
195
+ * however the stages take turns, then the last progress of each stage when the stages end (`end`).
196
+ * A progress that completes its stage goes out at once, the first time, so that stages that run one
197
+ * after the other end in that order. Made only when someone listens.
198
+ */
199
+ class IngestProgress {
200
+ events;
201
+ /** Each stage that reported, in the order it first did: when it last sent, and its last progress. */
202
+ stages = new Map();
203
+ /** Set once a stage after the extractor's began: an extract stage is not reported again. */
204
+ extractOver = false;
205
+ constructor(events) {
206
+ this.events = events;
207
+ }
208
+ report(stage, done, total, unit) {
209
+ if (!EXTRACT_STAGES.has(stage))
210
+ this.extractOver = true;
211
+ const last = { done, total, unit, sent: false };
212
+ let state = this.stages.get(stage);
213
+ if (!state) {
214
+ state = { sentAt: Number.NEGATIVE_INFINITY, completed: false, last };
215
+ this.stages.set(stage, state);
216
+ }
217
+ state.last = last;
218
+ const now = performance.now();
219
+ const completes = !state.completed && total !== undefined && done >= total;
220
+ if (completes)
221
+ state.completed = true;
222
+ if (completes || now - state.sentAt >= PROGRESS_MS) {
223
+ state.sentAt = now;
224
+ this.send(stage, last);
225
+ }
226
+ }
227
+ /** The progress an extractor reported (`ExtractInput.onProgress`). One of your own may send anything: what does not fit is left out. */
228
+ extracted(progress) {
229
+ if (this.extractOver)
230
+ return;
231
+ const stage = progress?.stage ?? "extract";
232
+ if (!EXTRACT_STAGES.has(stage) || !EXTRACT_UNITS.has(progress?.unit) || !isCount(progress?.done))
233
+ return;
234
+ this.report(stage, progress.done, isCount(progress.total) ? progress.total : undefined, progress.unit);
235
+ }
236
+ /** The stages so far are over: the last progress of each, when it was held back, goes out, in the order they began. */
237
+ end() {
238
+ const held = [...this.stages].filter(([, state]) => !state.last.sent);
239
+ this.stages.clear();
240
+ for (const [stage, state] of held)
241
+ this.send(stage, state.last);
242
+ }
243
+ send(stage, last) {
244
+ last.sent = true;
245
+ this.events.emit({
246
+ type: "ingest.progress",
247
+ stage,
248
+ done: last.done,
249
+ ...(last.total !== undefined ? { total: last.total } : {}),
250
+ unit: last.unit,
251
+ });
252
+ }
253
+ }
77
254
  /** Default for `wholeDocumentBytes`. */
78
255
  export const DEFAULT_WHOLE_DOCUMENT_BYTES = 2 * 1024 * 1024;
79
256
  export function createLargeFiles(options) {
80
- const budget = { ...DEFAULT_BUDGET, ...options.budget };
257
+ /** The fields the application set. The others follow the context window, whichever it is for a request. */
258
+ const ownBudget = givenBudget(options.budget);
259
+ const budget = resolveBudget(ownBudget);
260
+ const budgetFor = (overrides, limits) => (overrides || limits ? resolveBudget({ ...ownBudget, ...givenBudget(overrides) }, limits) : budget);
81
261
  const ttlMs = options.ttlMs ?? 72 * 60 * 60 * 1000;
82
262
  const maxUploadBytes = options.maxUploadBytes ?? 100 * 1024 * 1024;
263
+ const given = (value, fallback) => (typeof value === "number" && !Number.isNaN(value) ? value : fallback);
264
+ const maxTextBytes = Math.max(1, given(options.maxTextBytes, Math.max(maxUploadBytes, DEFAULT_MAX_TEXT_BYTES)));
265
+ const maxPdfPages = Math.max(1, Math.trunc(given(options.maxPdfPages, DEFAULT_MAX_PDF_PAGES)));
266
+ const ingestTimeoutMs = given(options.ingestTimeoutMs, DEFAULT_INGEST_TIMEOUT_MS);
83
267
  const now = options.now ?? (() => new Date());
84
268
  const { store } = options;
85
269
  const cacheBytes = Math.max(0, options.cacheBytes ?? DEFAULT_CACHE_BYTES);
@@ -134,7 +318,7 @@ export function createLargeFiles(options) {
134
318
  forget(id);
135
319
  return undefined;
136
320
  }
137
- return meta;
321
+ return wholeName(meta);
138
322
  }
139
323
  /**
140
324
  * A document ready to read and search. The store is asked first, every time: a kept copy is
@@ -167,13 +351,16 @@ export function createLargeFiles(options) {
167
351
  return openRangedDocument(ranged, meta, scan, { ignoreSavedIndex: rebuild });
168
352
  }
169
353
  const stored = await reading(() => store.get(id));
170
- return stored ? new SearchableDocument(stored) : undefined;
354
+ if (!stored)
355
+ return undefined;
356
+ const named = wholeName(stored.meta);
357
+ return new SearchableDocument(named === stored.meta ? stored : { ...stored, meta: named });
171
358
  }
172
359
  /**
173
360
  * What a document contributes to the prompt: its text, or its card. Undefined when it is gone
174
361
  * by now. A copy found to disagree with the store is opened again once.
175
362
  */
176
- async function block(id, meta, whole, viewable, readableWhole) {
363
+ async function block(id, meta, whole, viewable, wholeRead) {
177
364
  for (let attempt = 0; attempt < 2; attempt++) {
178
365
  const document = await load(id, attempt === 0 ? meta : undefined);
179
366
  if (!document)
@@ -181,7 +368,7 @@ export function createLargeFiles(options) {
181
368
  try {
182
369
  return whole
183
370
  ? renderInline(document.meta, await document.readText())
184
- : renderCard(document.meta, numberLines(await document.readLines(1, CARD_LINES), 1), viewable, readableWhole);
371
+ : renderCard(document.meta, numberLines(await document.readLines(1, CARD_LINES), 1), viewable, wholeRead);
185
372
  }
186
373
  catch (error) {
187
374
  if (!document.broken) {
@@ -198,80 +385,192 @@ export function createLargeFiles(options) {
198
385
  const meta = await currentMeta(id);
199
386
  return meta && allowed(meta, access) ? meta : undefined;
200
387
  }
201
- return {
202
- budget,
203
- maxUploadBytes,
204
- async ingest(input) {
205
- const name = cleanFileName(input.name);
206
- const mimeType = input.mimeType?.trim() || "application/octet-stream";
207
- if (input.bytes.byteLength === 0)
208
- throw new Error(`${name} is empty.`);
209
- if (input.bytes.byteLength > maxUploadBytes) {
210
- throw new Error(`${name} is larger than the ${formatBytes(maxUploadBytes)} upload limit.`);
211
- }
212
- let format = detectFormat(name, mimeType);
213
- const extracted = await extractText(input.bytes, {
214
- name,
215
- mimeType,
216
- format,
217
- // A scan is worth storing only if its pages can be shown later: that needs the file itself.
218
- ...(format === "pdf" && keeps(format) && scannedPdfPages > 0 ? { scannedPages: scannedPdfPages } : {}),
219
- }, options.extractors);
220
- const { text, wrapped } = wrapLongLines(normalizeText(extracted.text));
388
+ /**
389
+ * The work of `ingest`, once the file is named: `detected` is the format its name and type say.
390
+ * `progress` is given when someone listens to the events of the ingest. `storeFailed` is called
391
+ * when the store fails to write the document, whatever it throws.
392
+ */
393
+ async function ingestFile(input, name, mimeType, detected, progress, storeFailed) {
394
+ if (input.bytes.byteLength === 0)
395
+ throw new Error(`${name} is empty.`);
396
+ if (input.bytes.byteLength > maxUploadBytes) {
397
+ throw new Error(`${name} is larger than the ${formatBytes(maxUploadBytes)} upload limit.`);
398
+ }
399
+ let format = detected;
400
+ const { signal, dispose } = ingestSignal(name, input.signal, ingestTimeoutMs);
401
+ // Each long step works in slices, with pauses for other requests: one large upload no longer
402
+ // holds the whole server while it is read.
403
+ const slicer = new TimeSlicer(signal);
404
+ let pages;
405
+ let reading;
406
+ let text;
407
+ let wrapped;
408
+ let lines;
409
+ let measured;
410
+ let outline;
411
+ let logProfile;
412
+ let index;
413
+ try {
414
+ signal.throwIfAborted();
415
+ // In a function of its own, so that the text as extracted is let go once it is prepared:
416
+ // the steps after it hold only the prepared text.
417
+ const read = async () => {
418
+ // What an extractor of your own reports once it has settled (from a timer, a worker) is
419
+ // not reported: the stages after it have begun.
420
+ let extracting = true;
421
+ let extracted;
422
+ try {
423
+ extracted = await untilAborted(extractText(input.bytes, {
424
+ name,
425
+ mimeType,
426
+ format,
427
+ // A scan is worth storing only if its pages can be shown later: that needs the file itself.
428
+ ...(format === "pdf" && keeps(format) && scannedPdfPages > 0 ? { scannedPages: scannedPdfPages } : {}),
429
+ signal,
430
+ maxTextBytes,
431
+ maxPages: maxPdfPages,
432
+ ...(progress ? { onProgress: (report) => { if (extracting)
433
+ progress.extracted(report); } } : {}),
434
+ }, options.extractors), signal);
435
+ }
436
+ finally {
437
+ extracting = false;
438
+ }
439
+ progress?.end();
440
+ // A character is at least one byte: a text this long is too large whatever it holds.
441
+ if (extracted.text.length > maxTextBytes)
442
+ throw tooMuchText(name, maxTextBytes);
443
+ await slicer.pauseNow();
444
+ return { pages: extracted.pages, reading: readingOf(extracted), ...await prepareText(extracted.text, slicer, progress && ((done, total) => progress.report("prepare", done, total, "characters"))) };
445
+ };
446
+ ({ pages, reading, text, wrapped, lines } = await read());
447
+ progress?.end();
221
448
  if (!text.trim())
222
449
  throw new Error(`${name} did not contain any text.`);
223
- const lines = text.split("\n");
224
- if (text.endsWith("\n"))
225
- lines.pop();
226
450
  if (format === "text" && looksLikeLog(lines))
227
451
  format = "log";
228
- const created = now();
229
- const expires = created.getTime() + ttlMs;
230
- const sizes = textSizes(text);
231
- const keepOriginal = keeps(format);
232
- const meta = {
233
- id: `doc_${randomUUID().replaceAll("-", "")}`,
234
- ...(input.owner !== undefined ? { owner: input.owner } : {}),
235
- name,
236
- mimeType,
237
- format,
238
- bytes: input.bytes.byteLength,
239
- textBytes: sizes.utf8,
240
- jsonBytes: sizes.json,
241
- characters: text.length,
242
- lines: lines.length,
243
- estimatedTokens: estimateTokens(text),
244
- wrappedLines: wrapped,
245
- ...(extracted.pages ? { pages: extracted.pages } : {}),
246
- ...(keepOriginal ? { originalKept: true } : {}),
247
- outline: buildOutline(lines, format),
248
- ...(format === "log" ? { logProfile: buildLogProfile(lines) } : {}),
249
- createdAt: created.toISOString(),
250
- // Never, for a time to live without end (or one that runs past what a date can hold).
251
- expiresAt: expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString(),
252
- };
452
+ measured = await measureText(text, slicer);
453
+ if (measured.utf8 > maxTextBytes)
454
+ throw tooMuchText(name, maxTextBytes);
455
+ outline = await buildOutlineInSlices(lines, format, slicer);
456
+ logProfile = format === "log" ? await buildLogProfileInSlices(lines, slicer) : undefined;
253
457
  // The line index, so that the text can be read by range: a few bytes a line, built from the
254
458
  // UTF-8 bytes the store writes. Kept by any store that can keep it, even one this library
255
459
  // then loads whole, so that switching to reading by range finds it ready.
256
- const index = typeof store.putIndex === "function" ? buildTextIndex(text) : undefined;
257
- const savedIndex = index && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters
258
- ? serializeTextIndex(index)
460
+ index = typeof store.putIndex === "function"
461
+ ? await buildTextIndexInSlices(text, slicer, progress && ((done, total) => progress.report("index", done, total, "characters")))
259
462
  : undefined;
463
+ progress?.end();
464
+ signal.throwIfAborted();
465
+ }
466
+ finally {
467
+ dispose();
468
+ }
469
+ const created = now();
470
+ const expires = created.getTime() + ttlMs;
471
+ const keepOriginal = keeps(format);
472
+ const meta = {
473
+ id: `doc_${randomUUID().replaceAll("-", "")}`,
474
+ ...(input.owner !== undefined ? { owner: input.owner } : {}),
475
+ name,
476
+ mimeType,
477
+ format,
478
+ bytes: input.bytes.byteLength,
479
+ textBytes: measured.utf8,
480
+ jsonBytes: measured.json,
481
+ characters: text.length,
482
+ lines: lines.length,
483
+ estimatedTokens: measured.tokens,
484
+ wrappedLines: wrapped,
485
+ ...(pages ? { pages } : {}),
486
+ ...reading,
487
+ ...(keepOriginal ? { originalKept: true } : {}),
488
+ outline,
489
+ ...(logProfile ? { logProfile } : {}),
490
+ createdAt: created.toISOString(),
491
+ // Never, for a time to live without end (or one that runs past what a date can hold).
492
+ expiresAt: expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString(),
493
+ };
494
+ const savedIndex = index && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters
495
+ ? serializeTextIndex(index)
496
+ : undefined;
497
+ // Each write is reported once done. What the listener of the events throws is not the store's failure.
498
+ const writes = (keepOriginal ? 1 : 0) + (savedIndex ? 1 : 0) + 1;
499
+ let written = 0;
500
+ let listenerFailed;
501
+ const wrote = (last) => {
502
+ if (!progress)
503
+ return;
504
+ try {
505
+ progress.report("store", ++written, writes, "parts");
506
+ if (last)
507
+ progress.end();
508
+ }
509
+ catch (error) {
510
+ listenerFailed = { error };
511
+ throw error;
512
+ }
513
+ };
514
+ try {
515
+ // The files first, the document last: a document is there once its metadata is.
516
+ if (keepOriginal) {
517
+ await store.putOriginal(meta.id, input.bytes);
518
+ wrote(false);
519
+ }
520
+ if (savedIndex) {
521
+ await store.putIndex(meta.id, savedIndex);
522
+ wrote(false);
523
+ }
524
+ await store.put({ meta, text });
525
+ wrote(true);
526
+ }
527
+ catch (error) {
528
+ // Do not leave a file of up to the upload limit, or a part of one, behind for a document
529
+ // that does not exist.
530
+ await store.delete(meta.id).catch(() => undefined);
531
+ if (listenerFailed?.error !== error) {
532
+ noteStoreWriteFailure(error);
533
+ storeFailed();
534
+ }
535
+ throw error;
536
+ }
537
+ return meta;
538
+ }
539
+ return {
540
+ budget,
541
+ budgetFor,
542
+ maxUploadBytes,
543
+ async ingest(input) {
544
+ // The events first, so that every ingest that throws, even on what it was given, ends with ingest.error.
545
+ const events = new EventEmitter(input?.runId ?? newRunId("ing"), input?.onEvent);
546
+ let storeFailed = false;
260
547
  try {
261
- // The files first, the document last: a document is there once its metadata is.
262
- if (keepOriginal)
263
- await store.putOriginal(meta.id, input.bytes);
264
- if (savedIndex)
265
- await store.putIndex(meta.id, savedIndex);
266
- await store.put({ meta, text });
548
+ if (events.active)
549
+ events.emit({ type: "ingest.start", ...startOf(input) });
550
+ checkOwner(input.owner);
551
+ const name = cleanFileName(input.name);
552
+ const mimeType = input.mimeType?.trim() || "application/octet-stream";
553
+ const format = detectFormat(name, mimeType);
554
+ // Progress is worked out only for someone who listens.
555
+ const progress = events.active ? new IngestProgress(events) : undefined;
556
+ const meta = await ingestFile(input, name, mimeType, format, progress, () => (storeFailed = true));
557
+ try {
558
+ events.emit({ type: "ingest.finish", document: toDocumentSummary(meta) });
559
+ }
560
+ catch (error) {
561
+ // The caller never gets the id: the document goes, as on a throw of the listener a moment earlier.
562
+ await store.delete(meta.id).catch(() => undefined);
563
+ forget(meta.id);
564
+ throw error;
565
+ }
566
+ return meta;
267
567
  }
268
568
  catch (error) {
269
- // Do not leave a file of up to the upload limit, or a part of one, behind for a document
270
- // that does not exist.
271
- await store.delete(meta.id).catch(() => undefined);
569
+ // A store's own error may name a host or a path, whatever it is: the event, which a browser
570
+ // may see, says only that the document could not be stored.
571
+ events.emit({ type: "ingest.error", error: storeFailed ? { message: STORE_WRITE_FAILED } : eventErrorOf(error) });
272
572
  throw error;
273
573
  }
274
- return meta;
275
574
  },
276
575
  getMeta: metaFor,
277
576
  async getOriginal(id, access) {
@@ -288,6 +587,8 @@ export function createLargeFiles(options) {
288
587
  return options.store.sweep?.(now()) ?? 0;
289
588
  },
290
589
  async prepare(ids, base, access) {
590
+ const budget = budgetFor(access?.budget);
591
+ const analysis = access?.wholeDocumentAnalysis !== false;
291
592
  const unique = [...new Set(ids)];
292
593
  let documents = [];
293
594
  const missing = [];
@@ -313,15 +614,17 @@ export function createLargeFiles(options) {
313
614
  const blocks = new Map();
314
615
  const gone = [];
315
616
  for (const meta of documents) {
316
- const text = await block(meta.id, meta, inline.has(meta.id), shown.has(meta.id), canBeReadWhole(meta, budget));
617
+ const wholeRead = !analysis ? "not_offered" : canBeReadWhole(meta, budget) ? "offered" : "too_large";
618
+ const text = await block(meta.id, meta, inline.has(meta.id), shown.has(meta.id), wholeRead);
317
619
  if (text === undefined)
318
620
  gone.push(meta.id);
319
621
  else
320
622
  blocks.set(meta.id, text);
321
623
  }
322
624
  if (gone.length === 0) {
323
- // A whole-document read is named only when one of the files is small enough for it.
324
- const wholeReads = plan.searchable.some((meta) => canBeReadWhole(meta, budget));
625
+ // A whole-document read is named only when the tools have it, and one of the files is
626
+ // small enough for it.
627
+ const wholeReads = analysis && plan.searchable.some((meta) => canBeReadWhole(meta, budget));
325
628
  return { plan, blocks, instruction: documentToolsInstruction(plan.searchable, viewable, wholeReads), missing, viewable };
326
629
  }
327
630
  missing.push(...gone);
@@ -329,15 +632,30 @@ export function createLargeFiles(options) {
329
632
  }
330
633
  },
331
634
  tools(documents, toolOptions = {}) {
332
- const { viewPages, ...rest } = toolOptions;
635
+ const { viewPages, budget: overrides, ...rest } = toolOptions;
636
+ const budget = budgetFor(overrides);
333
637
  const viewable = (loadOriginal ? (viewPages === true ? documents : viewPages || []) : [])
334
638
  .filter((meta) => meta.format === "pdf" && meta.originalKept);
639
+ // The owner each document was handed in with. The store's owner is checked against it on
640
+ // every call, so metadata built from an ID alone cannot read another owner's document: such
641
+ // a document is answered as no longer available, as `getMeta` reports it missing.
642
+ const handedOwner = new Map([...documents, ...viewable].map((meta) => [meta.id, meta.owner]));
643
+ const mayUse = (meta) => meta.owner === undefined || (handedOwner.has(meta.id) && meta.owner === handedOwner.get(meta.id));
644
+ // The metadata the store holds now, not that of a copy kept in memory.
645
+ const checkedLoad = async (id) => {
646
+ const meta = await currentMeta(id);
647
+ return meta && mayUse(meta) ? load(id, meta) : undefined;
648
+ };
649
+ const checkedOriginal = loadOriginal && (async (id) => {
650
+ const meta = await currentMeta(id);
651
+ return meta && mayUse(meta) ? loadOriginal(id) : undefined;
652
+ });
335
653
  return createDocumentTools({
336
- load,
654
+ load: checkedLoad,
337
655
  documentIds: documents.map((meta) => meta.id),
338
- names: Object.fromEntries([...documents, ...viewable].map((meta) => [meta.id, meta.name])),
656
+ names: Object.fromEntries([...documents, ...viewable].map((meta) => [meta.id, wellFormed(meta.name)])),
339
657
  budget,
340
- ...(loadOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal } : {}),
658
+ ...(checkedOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal: checkedOriginal } : {}),
341
659
  // `analyze_whole_document` is declared only when it can read at least one of the documents.
342
660
  wholeReads: documents.some((meta) => canBeReadWhole(meta, budget)),
343
661
  ...rest,