llm-large-files 0.8.2 → 0.9.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 (201) hide show
  1. package/CHANGELOG.md +535 -0
  2. package/README.md +9 -10
  3. package/dist/access.d.ts +86 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +131 -0
  6. package/dist/access.js.map +1 -0
  7. package/dist/ask.d.ts +45 -1
  8. package/dist/ask.d.ts.map +1 -1
  9. package/dist/ask.js +181 -20
  10. package/dist/ask.js.map +1 -1
  11. package/dist/cache.d.ts +12 -3
  12. package/dist/cache.d.ts.map +1 -1
  13. package/dist/cache.js +18 -5
  14. package/dist/cache.js.map +1 -1
  15. package/dist/encoding.js +5 -3
  16. package/dist/encoding.js.map +1 -1
  17. package/dist/error-info.d.ts +57 -0
  18. package/dist/error-info.d.ts.map +1 -0
  19. package/dist/error-info.js +217 -0
  20. package/dist/error-info.js.map +1 -0
  21. package/dist/errors.d.ts +72 -8
  22. package/dist/errors.d.ts.map +1 -1
  23. package/dist/errors.js +102 -15
  24. package/dist/errors.js.map +1 -1
  25. package/dist/events.d.ts +35 -9
  26. package/dist/events.d.ts.map +1 -1
  27. package/dist/events.js +42 -11
  28. package/dist/events.js.map +1 -1
  29. package/dist/evidence.d.ts +4 -2
  30. package/dist/evidence.d.ts.map +1 -1
  31. package/dist/evidence.js +14 -3
  32. package/dist/evidence.js.map +1 -1
  33. package/dist/extract.d.ts +32 -8
  34. package/dist/extract.d.ts.map +1 -1
  35. package/dist/extract.js +46 -35
  36. package/dist/extract.js.map +1 -1
  37. package/dist/gemini/adapter.d.ts +19 -3
  38. package/dist/gemini/adapter.d.ts.map +1 -1
  39. package/dist/gemini/adapter.js +84 -12
  40. package/dist/gemini/adapter.js.map +1 -1
  41. package/dist/gemini/chat.d.ts +18 -6
  42. package/dist/gemini/chat.d.ts.map +1 -1
  43. package/dist/gemini/chat.js +2 -0
  44. package/dist/gemini/chat.js.map +1 -1
  45. package/dist/gemini/index.d.ts +1 -1
  46. package/dist/gemini/index.d.ts.map +1 -1
  47. package/dist/index.d.ts +9 -6
  48. package/dist/index.d.ts.map +1 -1
  49. package/dist/index.js +4 -3
  50. package/dist/index.js.map +1 -1
  51. package/dist/ingest.d.ts +70 -0
  52. package/dist/ingest.d.ts.map +1 -0
  53. package/dist/ingest.js +868 -0
  54. package/dist/ingest.js.map +1 -0
  55. package/dist/library.d.ts +169 -34
  56. package/dist/library.d.ts.map +1 -1
  57. package/dist/library.js +324 -591
  58. package/dist/library.js.map +1 -1
  59. package/dist/map-reduce.js +3 -3
  60. package/dist/map-reduce.js.map +1 -1
  61. package/dist/model.d.ts +43 -2
  62. package/dist/model.d.ts.map +1 -1
  63. package/dist/model.js +63 -3
  64. package/dist/model.js.map +1 -1
  65. package/dist/node/handlers.d.ts +226 -14
  66. package/dist/node/handlers.d.ts.map +1 -1
  67. package/dist/node/handlers.js +423 -181
  68. package/dist/node/handlers.js.map +1 -1
  69. package/dist/node/index.d.ts +3 -2
  70. package/dist/node/index.d.ts.map +1 -1
  71. package/dist/node/index.js +2 -1
  72. package/dist/node/index.js.map +1 -1
  73. package/dist/node/ingest-child.d.ts +7 -1
  74. package/dist/node/ingest-child.d.ts.map +1 -1
  75. package/dist/node/ingest-child.js +18 -3
  76. package/dist/node/ingest-child.js.map +1 -1
  77. package/dist/node/isolated.d.ts +3 -1
  78. package/dist/node/isolated.d.ts.map +1 -1
  79. package/dist/node/isolated.js +11 -4
  80. package/dist/node/isolated.js.map +1 -1
  81. package/dist/node/originals.d.ts +19 -0
  82. package/dist/node/originals.d.ts.map +1 -0
  83. package/dist/node/originals.js +82 -0
  84. package/dist/node/originals.js.map +1 -0
  85. package/dist/node/spool.d.ts +102 -0
  86. package/dist/node/spool.d.ts.map +1 -0
  87. package/dist/node/spool.js +365 -0
  88. package/dist/node/spool.js.map +1 -0
  89. package/dist/node/sse.d.ts +4 -3
  90. package/dist/node/sse.d.ts.map +1 -1
  91. package/dist/node/sse.js +7 -6
  92. package/dist/node/sse.js.map +1 -1
  93. package/dist/pdf-layout.d.ts.map +1 -1
  94. package/dist/pdf-layout.js +71 -12
  95. package/dist/pdf-layout.js.map +1 -1
  96. package/dist/ranged.d.ts +15 -11
  97. package/dist/ranged.d.ts.map +1 -1
  98. package/dist/ranged.js +42 -11
  99. package/dist/ranged.js.map +1 -1
  100. package/dist/retry.d.ts +3 -1
  101. package/dist/retry.d.ts.map +1 -1
  102. package/dist/retry.js +6 -2
  103. package/dist/retry.js.map +1 -1
  104. package/dist/scope.d.ts +25 -0
  105. package/dist/scope.d.ts.map +1 -0
  106. package/dist/scope.js +60 -0
  107. package/dist/scope.js.map +1 -0
  108. package/dist/source.d.ts +60 -0
  109. package/dist/source.d.ts.map +1 -0
  110. package/dist/source.js +170 -0
  111. package/dist/source.js.map +1 -0
  112. package/dist/stores.d.ts +120 -31
  113. package/dist/stores.d.ts.map +1 -1
  114. package/dist/stores.js +582 -139
  115. package/dist/stores.js.map +1 -1
  116. package/dist/testing/fake-fetch.d.ts +31 -0
  117. package/dist/testing/fake-fetch.d.ts.map +1 -0
  118. package/dist/testing/fake-fetch.js +66 -0
  119. package/dist/testing/fake-fetch.js.map +1 -0
  120. package/dist/testing/fake-model.d.ts +38 -0
  121. package/dist/testing/fake-model.d.ts.map +1 -0
  122. package/dist/testing/fake-model.js +62 -0
  123. package/dist/testing/fake-model.js.map +1 -0
  124. package/dist/testing/index.d.ts +7 -0
  125. package/dist/testing/index.d.ts.map +1 -0
  126. package/dist/testing/index.js +9 -0
  127. package/dist/testing/index.js.map +1 -0
  128. package/dist/testing/store-checks.d.ts +72 -0
  129. package/dist/testing/store-checks.d.ts.map +1 -0
  130. package/dist/testing/store-checks.js +619 -0
  131. package/dist/testing/store-checks.js.map +1 -0
  132. package/dist/tools.d.ts +25 -0
  133. package/dist/tools.d.ts.map +1 -1
  134. package/dist/tools.js +135 -13
  135. package/dist/tools.js.map +1 -1
  136. package/dist/types.d.ts +116 -13
  137. package/dist/types.d.ts.map +1 -1
  138. package/docs/README.md +17 -8
  139. package/docs/getting-started.md +18 -13
  140. package/docs/guides/anthropic.md +12 -8
  141. package/docs/guides/conversations.md +112 -47
  142. package/docs/guides/costs-and-limits.md +16 -7
  143. package/docs/guides/deployment.md +284 -83
  144. package/docs/guides/errors-and-reliability.md +161 -23
  145. package/docs/guides/own-adapter-and-loop.md +27 -10
  146. package/docs/guides/pdfs.md +123 -29
  147. package/docs/guides/storage.md +633 -145
  148. package/docs/guides/testing.md +78 -129
  149. package/docs/guides/vertex-and-gemini.md +10 -7
  150. package/docs/guides/web-app.md +312 -78
  151. package/docs/how-it-works.md +35 -8
  152. package/docs/measurements.md +43 -8
  153. package/docs/publishing.md +112 -36
  154. package/docs/reference/ask.md +154 -13
  155. package/docs/reference/errors-and-retries.md +166 -14
  156. package/docs/reference/events.md +53 -20
  157. package/docs/reference/gemini.md +70 -21
  158. package/docs/reference/library.md +706 -165
  159. package/docs/reference/node.md +624 -110
  160. package/docs/reference/testing.md +311 -0
  161. package/docs/reference/tools.md +15 -5
  162. package/docs/security.md +304 -67
  163. package/docs/troubleshooting.md +144 -65
  164. package/docs/upgrading-0.9.md +890 -0
  165. package/package.json +12 -3
  166. package/src/access.ts +144 -0
  167. package/src/ask.ts +230 -19
  168. package/src/cache.ts +20 -5
  169. package/src/encoding.ts +6 -4
  170. package/src/error-info.ts +255 -0
  171. package/src/errors.ts +129 -15
  172. package/src/events.ts +86 -21
  173. package/src/evidence.ts +14 -3
  174. package/src/extract.ts +50 -33
  175. package/src/gemini/adapter.ts +97 -11
  176. package/src/gemini/chat.ts +20 -6
  177. package/src/gemini/index.ts +1 -1
  178. package/src/index.ts +9 -6
  179. package/src/ingest.ts +927 -0
  180. package/src/library.ts +467 -601
  181. package/src/map-reduce.ts +3 -3
  182. package/src/model.ts +69 -5
  183. package/src/node/handlers.ts +630 -183
  184. package/src/node/index.ts +13 -2
  185. package/src/node/ingest-child.ts +23 -5
  186. package/src/node/isolated.ts +11 -4
  187. package/src/node/originals.ts +78 -0
  188. package/src/node/spool.ts +365 -0
  189. package/src/node/sse.ts +7 -6
  190. package/src/pdf-layout.ts +69 -11
  191. package/src/ranged.ts +34 -13
  192. package/src/retry.ts +6 -2
  193. package/src/scope.ts +63 -0
  194. package/src/source.ts +178 -0
  195. package/src/stores.ts +635 -140
  196. package/src/testing/fake-fetch.ts +80 -0
  197. package/src/testing/fake-model.ts +78 -0
  198. package/src/testing/index.ts +11 -0
  199. package/src/testing/store-checks.ts +660 -0
  200. package/src/tools.ts +150 -14
  201. package/src/types.ts +106 -13
package/dist/library.js CHANGED
@@ -1,82 +1,25 @@
1
- import { randomUUID } from "node:crypto";
2
- import { buildLogProfileInSlices, buildOutlineInSlices, looksLikeLog } from "./analyze.js";
1
+ import { callerOf, checkMetaVersion, documentContext, mayUse, metaOf, OWNER_REQUIRED, SCOPE_REQUIRED, storeCall, storeContext } from "./access.js";
3
2
  import { givenBudget, resolveBudget } from "./budget.js";
4
3
  import { DocumentCache, documentVersion } from "./cache.js";
5
- import { DocumentStoreError, isStoreWriteFailure, noteStoreWriteFailure, toIngestError } from "./errors.js";
6
- import { EventEmitter, eventErrorOf, newRunId } from "./events.js";
7
- import { detectFormat, extractText } from "./extract.js";
4
+ import { ingestDocument, LONGEST_TIMER_MS } from "./ingest.js";
8
5
  import { Limiter } from "./limiter.js";
9
- import { TimeSlicer } from "./pause.js";
10
- import { canBeReadWhole, CARD_LINES, documentToolsInstruction, formatBytes, planDocuments, renderCard, renderInline, TABLE_FORMATS } from "./plan.js";
11
- import { measureQuality } from "./quality.js";
12
- import { DocumentGoneError, openRangedDocument, pieceKey } from "./ranged.js";
6
+ import { canBeReadWhole, CARD_LINES, documentToolsInstruction, planDocuments, renderCard, renderInline, TABLE_FORMATS } from "./plan.js";
7
+ import { DocumentGoneError, openRangedDocument, pieceKey, RangedDocument } from "./ranged.js";
13
8
  import { numberLines, SearchableDocument } from "./search.js";
14
- import { DOCUMENT_ID_PATTERN } from "./stores.js";
15
- import { buildTextIndexInSlices, canSerialize, serializeTextIndex } from "./text-index.js";
16
- import { measureText, prepareText, removeInvisible, sliceWhole, wellFormed } from "./text.js";
9
+ import { TimeSlicer } from "./pause.js";
10
+ import { checkScope } from "./scope.js";
11
+ import { isSha256, sha256InSlices } from "./source.js";
12
+ import { APP_DOCUMENT_ID_PATTERN } from "./stores.js";
13
+ import { wellFormed } from "./text.js";
17
14
  import { createDocumentTools } from "./tools.js";
18
15
  export { DEFAULT_BUDGET } from "./budget.js";
19
- export function isDocumentId(value) {
20
- return typeof value === "string" && DOCUMENT_ID_PATTERN.test(value);
21
- }
22
- /** The fields of a document that are safe to return to a browser. */
23
- export function toDocumentSummary(meta) {
24
- return {
25
- id: meta.id,
26
- name: meta.name,
27
- mimeType: meta.mimeType,
28
- format: meta.format,
29
- bytes: meta.bytes,
30
- lines: meta.lines,
31
- estimatedTokens: meta.estimatedTokens,
32
- ...(meta.pages ? { pages: meta.pages } : {}),
33
- ...(meta.encoding ? { encoding: meta.encoding } : {}),
34
- ...(meta.replacedCharacters ? { replacedCharacters: meta.replacedCharacters } : {}),
35
- expiresAt: meta.expiresAt,
36
- };
37
- }
38
- /** An encoding's name as TextDecoder gives it ("windows-1255"): an extractor of your own may name another. */
39
- const ENCODING_NAME = /^[a-z0-9][a-z0-9._:-]{0,39}$/i;
40
- /**
41
- * Whether the name is an older encoding, as `DocumentMeta.encoding` records: not UTF-8 or UTF-16,
42
- * under any of their names ("utf8", "unicode"). The model is told the file is not in UTF-8.
43
- */
44
- function olderEncoding(name) {
45
- if (typeof name !== "string" || !ENCODING_NAME.test(name))
46
- return false;
47
- let known;
48
- try {
49
- known = new TextDecoder(name).encoding;
50
- }
51
- catch {
52
- // A name TextDecoder does not know: the extractor read the file itself.
53
- return true;
54
- }
55
- return known !== "utf-8" && known !== "utf-16le" && known !== "utf-16be";
56
- }
57
- /** How the text of a file was read, as its extractor said, in the fields of `DocumentMeta`. */
58
- function readingOf(extracted) {
59
- const { encoding, replacedCharacters } = extracted;
60
- return {
61
- ...(olderEncoding(encoding) ? { encoding } : {}),
62
- ...(typeof replacedCharacters === "number" && Number.isSafeInteger(replacedCharacters) && replacedCharacters > 0 ? { replacedCharacters } : {}),
63
- };
64
- }
16
+ export { checkOwner, cleanFileName, cleanMimeType, NEVER_EXPIRES, toDocumentSummary } from "./ingest.js";
65
17
  /**
66
- * A file name as one printable line: the last path segment. Control characters, line and paragraph
67
- * separators, and text-direction controls (the marks of right-to-left text included) become a space.
68
- * Names are shown to the model and in UIs, so a name must not be able to start a new line of the
69
- * prompt, or disguise its extension. Most characters that show nothing are removed (tag characters,
70
- * zero-width spaces); the variation selectors and joiners that scripts and emoji need are kept, and
71
- * can still carry data a person does not see.
18
+ * Whether `value` has the shape of a document ID: one the library makes ("doc_" and 32 hex digits),
19
+ * or one an application may give (`APP_DOCUMENT_ID_PATTERN`, since 0.9.0), which the library's fit too.
72
20
  */
73
- export function cleanFileName(raw) {
74
- const base = raw.split(/[\\/]/).at(-1) ?? "";
75
- // Control characters, line and paragraph separators, and text-direction controls become a space.
76
- const spaced = base.replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]+/gu, " ");
77
- const name = removeInvisible(spaced).replace(/\s+/g, " ").trim();
78
- // At most 255 characters, never half of an emoji. A flag cut short loses the tags left of it.
79
- return (name.length > 255 ? removeInvisible(sliceWhole(name, 255)) : name) || "file";
21
+ export function isDocumentId(value) {
22
+ return typeof value === "string" && APP_DOCUMENT_ID_PATTERN.test(value);
80
23
  }
81
24
  /**
82
25
  * Metadata with a whole file name. 0.5.0 and earlier cut a long name at 255 UTF-16 units, at times
@@ -87,224 +30,50 @@ function wholeName(meta) {
87
30
  const name = wellFormed(meta.name);
88
31
  return name === meta.name ? meta : { ...meta, name };
89
32
  }
90
- /**
91
- * Refuses an owner that every caller without a user would share: an empty string (what
92
- * `user?.id ?? ""` gives), one of spaces only, or null. Undefined is no owner. A number is let
93
- * through, as before, for JavaScript code that passes numeric user IDs.
94
- */
95
- export function checkOwner(owner) {
96
- if (owner === undefined || (typeof owner === "string" && owner.trim() !== "") || (typeof owner === "number" && Number.isFinite(owner)))
97
- return;
98
- 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.");
99
- }
100
33
  /**
101
34
  * A read of the store. Whatever it throws is passed on as a `DocumentStoreError`: a store that
102
35
  * could not be read is not a document that is gone, and its own error names paths or hosts.
103
36
  */
104
- async function reading(read) {
105
- try {
106
- return await read();
107
- }
108
- catch (error) {
109
- throw error instanceof DocumentStoreError ? error : new DocumentStoreError(error);
110
- }
37
+ function reading(read) {
38
+ return storeCall("read", read);
111
39
  }
40
+ /** The key a caller's copy of a document is kept under in memory: the key of its scope, then the ID. */
41
+ const documentKey = (caller, id) => `${caller.key}\u0000${id}`;
42
+ /** A caller with no owner and no scope. */
43
+ const NO_CALLER = Object.freeze({ context: storeContext(undefined, undefined), key: "" });
112
44
  /**
113
- * The `expiresAt` of a document that never expires (`ttlMs: Infinity`): the last instant of the
114
- * year 9999. A date, so that every comparison, and a server of an older version, reads it as any other.
45
+ * What `view_pages` answers for a file the application keeps (`IngestInput.original`) that is no
46
+ * longer the one that was ingested. New in 0.9.0.
115
47
  */
116
- export const NEVER_EXPIRES = "9999-12-31T23:59:59.999Z";
117
- function allowed(meta, access) {
118
- return meta.owner === undefined || meta.owner === access?.owner;
48
+ const changedOriginal = (file) => `${file} changed on the server since it was read. Attach it again to look at its pages.`;
49
+ /**
50
+ * Where the application keeps the uploaded file of a document (`DocumentMeta.original`), when its
51
+ * metadata says so in the shape the library writes. Undefined for one kept in the store, and for
52
+ * one written by hand in another shape, which reads as missing.
53
+ */
54
+ function refOf(meta) {
55
+ const original = meta.original;
56
+ if (typeof original !== "object" || original === null)
57
+ return undefined;
58
+ const { ref, bytes, sha256 } = original;
59
+ return typeof ref === "string" && ref.length > 0 && typeof bytes === "number" && Number.isSafeInteger(bytes) && bytes >= 0 && isSha256(sha256)
60
+ ? { ref, bytes, sha256 }
61
+ : undefined;
119
62
  }
120
63
  /** Default for `cacheBytes`. */
121
64
  export const DEFAULT_CACHE_BYTES = 256 * 1024 * 1024;
122
- /** The refusal of a file whose text is larger than `maxTextBytes`. */
123
- 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.`);
124
65
  /** Default for `maxPdfPages`. */
125
66
  export const DEFAULT_MAX_PDF_PAGES = 5_000;
126
67
  /** Default for `maxTextBytes`, when `maxUploadBytes` is not larger: 100 MB. */
127
68
  export const DEFAULT_MAX_TEXT_BYTES = 100 * 1024 * 1024;
128
69
  /** Default for `ingestTimeoutMs`: 2 minutes. */
129
70
  export const DEFAULT_INGEST_TIMEOUT_MS = 120_000;
130
- /** The longest a Node.js timer waits: a longer one fires at once. A limit past it is no limit. */
131
- const LONGEST_TIMER_MS = 2 ** 31 - 1;
132
- /** `value` copied through JSON: new strings, none of them a piece of a larger one. */
133
- function jsonCopy(value) {
134
- return JSON.parse(JSON.stringify(value));
135
- }
136
- /** `work`, or the error `late` makes once `ms` have passed without it settling. */
137
- function settleWithin(work, ms, late) {
138
- let timer;
139
- const timeUp = new Promise((_, reject) => {
140
- timer = setTimeout(() => reject(late()), ms);
141
- });
142
- return Promise.race([work, timeUp]).finally(() => clearTimeout(timer));
143
- }
144
- /**
145
- * The turn of one ingest (`maxConcurrentIngests`). It is given back when the ingest ends; when the
146
- * ingest gave up on work that goes on (an extractor that does not stop on the signal, such as a
147
- * PDF being parsed when its caller left), once that work ends, or `capMs` later when it does not.
148
- * (Store writes that do not end fail the ingest after `capMs`: see `ingestFile`.)
149
- */
150
- class IngestSlot {
151
- release;
152
- capMs;
153
- released = false;
154
- timer;
155
- constructor(release, capMs) {
156
- this.release = release;
157
- this.capMs = capMs;
158
- }
159
- free = () => {
160
- if (this.released)
161
- return;
162
- this.released = true;
163
- clearTimeout(this.timer);
164
- this.release();
165
- };
166
- /**
167
- * Gives the turn back `capMs` from now at the latest. The timer keeps the process alive: work
168
- * that never ends may hold nothing that does, and ingests waiting for the turn would be lost.
169
- */
170
- limit() {
171
- if (this.released || this.timer !== undefined)
172
- return;
173
- this.timer = setTimeout(this.free, this.capMs);
174
- }
175
- /** The ingest is over: the turn goes back now, or once `abandoned` ends (`capMs` at the latest). */
176
- end(abandoned) {
177
- if (!abandoned)
178
- return this.free();
179
- abandoned.then(this.free, this.free);
180
- this.limit();
181
- }
182
- }
183
- /** A time limit in the words of a message: "500 ms", "45 s", "2 min". */
184
- function formatDuration(ms) {
185
- if (ms < 1_000)
186
- return `${Math.max(1, Math.round(ms))} ms`;
187
- if (ms < 120_000)
188
- return `${Number((ms / 1_000).toFixed(1))} s`;
189
- return `${Number((ms / 60_000).toFixed(1))} min`;
190
- }
191
- /**
192
- * The signal one ingest runs under: aborted when the caller's is, or when `timeoutMs` has passed
193
- * (with an error that says the file took too long). `dispose` stops the timer.
194
- */
195
- function ingestSignal(name, caller, timeoutMs) {
196
- const controller = new AbortController();
197
- const onAbort = () => controller.abort(caller.reason);
198
- if (caller?.aborted)
199
- controller.abort(caller.reason);
200
- else
201
- caller?.addEventListener("abort", onAbort, { once: true });
202
- const timer = timeoutMs > 0 && timeoutMs <= LONGEST_TIMER_MS
203
- ? 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)
204
- : undefined;
205
- return {
206
- signal: controller.signal,
207
- dispose() {
208
- clearTimeout(timer);
209
- caller?.removeEventListener("abort", onAbort);
210
- },
211
- };
212
- }
213
- /**
214
- * `work`, or the signal's reason as soon as it is aborted: an extractor of your own that does not
215
- * look at the signal is no longer waited for (though the work it does cannot be stopped).
216
- */
217
- function untilAborted(work, signal) {
218
- if (signal.aborted)
219
- return Promise.reject(signal.reason);
220
- return new Promise((resolve, reject) => {
221
- const onAbort = () => reject(signal.reason);
222
- signal.addEventListener("abort", onAbort, { once: true });
223
- work.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
224
- });
225
- }
226
- /** The message of `ingest.error` when the store failed to write the document. */
227
- const STORE_WRITE_FAILED = "The document could not be stored. Try again later.";
228
- /** The least time between two `ingest.progress` events of one stage, in milliseconds: a slice of `TimeSlicer`. */
229
- const PROGRESS_MS = 12;
230
- const EXTRACT_STAGES = new Set(["extract", "check", "pictures", "decode"]);
231
- const EXTRACT_UNITS = new Set(["pages", "parts", "bytes"]);
232
- const isCount = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
233
- /** What `ingest.start` says of an ingest, worked out from whatever it was given: the checks come after it. */
234
- function startOf(input) {
235
- try {
236
- const name = typeof input?.name === "string" ? cleanFileName(input.name) : "";
237
- const mimeType = (typeof input?.mimeType === "string" ? input.mimeType.trim() : "") || "application/octet-stream";
238
- const bytes = input?.bytes?.byteLength;
239
- return { name, format: detectFormat(name, mimeType), bytes: isCount(bytes) ? bytes : 0 };
240
- }
241
- catch {
242
- return { name: "", format: "text", bytes: 0 };
243
- }
244
- }
245
- /**
246
- * Sends the `ingest.progress` events of one ingest: at most one every `PROGRESS_MS` for each stage,
247
- * however the stages take turns, then the last progress of each stage when the stages end (`end`).
248
- * A progress that completes its stage goes out at once, the first time, so that stages that run one
249
- * after the other end in that order. Made only when someone listens.
250
- */
251
- class IngestProgress {
252
- events;
253
- /** Each stage that reported, in the order it first did: when it last sent, and its last progress. */
254
- stages = new Map();
255
- /** Set once a stage after the extractor's began: an extract stage is not reported again. */
256
- extractOver = false;
257
- constructor(events) {
258
- this.events = events;
259
- }
260
- report(stage, done, total, unit) {
261
- if (!EXTRACT_STAGES.has(stage))
262
- this.extractOver = true;
263
- const last = { done, total, unit, sent: false };
264
- let state = this.stages.get(stage);
265
- if (!state) {
266
- state = { sentAt: Number.NEGATIVE_INFINITY, completed: false, last };
267
- this.stages.set(stage, state);
268
- }
269
- state.last = last;
270
- const now = performance.now();
271
- const completes = !state.completed && total !== undefined && done >= total;
272
- if (completes)
273
- state.completed = true;
274
- if (completes || now - state.sentAt >= PROGRESS_MS) {
275
- state.sentAt = now;
276
- this.send(stage, last);
277
- }
278
- }
279
- /** The progress an extractor reported (`ExtractInput.onProgress`). One of your own may send anything: what does not fit is left out. */
280
- extracted(progress) {
281
- if (this.extractOver)
282
- return;
283
- const stage = progress?.stage ?? "extract";
284
- if (!EXTRACT_STAGES.has(stage) || !EXTRACT_UNITS.has(progress?.unit) || !isCount(progress?.done))
285
- return;
286
- this.report(stage, progress.done, isCount(progress.total) ? progress.total : undefined, progress.unit);
287
- }
288
- /** The stages so far are over: the last progress of each, when it was held back, goes out, in the order they began. */
289
- end() {
290
- const held = [...this.stages].filter(([, state]) => !state.last.sent);
291
- this.stages.clear();
292
- for (const [stage, state] of held)
293
- this.send(stage, state.last);
294
- }
295
- send(stage, last) {
296
- last.sent = true;
297
- this.events.emit({
298
- type: "ingest.progress",
299
- stage,
300
- done: last.done,
301
- ...(last.total !== undefined ? { total: last.total } : {}),
302
- unit: last.unit,
303
- });
304
- }
305
- }
306
71
  /** Default for `wholeDocumentBytes`. */
307
72
  export const DEFAULT_WHOLE_DOCUMENT_BYTES = 2 * 1024 * 1024;
73
+ /** Looks at pages that run at once in a library, unless `maxConcurrentPageLooks` says otherwise. */
74
+ const DEFAULT_PAGE_LOOKS = 1;
75
+ /** How long a look at pages waits for its turn, unless `pageLookWaitMs` says otherwise. */
76
+ const DEFAULT_PAGE_LOOK_WAIT_MS = 30_000;
308
77
  /**
309
78
  * A number option as it was given, or `fallback` when it was left out. NaN, which
310
79
  * `Number(process.env.X)` gives for a variable that is not set, and a value that is not a number
@@ -334,37 +103,64 @@ export function createLargeFiles(options) {
334
103
  const now = options.now ?? (() => new Date());
335
104
  const { store } = options;
336
105
  const cacheBytes = Math.max(0, numberOption("cacheBytes", options.cacheBytes, DEFAULT_CACHE_BYTES));
337
- /** Documents ready to search, and decoded pieces of documents read by range, in one memory budget. */
106
+ /** What every call must name (`requireOwner`, `requireScope`). */
107
+ const rules = Object.freeze({ requireOwner: options.requireOwner === true, requireScope: options.requireScope === true });
108
+ /**
109
+ * Documents ready to search, and decoded pieces of documents read by range, in one memory budget.
110
+ * Each is kept under the key of the caller's scope and the document's ID (`documentKey`): one ID
111
+ * in two scopes is two documents, and the copy of one is never served to the other. Its version
112
+ * (`documentVersion`) holds the document's owner and scope too, so a copy is not served to
113
+ * another owner either, once another document is stored under the same ID.
114
+ */
338
115
  const cache = new DocumentCache(cacheBytes, Math.max(0, Math.trunc(numberOption("cacheSize", options.cacheSize, Number.POSITIVE_INFINITY))));
339
- /** Forgets everything kept of a document: the document, and its pieces. */
116
+ /** Forgets everything kept of the document of one key (`documentKey`): the document, and its pieces. */
117
+ const forgetKey = (key) => {
118
+ cache.delete(key);
119
+ cache.deletePrefix(pieceKey(key, 0).slice(0, -1));
120
+ };
121
+ /** Whether `key` is that of document `id`, or of one of its pieces, in any scope. */
122
+ const keyOfId = (key, id) => {
123
+ const rest = key.slice(key.indexOf("\u0000") + 1);
124
+ return rest === id || rest.startsWith(`${id}#`);
125
+ };
126
+ /**
127
+ * Forgets everything kept of document `id`, in every scope: it was deleted, or written again.
128
+ * In a store that keeps no scopes apart, the copies of all scopes are of that one document.
129
+ */
340
130
  const forget = (id) => {
341
- cache.delete(id);
342
- cache.deletePrefix(pieceKey(id, 0).slice(0, -1));
131
+ cache.deleteWhere((key) => keyOfId(key, id));
132
+ for (const key of rebuildIndex)
133
+ if (keyOfId(key, id))
134
+ rebuildIndex.delete(key);
343
135
  };
344
136
  /** Documents being opened, so that calls arriving together open each one once. */
345
137
  const opening = new Map();
346
- /** The store, when large documents can be read from it by range rather than loaded whole. */
347
- const ranged = typeof store.readTextRange === "function" ? {
348
- readTextRange: (id, start, end) => reading(() => store.readTextRange(id, start, end)),
349
- ...(store.getIndex ? { getIndex: (id) => reading(() => store.getIndex(id)) } : {}),
350
- ...(store.putIndex ? { putIndex: (id, index) => store.putIndex(id, index) } : {}),
351
- } : undefined;
138
+ /**
139
+ * The store, to read the text of a document by range rather than load it whole: each call carries
140
+ * `context`: the caller's scope, and the document's owner when it has one (`documentContext`).
141
+ */
142
+ const rangeStore = (context) => ({
143
+ readTextRange: (id, start, end) => reading(() => store.readTextRange(id, start, end, context)),
144
+ ...(store.getIndex ? { getIndex: (id) => reading(() => store.getIndex(id, context)) } : {}),
145
+ ...(store.putIndex ? { putIndex: (id, index) => store.putIndex(id, index, context) } : {}),
146
+ });
352
147
  /** The uploaded file of a document, when the store keeps such files. */
353
- const loadOriginal = store.getOriginal ? (id) => reading(() => store.getOriginal(id)) : undefined;
148
+ const loadOriginal = (id, context) => reading(() => store.getOriginal(id, context));
354
149
  const wholeDocumentBytes = Math.max(0, numberOption("wholeDocumentBytes", options.wholeDocumentBytes, DEFAULT_WHOLE_DOCUMENT_BYTES));
355
- /** Documents whose saved index did not match their text: the next opening builds it from the text. */
150
+ /** Documents (by `documentKey`) whose saved index did not match their text: the next opening builds it from the text. */
356
151
  const rebuildIndex = new Set();
357
152
  const scan = {
358
153
  chunkBytes: Math.max(1, Math.trunc(numberOption("scanChunkBytes", options.scanChunkBytes, 1024 * 1024, true))),
359
154
  limiter: new Limiter(Math.max(1, Math.trunc(numberOption("maxConcurrentScans", options.maxConcurrentScans, 4)))),
360
- onBroken: (id) => {
361
- rebuildIndex.add(id);
362
- forget(id);
155
+ onBroken: (key) => {
156
+ rebuildIndex.add(key);
157
+ forgetKey(key);
363
158
  },
364
159
  pieces: {
365
160
  get: (key, version) => cache.get(key, version),
366
- // A piece belongs to its document: it is not one of the `cacheSize` documents, and leaves with it.
367
- set: (key, version, piece) => cache.set(key, version, piece, key.slice(0, key.indexOf("#"))),
161
+ // A piece belongs to its document: it is not one of the `cacheSize` documents, and leaves with
162
+ // it. The document's key is all before the last "#", which no ID holds, and no scope key either.
163
+ set: (key, version, piece) => cache.set(key, version, piece, key.slice(0, key.lastIndexOf("#"))),
368
164
  // A quarter of the cache: a few documents can be kept, and no one pushes out all the rest.
369
165
  maxDocumentBytes: cacheBytes / 4,
370
166
  },
@@ -374,70 +170,200 @@ export function createLargeFiles(options) {
374
170
  const ingests = new Limiter(Math.max(1, Math.trunc(numberOption("maxConcurrentIngests", options.maxConcurrentIngests, 2))));
375
171
  /** How long work an ingest waits on, or gave up on, may keep its turn (see `IngestSlot`). */
376
172
  const slotCapMs = ingestTimeoutMs > 0 && ingestTimeoutMs <= LONGEST_TIMER_MS ? ingestTimeoutMs : DEFAULT_INGEST_TIMEOUT_MS;
173
+ /**
174
+ * The looks at pages of every question of this library take their turns (`maxConcurrentPageLooks`).
175
+ * A look reads its original within the time the library gives its store calls (`slotCapMs`).
176
+ */
177
+ const pageLooks = {
178
+ limiter: new Limiter(Math.max(1, Math.trunc(numberOption("maxConcurrentPageLooks", options.maxConcurrentPageLooks, DEFAULT_PAGE_LOOKS)))),
179
+ waitMs: Math.max(0, numberOption("pageLookWaitMs", options.pageLookWaitMs, DEFAULT_PAGE_LOOK_WAIT_MS)),
180
+ holdMs: slotCapMs,
181
+ };
377
182
  const scannedPdfPages = Math.max(0, Math.trunc(numberOption("scannedPdfPages", options.scannedPdfPages, 30)));
378
- /** Whether the uploaded file of a document of this format is kept. */
379
- const keeps = (format) => keepOriginals.has(format) && typeof options.store.putOriginal === "function";
183
+ const { originals } = options;
184
+ if (originals !== undefined && (typeof originals !== "object" || originals === null || typeof originals.read !== "function")) {
185
+ throw new TypeError("originals must be an object with a read(ref, context) method, such as fileOriginals(root) gives.");
186
+ }
187
+ /**
188
+ * Whether the uploaded file of a document of this format is kept: by its ref (`IngestInput.original`),
189
+ * which `originals` reads back, or as a copy in the store (`putOriginal`).
190
+ */
191
+ const keeps = (format, byRef) => keepOriginals.has(format) && (byRef ? originals !== undefined : typeof store.putOriginal === "function");
192
+ /**
193
+ * Whether the original of a document, which its metadata says is kept, can be read: by its ref,
194
+ * through `originals`, or from the store (`getOriginal`).
195
+ */
196
+ const readable = (meta) => (meta.original !== undefined && meta.original !== null ? originals !== undefined : typeof store.getOriginal === "function");
197
+ /** Whether `view_pages` can show the pages of a document: a PDF whose original is kept, and can be read. */
198
+ const viewableMeta = (meta) => meta.format === "pdf" && meta.originalKept === true && readable(meta);
199
+ /** What `ingest` (src/ingest.ts) needs of this library. */
200
+ const ingestContext = {
201
+ store,
202
+ now,
203
+ ttlMs,
204
+ maxUploadBytes,
205
+ maxTextBytes,
206
+ maxPdfPages,
207
+ ingestTimeoutMs,
208
+ scannedPdfPages,
209
+ // Read at each ingest, as before the move: an application may set them after.
210
+ get extractors() {
211
+ return options.extractors;
212
+ },
213
+ ingests,
214
+ slotCapMs,
215
+ keeps,
216
+ readsRefs: originals !== undefined,
217
+ forget,
218
+ rules,
219
+ ingesting: new Set(),
220
+ };
380
221
  /**
381
- * The document as the store describes it now: undefined when it was never there, has been
382
- * deleted (by this server or another one sharing the store), or has expired.
222
+ * The document as the store describes it now, asked with the caller's context: undefined when it
223
+ * was never there, has been deleted (by this server or another one sharing the store), or has
224
+ * expired. Whether the caller may use it is `metaFor`'s to say.
383
225
  */
384
- async function currentMeta(id) {
226
+ async function currentMeta(id, caller) {
385
227
  if (!isDocumentId(id))
386
228
  return undefined;
387
- const meta = await reading(() => store.getMeta(id));
229
+ const meta = metaOf(await reading(() => store.getMeta(id, caller.context)), id);
230
+ if (meta)
231
+ checkMetaVersion(meta);
388
232
  if (!meta || Date.parse(meta.expiresAt) <= now().getTime()) {
389
- forget(id);
233
+ forgetKey(documentKey(caller, id));
390
234
  return undefined;
391
235
  }
392
236
  return wholeName(meta);
393
237
  }
238
+ /** The document, when `caller` may use it: one of another owner or scope is missing, not forbidden. */
239
+ async function metaFor(id, caller) {
240
+ const meta = await currentMeta(id, caller);
241
+ return meta && mayUse(meta, caller, rules) ? meta : undefined;
242
+ }
394
243
  /**
395
- * A document ready to read and search. The store is asked first, every time: a kept copy is
396
- * used only while the store still has the same document. `known` is metadata just read from
397
- * the store, to save asking twice.
244
+ * A document ready to read and search, for `caller`, who may use it. The store is asked first,
245
+ * every time: a kept copy is used only while the store still has the same document. `known` is
246
+ * metadata just read from the store and checked, to save asking twice.
398
247
  */
399
- async function load(id, known) {
400
- const meta = known ?? await currentMeta(id);
248
+ async function load(id, caller, known) {
249
+ const meta = known ?? await metaFor(id, caller);
401
250
  if (!meta)
402
251
  return undefined;
252
+ const key = documentKey(caller, id);
403
253
  const version = documentVersion(meta);
404
- const cached = cache.get(id, version);
254
+ const cached = cache.get(key, version);
405
255
  if (cached && !cached.broken)
406
256
  return cached;
407
- const key = `${id}|${version}`;
408
- let pending = opening.get(key);
257
+ const opened = `${key}|${version}`;
258
+ let pending = opening.get(opened);
409
259
  if (!pending) {
410
- pending = open(id, meta).finally(() => opening.delete(key));
411
- opening.set(key, pending);
260
+ pending = open(id, meta, caller, key).finally(() => opening.delete(opened));
261
+ opening.set(opened, pending);
412
262
  }
413
263
  const document = await pending;
414
264
  if (document)
415
- cache.set(id, version, document);
265
+ cache.set(key, version, document);
416
266
  return document;
417
267
  }
418
- /** Reads a document from the store: its index, to read it by range, or all of it. */
419
- async function open(id, meta) {
420
- if (ranged && meta.textBytes > wholeDocumentBytes) {
421
- const rebuild = rebuildIndex.delete(id);
422
- return openRangedDocument(ranged, meta, scan, { ignoreSavedIndex: rebuild });
268
+ /**
269
+ * Reads a document from the store: its index, to read it by range, or all of it. `meta` is what
270
+ * `metaFor` found for `caller`. The reads carry the caller's scope, and the document's owner when it
271
+ * has one (`documentContext`): the copy is kept for every caller of the scope.
272
+ */
273
+ async function open(id, meta, caller, key) {
274
+ const context = documentContext(meta, caller);
275
+ if (typeof store.readTextRange === "function" && meta.textBytes > wholeDocumentBytes) {
276
+ const rebuild = rebuildIndex.delete(key);
277
+ return openRangedDocument(rangeStore(context), meta, scan, { ignoreSavedIndex: rebuild, key });
423
278
  }
424
- const stored = await reading(() => store.get(id));
425
- if (!stored)
279
+ const stored = await reading(() => store.get(id, context));
280
+ // Another document is not this one: the metadata `get` gives must be of this ID, owner and
281
+ // scope, and of the version `meta` is (not one deleted and stored again since, by another
282
+ // server, nor one a store of your own gave from the wrong scope). And the text must be the one
283
+ // that metadata describes, of its length and its number of lines: a store that writes the text
284
+ // and the metadata apart can give one document's metadata with another's text (two servers that
285
+ // ingest one ID at once, a file read between two writes). A document read by range is checked
286
+ // too: its index against the metadata, and the end of its text against its index
287
+ // (openRangedDocument). Missing, as for a caller who may not use it.
288
+ const found = stored ? metaOf(stored.meta, id) : undefined;
289
+ if (!stored || !found || !mayUse(found, caller, rules) || documentVersion(found) !== documentVersion(meta))
290
+ return undefined;
291
+ if (typeof stored.text !== "string" || stored.text.length !== found.characters)
426
292
  return undefined;
427
- const named = wholeName(stored.meta);
428
- return new SearchableDocument(named === stored.meta ? stored : { ...stored, meta: named });
293
+ const named = wholeName(found);
294
+ const document = new SearchableDocument(named === stored.meta ? stored : { ...stored, meta: named });
295
+ return document.lineCount === found.lines ? document : undefined;
296
+ }
297
+ /**
298
+ * The uploaded file of document `id`, which `meta`, checked for `caller`, says is kept: read from
299
+ * where the application keeps it (`meta.original`, through `originals`), or from the store. Another
300
+ * server may delete the document and store another under its ID while the bytes are read: so the
301
+ * store is asked again once they are. "missing" unless it still describes the same document, of
302
+ * the same owner and scope, and the bytes are the size of the file that was ingested, and have its
303
+ * SHA-256 when it is known (0.9.0): a store that gives back other bytes of the same size is caught
304
+ * too. "changed" for a file kept by the application that is no longer the one that was ingested:
305
+ * of another size or another SHA-256.
306
+ */
307
+ async function originalOf(id, caller, meta) {
308
+ const kept = refOf(meta);
309
+ let read;
310
+ if (kept) {
311
+ if (!originals)
312
+ return "missing";
313
+ const context = Object.freeze({ ...caller.context, id, bytes: kept.bytes });
314
+ read = await reading(() => originals.read(kept.ref, context));
315
+ }
316
+ else {
317
+ if (meta.original !== undefined && meta.original !== null)
318
+ return "missing";
319
+ if (!store.getOriginal)
320
+ return "missing";
321
+ read = await loadOriginal(id, caller.context);
322
+ }
323
+ if (!read)
324
+ return "missing";
325
+ const bytes = read;
326
+ const after = await metaFor(id, caller);
327
+ if (!after || documentVersion(after) !== documentVersion(meta))
328
+ return "missing";
329
+ // The SHA-256 of a file of up to the upload limit is taken a slice at a time.
330
+ const same = async (sha256) => await sha256InSlices(bytes, new TimeSlicer()) === sha256;
331
+ if (kept)
332
+ return bytes.byteLength === kept.bytes && await same(kept.sha256) ? bytes : "changed";
333
+ if (bytes.byteLength !== meta.bytes)
334
+ return "missing";
335
+ return typeof meta.sha256 === "string" && !await same(meta.sha256) ? "missing" : bytes;
336
+ }
337
+ /**
338
+ * Whether `document`, which a call of `caller` has just read, is still the one the store describes
339
+ * for `caller`. A document loaded whole was checked as it was read (see `open`). The bytes of one
340
+ * read by range carry nothing to check them by, and another server, or this one, may delete the
341
+ * document and store another under its ID while they are read, or between the look-up and the
342
+ * reads: so the store is asked again once they are, as `originalOf` does. When it no longer
343
+ * describes the same document, of the same owner and scope, what was read may be another's: the
344
+ * copy kept of it, read from the store too, is forgotten, and the read is missing.
345
+ */
346
+ async function stillOpened(document, caller) {
347
+ if (!(document instanceof RangedDocument))
348
+ return true;
349
+ const after = await metaFor(document.meta.id, caller);
350
+ if (after && documentVersion(after) === documentVersion(document.meta))
351
+ return true;
352
+ forgetKey(documentKey(caller, document.meta.id));
353
+ return false;
429
354
  }
430
355
  /**
431
356
  * What a document contributes to the prompt: its text, or its card. Undefined when it is gone
432
357
  * by now. A copy found to disagree with the store is opened again once.
433
358
  */
434
- async function block(id, meta, whole, viewable, wholeRead) {
359
+ async function block(id, meta, caller, whole, viewable, wholeRead) {
435
360
  for (let attempt = 0; attempt < 2; attempt++) {
436
- const document = await load(id, attempt === 0 ? meta : undefined);
361
+ const document = await load(id, caller, attempt === 0 ? meta : undefined);
437
362
  if (!document)
438
363
  return undefined;
364
+ let text;
439
365
  try {
440
- return whole
366
+ text = whole
441
367
  ? renderInline(document.meta, await document.readText())
442
368
  : renderCard(document.meta, numberLines(await document.readLines(1, CARD_LINES), 1), viewable, wholeRead);
443
369
  }
@@ -446,284 +372,61 @@ export function createLargeFiles(options) {
446
372
  // same as missing. It was a plain Error, which failed the whole question.
447
373
  if (error instanceof DocumentGoneError)
448
374
  return undefined;
449
- if (!document.broken) {
450
- // Deleted between the look-up and the read: the same as missing.
451
- if (!await currentMeta(id))
452
- return undefined;
453
- throw error;
454
- }
455
- }
456
- }
457
- return undefined;
458
- }
459
- async function metaFor(id, access) {
460
- const meta = await currentMeta(id);
461
- return meta && allowed(meta, access) ? meta : undefined;
462
- }
463
- /**
464
- * The work of `ingest`, once the file is named: `detected` is the format its name and type say.
465
- * `progress` is given when someone listens to the events of the ingest. `storeFailed` is called
466
- * when the store fails to write the document, whatever it throws.
467
- */
468
- async function ingestFile(input, name, mimeType, detected, progress, storeFailed, work) {
469
- let format = detected;
470
- const { signal, dispose } = ingestSignal(name, input.signal, ingestTimeoutMs);
471
- // Each long step works in slices, with pauses for other requests: one large upload no longer
472
- // holds the whole server while it is read.
473
- const slicer = new TimeSlicer(signal);
474
- let pages;
475
- let reading;
476
- let text;
477
- let wrapped;
478
- let lines;
479
- let measured;
480
- let outline;
481
- let logProfile;
482
- let quality = {};
483
- let index;
484
- try {
485
- signal.throwIfAborted();
486
- // In a function of its own, so that the text as extracted is let go once it is prepared:
487
- // the steps after it hold only the prepared text.
488
- const read = async () => {
489
- // What an extractor of your own reports once it has settled (from a timer, a worker) is
490
- // not reported: the stages after it have begun.
491
- let extracting = true;
492
- let extracted;
493
- try {
494
- // Kept, so that an ingest that stops waiting for it (its time is up, its caller left)
495
- // keeps its turn until the extractor is done too: it still holds memory.
496
- const extraction = extractText(input.bytes, {
497
- name,
498
- mimeType,
499
- format,
500
- // A scan is worth storing only if its pages can be shown later: that needs the file itself.
501
- ...(format === "pdf" && keeps(format) && scannedPdfPages > 0 ? { scannedPages: scannedPdfPages } : {}),
502
- signal,
503
- maxTextBytes,
504
- maxPages: maxPdfPages,
505
- ...(progress ? { onProgress: (report) => { if (extracting)
506
- progress.extracted(report); } } : {}),
507
- }, options.extractors);
508
- work.abandoned = extraction;
509
- extracted = await untilAborted(extraction, signal);
510
- work.abandoned = undefined;
511
- }
512
- finally {
513
- extracting = false;
514
- }
515
- progress?.end();
516
- // A character is at least one byte: a text this long is too large whatever it holds.
517
- if (extracted.text.length > maxTextBytes)
518
- throw tooMuchText(name, maxTextBytes);
519
- await slicer.pauseNow();
520
- return { pages: extracted.pages, reading: readingOf(extracted), ...await prepareText(extracted.text, slicer, progress && ((done, total) => progress.report("prepare", done, total, "characters"))) };
521
- };
522
- ({ pages, reading, text, wrapped, lines } = await read());
523
- progress?.end();
524
- if (!text.trim())
525
- throw new Error(`${name} did not contain any text.`);
526
- if (format === "text" && looksLikeLog(lines))
527
- format = "log";
528
- measured = await measureText(text, slicer);
529
- if (measured.utf8 > maxTextBytes)
530
- throw tooMuchText(name, maxTextBytes);
531
- outline = await buildOutlineInSlices(lines, format, slicer);
532
- logProfile = format === "log" ? await buildLogProfileInSlices(lines, slicer) : undefined;
533
- quality = await measureQuality(lines, format, slicer);
534
- // The line index, so that the text can be read by range: a few bytes a line, built from the
535
- // UTF-8 bytes the store writes. Kept by any store that can keep it, even one this library
536
- // then loads whole, so that switching to reading by range finds it ready.
537
- index = typeof store.putIndex === "function"
538
- ? await buildTextIndexInSlices(text, slicer, progress && ((done, total) => progress.report("index", done, total, "characters")))
539
- : undefined;
540
- progress?.end();
541
- signal.throwIfAborted();
542
- }
543
- finally {
544
- dispose();
545
- }
546
- const created = now();
547
- const expires = created.getTime() + ttlMs;
548
- const keepOriginal = keeps(format);
549
- // A copy: the outline's headings and the log's timestamps are pieces of the text, and a piece
550
- // keeps the whole text in memory as long as it is held. A meta an application kept held its
551
- // text: 25 MB of heap for a log of 10 MB in Hebrew, 194 MB for one of 100 MB. Copied through
552
- // JSON, as a store that keeps it as JSON gives it back.
553
- const meta = jsonCopy({
554
- id: `doc_${randomUUID().replaceAll("-", "")}`,
555
- ...(input.owner !== undefined ? { owner: input.owner } : {}),
556
- name,
557
- mimeType,
558
- format,
559
- bytes: input.bytes.byteLength,
560
- textBytes: measured.utf8,
561
- jsonBytes: measured.json,
562
- characters: text.length,
563
- lines: lines.length,
564
- estimatedTokens: measured.tokens,
565
- wrappedLines: wrapped,
566
- ...(pages ? { pages } : {}),
567
- ...reading,
568
- ...(keepOriginal ? { originalKept: true } : {}),
569
- outline,
570
- ...(logProfile ? { logProfile } : {}),
571
- ...quality,
572
- createdAt: created.toISOString(),
573
- // Never, for a time to live without end (or one that runs past what a date can hold).
574
- expiresAt: expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString(),
575
- });
576
- const savedIndex = index && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters && index.textBytes === meta.textBytes
577
- ? serializeTextIndex(index)
578
- : undefined;
579
- // Each write is reported once done. What the listener of the events throws is not the store's failure.
580
- const writes = (keepOriginal ? 1 : 0) + (savedIndex ? 1 : 0) + 1;
581
- let written = 0;
582
- let listenerFailed;
583
- const wrote = (last) => {
584
- if (!progress)
585
- return;
586
- try {
587
- progress.report("store", ++written, writes, "parts");
588
- if (last)
589
- progress.end();
590
- }
591
- catch (error) {
592
- listenerFailed = { error };
375
+ if (document.broken)
376
+ continue;
377
+ // Deleted between the look-up and the read: the same as missing.
378
+ if (!await metaFor(id, caller))
379
+ return undefined;
593
380
  throw error;
594
381
  }
595
- };
596
- // The files first, the document last: a document is there once its metadata is.
597
- const storing = (async () => {
598
- if (keepOriginal) {
599
- await store.putOriginal(meta.id, input.bytes);
600
- wrote(false);
601
- }
602
- if (savedIndex) {
603
- await store.putIndex(meta.id, savedIndex);
604
- wrote(false);
605
- }
606
- await store.put({ meta, text });
607
- wrote(true);
608
- })();
609
- try {
610
- // A store that does not answer fails the ingest after `slotCapMs`: it held the ingest's turn,
611
- // and the upload handler's room for the file, for as long as it did not answer.
612
- await settleWithin(storing, slotCapMs, () => new Error(`The store did not finish writing ${name} within ${formatDuration(slotCapMs)}.`));
613
- }
614
- catch (error) {
615
- // Do not leave a file of up to the upload limit, or a part of one, behind for a document
616
- // that does not exist: once the writes have ended, when they have not yet. The removal is not
617
- // waited for longer than the writes were.
618
- const removal = storing.then(() => store.delete(meta.id), () => store.delete(meta.id)).catch(() => undefined);
619
- await settleWithin(removal, slotCapMs, () => new Error("")).catch(() => undefined);
620
- if (listenerFailed?.error !== error) {
621
- noteStoreWriteFailure(error);
622
- storeFailed();
623
- }
624
- throw error;
382
+ return await stillOpened(document, caller) ? text : undefined;
625
383
  }
626
- return meta;
384
+ return undefined;
627
385
  }
628
386
  return {
629
387
  budget,
630
388
  budgetFor,
631
389
  maxUploadBytes,
632
- async ingest(input) {
633
- // The events first, so that every ingest that throws, even on what it was given, ends with ingest.error.
634
- // What the caller's listener throws is passed on as it is, not told as a file that could not be read.
635
- let listenerFailure;
636
- const listener = input?.onEvent;
637
- const events = new EventEmitter(input?.runId ?? newRunId("ing"), listener && ((event) => {
638
- try {
639
- listener(event);
640
- }
641
- catch (error) {
642
- listenerFailure ??= { error };
643
- throw error;
644
- }
645
- }));
646
- let storeFailed = false;
647
- try {
648
- if (events.active)
649
- events.emit({ type: "ingest.start", ...startOf(input) });
650
- checkOwner(input.owner);
651
- const name = cleanFileName(input.name);
652
- const mimeType = input.mimeType?.trim() || "application/octet-stream";
653
- // A file whose name and type say nothing is known by its bytes: a PDF, an Office file, a page.
654
- const format = detectFormat(name, mimeType, input.bytes instanceof Uint8Array ? input.bytes : undefined);
655
- // Progress is worked out only for someone who listens.
656
- const progress = events.active ? new IngestProgress(events) : undefined;
657
- let meta;
658
- try {
659
- // Refused at once, without waiting for a turn.
660
- if (input.bytes.byteLength === 0)
661
- throw new Error(`${name} is empty.`);
662
- if (input.bytes.byteLength > maxUploadBytes) {
663
- throw new Error(`${name} is larger than the ${formatBytes(maxUploadBytes)} upload limit.`);
664
- }
665
- // Its turn (`maxConcurrentIngests`): a caller that gives up while it waits gets its own
666
- // reason, as it would once the work had begun. (An ingest started inside another of this
667
- // library, by an extractor of your own, waits for a turn like any other. Telling it apart
668
- // with AsyncLocalStorage made pdf.js about five times slower on Node 22, for every PDF.)
669
- const slot = new IngestSlot(await ingests.acquire(input.signal), slotCapMs);
670
- const work = {};
671
- try {
672
- meta = await ingestFile(input, name, mimeType, format, progress, () => (storeFailed = true), work);
673
- }
674
- finally {
675
- slot.end(work.abandoned);
676
- }
677
- }
678
- catch (error) {
679
- // A store that failed, and a caller that gave up (its own reason), are passed on as they
680
- // are; a file that could not be read is told with a code.
681
- if (storeFailed || (input.signal?.aborted && error === input.signal.reason) || isStoreWriteFailure(error) || (listenerFailure && error === listenerFailure.error))
682
- throw error;
683
- throw toIngestError(error);
684
- }
685
- try {
686
- events.emit({ type: "ingest.finish", document: toDocumentSummary(meta) });
687
- }
688
- catch (error) {
689
- // The caller never gets the id: the document goes, as on a throw of the listener a moment earlier.
690
- await store.delete(meta.id).catch(() => undefined);
691
- forget(meta.id);
692
- throw error;
693
- }
694
- return meta;
695
- }
696
- catch (error) {
697
- // A store's own error may name a host or a path, whatever it is: the event, which a browser
698
- // may see, says only that the document could not be stored.
699
- events.emit({ type: "ingest.error", error: storeFailed ? { message: STORE_WRITE_FAILED } : eventErrorOf(error) });
700
- throw error;
701
- }
390
+ access: rules,
391
+ ingest(input) {
392
+ return ingestDocument(ingestContext, input);
393
+ },
394
+ async getMeta(id, access) {
395
+ return metaFor(id, callerOf(access, rules));
702
396
  },
703
- getMeta: metaFor,
704
397
  async getOriginal(id, access) {
705
- const meta = await metaFor(id, access);
706
- return meta?.originalKept ? loadOriginal?.(id) : undefined;
398
+ const caller = callerOf(access, rules);
399
+ const meta = await metaFor(id, caller);
400
+ if (!meta?.originalKept || !readable(meta))
401
+ return undefined;
402
+ const original = await originalOf(id, caller, meta);
403
+ return original instanceof Uint8Array ? original : undefined;
707
404
  },
708
405
  async delete(id, access) {
709
- if (!await metaFor(id, access))
406
+ const caller = callerOf(access, rules);
407
+ if (!await metaFor(id, caller))
710
408
  return false;
711
409
  forget(id);
712
- return options.store.delete(id);
410
+ return storeCall("delete", () => store.delete(id, caller.context));
713
411
  },
714
- async sweep() {
715
- return options.store.sweep?.(now()) ?? 0;
412
+ async sweep(sweepOptions) {
413
+ // Upkeep of the store, not a user's access: allowed without a scope under `requireScope`.
414
+ const scope = checkScope(sweepOptions?.scope ?? undefined);
415
+ if (typeof store.sweep !== "function")
416
+ return 0;
417
+ return storeCall("sweep", () => store.sweep(now(), storeContext(scope, undefined)));
716
418
  },
717
419
  async prepare(ids, base, access) {
420
+ const caller = callerOf(access, rules);
718
421
  const budget = budgetFor(access?.budget);
719
422
  const analysis = access?.wholeDocumentAnalysis !== false;
720
423
  const unique = [...new Set(ids)];
721
424
  let documents = [];
722
425
  const missing = [];
723
426
  for (const id of unique) {
724
- // A document owned by someone else is reported as missing, not as forbidden, and is not
725
- // read at all.
726
- const meta = await metaFor(id, access);
427
+ // A document of another owner or scope is reported as missing, not as forbidden, and is
428
+ // not read at all.
429
+ const meta = await metaFor(id, caller);
727
430
  if (meta)
728
431
  documents.push(meta);
729
432
  else
@@ -735,15 +438,13 @@ export function createLargeFiles(options) {
735
438
  const plan = planDocuments(documents, budget, base);
736
439
  const inline = new Set(plan.inline.map((meta) => meta.id));
737
440
  // Pages can be shown for a PDF whose file is kept, whether its text is in the prompt or searched.
738
- const viewable = access?.viewPages && store.getOriginal
739
- ? documents.filter((meta) => meta.format === "pdf" && meta.originalKept)
740
- : [];
441
+ const viewable = access?.viewPages ? documents.filter(viewableMeta) : [];
741
442
  const shown = new Set(viewable.map((meta) => meta.id));
742
443
  const blocks = new Map();
743
444
  const gone = [];
744
445
  for (const meta of documents) {
745
446
  const wholeRead = !analysis ? "not_offered" : canBeReadWhole(meta, budget) ? "offered" : "too_large";
746
- const text = await block(meta.id, meta, inline.has(meta.id), shown.has(meta.id), wholeRead);
447
+ const text = await block(meta.id, meta, caller, inline.has(meta.id), shown.has(meta.id), wholeRead);
747
448
  if (text === undefined)
748
449
  gone.push(meta.id);
749
450
  else
@@ -760,30 +461,53 @@ export function createLargeFiles(options) {
760
461
  }
761
462
  },
762
463
  tools(documents, toolOptions = {}) {
763
- const { viewPages, budget: overrides, ...rest } = toolOptions;
464
+ const { viewPages, budget: overrides, access, ...rest } = toolOptions;
465
+ // Without `access`, the owner and scope of each document are those it was handed in with: a
466
+ // library that requires them takes them only from the caller.
467
+ if (access === undefined && (rules.requireOwner || rules.requireScope)) {
468
+ throw new TypeError(rules.requireOwner ? OWNER_REQUIRED : SCOPE_REQUIRED);
469
+ }
470
+ const asker = access !== undefined ? callerOf(access, rules) : undefined;
764
471
  const budget = budgetFor(overrides);
765
- const viewable = (loadOriginal ? (viewPages === true ? documents : viewPages || []) : [])
766
- .filter((meta) => meta.format === "pdf" && meta.originalKept);
767
- // The owner each document was handed in with. The store's owner is checked against it on
768
- // every call, so metadata built from an ID alone cannot read another owner's document: such
769
- // a document is answered as no longer available, as `getMeta` reports it missing.
770
- const handedOwner = new Map([...documents, ...viewable].map((meta) => [meta.id, meta.owner]));
771
- const mayUse = (meta) => meta.owner === undefined || (handedOwner.has(meta.id) && meta.owner === handedOwner.get(meta.id));
472
+ // Which PDFs can be looked at, by the metadata handed in: each look reads the metadata the
473
+ // store holds, and the file it names, not the one handed in.
474
+ const viewable = (viewPages === true ? documents : viewPages || []).filter(viewableMeta);
475
+ // Without `access`, as before 0.9.0: the owner and scope each document was handed in with.
476
+ // The store is asked with them, and the owner and scope it holds are checked against them on
477
+ // every call, so metadata built from an ID alone cannot read another owner's document: such a
478
+ // document is answered as no longer available, as `getMeta` reports it missing. A handed scope
479
+ // that is not valid reads nothing.
480
+ const handed = new Map(asker ? [] : [...documents, ...viewable].map((meta) => [meta.id, handedCaller(meta)]));
481
+ const callerFor = (id) => asker ?? (handed.has(id) ? handed.get(id) : NO_CALLER);
772
482
  // The metadata the store holds now, not that of a copy kept in memory.
773
483
  const checkedLoad = async (id) => {
774
- const meta = await currentMeta(id);
775
- return meta && mayUse(meta) ? load(id, meta) : undefined;
484
+ const caller = callerFor(id);
485
+ const meta = caller && await metaFor(id, caller);
486
+ return meta ? load(id, caller, meta) : undefined;
776
487
  };
777
- const checkedOriginal = loadOriginal && (async (id) => {
778
- const meta = await currentMeta(id);
779
- return meta && mayUse(meta) ? loadOriginal(id) : undefined;
488
+ const checkedOriginal = (store.getOriginal || originals) && (async (id) => {
489
+ const caller = callerFor(id);
490
+ const meta = caller && await metaFor(id, caller);
491
+ if (!meta || !readable(meta))
492
+ return undefined;
493
+ const original = await originalOf(id, caller, meta);
494
+ // A file the application keeps that has changed since it was ingested: its pages are not
495
+ // those of the text the model has, and the model is told so.
496
+ if (original === "changed")
497
+ throw new Error(changedOriginal(meta.name));
498
+ return original === "missing" ? undefined : original;
780
499
  });
781
500
  return createDocumentTools({
782
501
  load: checkedLoad,
502
+ // Once a call has read a document by range: the store is asked again (`stillOpened`).
503
+ checkRead: async (document) => {
504
+ const caller = callerFor(document.meta.id);
505
+ return caller !== undefined && await stillOpened(document, caller);
506
+ },
783
507
  documentIds: documents.map((meta) => meta.id),
784
508
  names: Object.fromEntries([...documents, ...viewable].map((meta) => [meta.id, wellFormed(meta.name)])),
785
509
  budget,
786
- ...(checkedOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal: checkedOriginal } : {}),
510
+ ...(checkedOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal: checkedOriginal, pageLooks } : {}),
787
511
  // `analyze_whole_document` is declared only when it can read at least one of the documents.
788
512
  wholeReads: documents.some((meta) => canBeReadWhole(meta, budget)),
789
513
  // `aggregate_table` only when one may hold a table.
@@ -792,5 +516,14 @@ export function createLargeFiles(options) {
792
516
  });
793
517
  },
794
518
  };
519
+ /** The caller a document was handed to `tools` for (without `access`): its owner and scope. Undefined for a scope that is not valid. */
520
+ function handedCaller(meta) {
521
+ try {
522
+ return callerOf({ owner: meta.owner, scope: meta.scope }, rules);
523
+ }
524
+ catch {
525
+ return undefined;
526
+ }
527
+ }
795
528
  }
796
529
  //# sourceMappingURL=library.js.map