llm-large-files 0.8.2 → 0.10.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 (288) hide show
  1. package/CHANGELOG.md +981 -0
  2. package/README.md +22 -17
  3. package/dist/access.d.ts +128 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +234 -0
  6. package/dist/access.js.map +1 -0
  7. package/dist/aggregate.d.ts +6 -0
  8. package/dist/aggregate.d.ts.map +1 -1
  9. package/dist/aggregate.js +86 -13
  10. package/dist/aggregate.js.map +1 -1
  11. package/dist/analyze.d.ts +4 -0
  12. package/dist/analyze.d.ts.map +1 -1
  13. package/dist/analyze.js +2 -2
  14. package/dist/analyze.js.map +1 -1
  15. package/dist/answer-info.d.ts +26 -0
  16. package/dist/answer-info.d.ts.map +1 -0
  17. package/dist/answer-info.js +32 -0
  18. package/dist/answer-info.js.map +1 -0
  19. package/dist/anthropic/adapter.d.ts +5 -1
  20. package/dist/anthropic/adapter.d.ts.map +1 -1
  21. package/dist/anthropic/adapter.js +35 -10
  22. package/dist/anthropic/adapter.js.map +1 -1
  23. package/dist/ask.d.ts +159 -14
  24. package/dist/ask.d.ts.map +1 -1
  25. package/dist/ask.js +743 -113
  26. package/dist/ask.js.map +1 -1
  27. package/dist/cache.d.ts +12 -3
  28. package/dist/cache.d.ts.map +1 -1
  29. package/dist/cache.js +18 -5
  30. package/dist/cache.js.map +1 -1
  31. package/dist/citations.d.ts +36 -0
  32. package/dist/citations.d.ts.map +1 -0
  33. package/dist/citations.js +291 -0
  34. package/dist/citations.js.map +1 -0
  35. package/dist/encoding.js +5 -3
  36. package/dist/encoding.js.map +1 -1
  37. package/dist/error-info.d.ts +70 -0
  38. package/dist/error-info.d.ts.map +1 -0
  39. package/dist/error-info.js +253 -0
  40. package/dist/error-info.js.map +1 -0
  41. package/dist/errors.d.ts +74 -8
  42. package/dist/errors.d.ts.map +1 -1
  43. package/dist/errors.js +104 -15
  44. package/dist/errors.js.map +1 -1
  45. package/dist/events.d.ts +57 -13
  46. package/dist/events.d.ts.map +1 -1
  47. package/dist/events.js +42 -11
  48. package/dist/events.js.map +1 -1
  49. package/dist/evidence.d.ts +4 -2
  50. package/dist/evidence.d.ts.map +1 -1
  51. package/dist/evidence.js +35 -5
  52. package/dist/evidence.js.map +1 -1
  53. package/dist/extract.d.ts +32 -8
  54. package/dist/extract.d.ts.map +1 -1
  55. package/dist/extract.js +52 -36
  56. package/dist/extract.js.map +1 -1
  57. package/dist/gemini/adapter.d.ts +54 -7
  58. package/dist/gemini/adapter.d.ts.map +1 -1
  59. package/dist/gemini/adapter.js +152 -41
  60. package/dist/gemini/adapter.js.map +1 -1
  61. package/dist/gemini/chat.d.ts +38 -53
  62. package/dist/gemini/chat.d.ts.map +1 -1
  63. package/dist/gemini/chat.js +20 -25
  64. package/dist/gemini/chat.js.map +1 -1
  65. package/dist/gemini/endpoints.d.ts +59 -11
  66. package/dist/gemini/endpoints.d.ts.map +1 -1
  67. package/dist/gemini/endpoints.js +33 -7
  68. package/dist/gemini/endpoints.js.map +1 -1
  69. package/dist/gemini/errors.d.ts +39 -5
  70. package/dist/gemini/errors.d.ts.map +1 -1
  71. package/dist/gemini/errors.js +70 -9
  72. package/dist/gemini/errors.js.map +1 -1
  73. package/dist/gemini/generate.d.ts +53 -2
  74. package/dist/gemini/generate.d.ts.map +1 -1
  75. package/dist/gemini/generate.js +100 -50
  76. package/dist/gemini/generate.js.map +1 -1
  77. package/dist/gemini/index.d.ts +4 -4
  78. package/dist/gemini/index.d.ts.map +1 -1
  79. package/dist/http.d.ts +41 -3
  80. package/dist/http.d.ts.map +1 -1
  81. package/dist/http.js +40 -2
  82. package/dist/http.js.map +1 -1
  83. package/dist/index.d.ts +13 -8
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.js +8 -5
  86. package/dist/index.js.map +1 -1
  87. package/dist/ingest.d.ts +78 -0
  88. package/dist/ingest.d.ts.map +1 -0
  89. package/dist/ingest.js +893 -0
  90. package/dist/ingest.js.map +1 -0
  91. package/dist/library.d.ts +295 -33
  92. package/dist/library.d.ts.map +1 -1
  93. package/dist/library.js +458 -650
  94. package/dist/library.js.map +1 -1
  95. package/dist/map-reduce.d.ts +176 -10
  96. package/dist/map-reduce.d.ts.map +1 -1
  97. package/dist/map-reduce.js +807 -61
  98. package/dist/map-reduce.js.map +1 -1
  99. package/dist/model.d.ts +79 -6
  100. package/dist/model.d.ts.map +1 -1
  101. package/dist/model.js +80 -4
  102. package/dist/model.js.map +1 -1
  103. package/dist/node/handlers.d.ts +247 -14
  104. package/dist/node/handlers.d.ts.map +1 -1
  105. package/dist/node/handlers.js +491 -227
  106. package/dist/node/handlers.js.map +1 -1
  107. package/dist/node/index.d.ts +3 -2
  108. package/dist/node/index.d.ts.map +1 -1
  109. package/dist/node/index.js +2 -1
  110. package/dist/node/index.js.map +1 -1
  111. package/dist/node/ingest-child.d.ts +7 -1
  112. package/dist/node/ingest-child.d.ts.map +1 -1
  113. package/dist/node/ingest-child.js +19 -4
  114. package/dist/node/ingest-child.js.map +1 -1
  115. package/dist/node/isolated.d.ts +3 -1
  116. package/dist/node/isolated.d.ts.map +1 -1
  117. package/dist/node/isolated.js +11 -4
  118. package/dist/node/isolated.js.map +1 -1
  119. package/dist/node/originals.d.ts +19 -0
  120. package/dist/node/originals.d.ts.map +1 -0
  121. package/dist/node/originals.js +82 -0
  122. package/dist/node/originals.js.map +1 -0
  123. package/dist/node/spool.d.ts +106 -0
  124. package/dist/node/spool.d.ts.map +1 -0
  125. package/dist/node/spool.js +378 -0
  126. package/dist/node/spool.js.map +1 -0
  127. package/dist/node/sse.d.ts +6 -4
  128. package/dist/node/sse.d.ts.map +1 -1
  129. package/dist/node/sse.js +9 -7
  130. package/dist/node/sse.js.map +1 -1
  131. package/dist/openai/adapter.d.ts +5 -1
  132. package/dist/openai/adapter.d.ts.map +1 -1
  133. package/dist/openai/adapter.js +53 -12
  134. package/dist/openai/adapter.js.map +1 -1
  135. package/dist/output-limit.d.ts +2 -1
  136. package/dist/output-limit.d.ts.map +1 -1
  137. package/dist/output-limit.js +5 -2
  138. package/dist/output-limit.js.map +1 -1
  139. package/dist/pdf-layout.d.ts.map +1 -1
  140. package/dist/pdf-layout.js +71 -12
  141. package/dist/pdf-layout.js.map +1 -1
  142. package/dist/pdf-outline.d.ts +71 -0
  143. package/dist/pdf-outline.d.ts.map +1 -0
  144. package/dist/pdf-outline.js +414 -0
  145. package/dist/pdf-outline.js.map +1 -0
  146. package/dist/plan.d.ts +137 -7
  147. package/dist/plan.d.ts.map +1 -1
  148. package/dist/plan.js +248 -26
  149. package/dist/plan.js.map +1 -1
  150. package/dist/prepare.d.ts +50 -0
  151. package/dist/prepare.d.ts.map +1 -0
  152. package/dist/prepare.js +207 -0
  153. package/dist/prepare.js.map +1 -0
  154. package/dist/ranged.d.ts +16 -11
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +56 -12
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +3 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +6 -2
  161. package/dist/retry.js.map +1 -1
  162. package/dist/scope.d.ts +25 -0
  163. package/dist/scope.d.ts.map +1 -0
  164. package/dist/scope.js +60 -0
  165. package/dist/scope.js.map +1 -0
  166. package/dist/search.d.ts +7 -0
  167. package/dist/search.d.ts.map +1 -1
  168. package/dist/search.js +72 -10
  169. package/dist/search.js.map +1 -1
  170. package/dist/source.d.ts +60 -0
  171. package/dist/source.d.ts.map +1 -0
  172. package/dist/source.js +170 -0
  173. package/dist/source.js.map +1 -0
  174. package/dist/stores.d.ts +126 -31
  175. package/dist/stores.d.ts.map +1 -1
  176. package/dist/stores.js +655 -141
  177. package/dist/stores.js.map +1 -1
  178. package/dist/testing/fake-fetch.d.ts +31 -0
  179. package/dist/testing/fake-fetch.d.ts.map +1 -0
  180. package/dist/testing/fake-fetch.js +66 -0
  181. package/dist/testing/fake-fetch.js.map +1 -0
  182. package/dist/testing/fake-model.d.ts +38 -0
  183. package/dist/testing/fake-model.d.ts.map +1 -0
  184. package/dist/testing/fake-model.js +62 -0
  185. package/dist/testing/fake-model.js.map +1 -0
  186. package/dist/testing/index.d.ts +7 -0
  187. package/dist/testing/index.d.ts.map +1 -0
  188. package/dist/testing/index.js +9 -0
  189. package/dist/testing/index.js.map +1 -0
  190. package/dist/testing/store-checks.d.ts +72 -0
  191. package/dist/testing/store-checks.d.ts.map +1 -0
  192. package/dist/testing/store-checks.js +619 -0
  193. package/dist/testing/store-checks.js.map +1 -0
  194. package/dist/tools.d.ts +47 -2
  195. package/dist/tools.d.ts.map +1 -1
  196. package/dist/tools.js +440 -71
  197. package/dist/tools.js.map +1 -1
  198. package/dist/types.d.ts +165 -14
  199. package/dist/types.d.ts.map +1 -1
  200. package/dist/whole-cost.d.ts +37 -0
  201. package/dist/whole-cost.d.ts.map +1 -0
  202. package/dist/whole-cost.js +46 -0
  203. package/dist/whole-cost.js.map +1 -0
  204. package/docs/README.md +21 -8
  205. package/docs/getting-started.md +18 -13
  206. package/docs/guides/anthropic.md +17 -10
  207. package/docs/guides/conversations.md +112 -47
  208. package/docs/guides/costs-and-limits.md +147 -42
  209. package/docs/guides/deployment.md +380 -86
  210. package/docs/guides/errors-and-reliability.md +317 -67
  211. package/docs/guides/explorer-model.md +4 -1
  212. package/docs/guides/openai-compatible.md +47 -7
  213. package/docs/guides/own-adapter-and-loop.md +60 -16
  214. package/docs/guides/pdfs.md +219 -36
  215. package/docs/guides/storage.md +676 -145
  216. package/docs/guides/testing.md +149 -129
  217. package/docs/guides/vertex-and-gemini.md +169 -57
  218. package/docs/guides/web-app.md +318 -80
  219. package/docs/how-it-works.md +155 -30
  220. package/docs/measurements.md +215 -13
  221. package/docs/publishing.md +185 -37
  222. package/docs/reference/anthropic.md +12 -7
  223. package/docs/reference/ask.md +415 -47
  224. package/docs/reference/errors-and-retries.md +194 -14
  225. package/docs/reference/events.md +77 -27
  226. package/docs/reference/gemini.md +252 -87
  227. package/docs/reference/library.md +886 -178
  228. package/docs/reference/node.md +659 -111
  229. package/docs/reference/openai.md +21 -10
  230. package/docs/reference/testing.md +311 -0
  231. package/docs/reference/tools.md +285 -30
  232. package/docs/security.md +404 -78
  233. package/docs/troubleshooting.md +151 -70
  234. package/docs/upgrading-0.10.md +472 -0
  235. package/docs/upgrading-0.9.md +890 -0
  236. package/package.json +16 -3
  237. package/src/access.ts +267 -0
  238. package/src/aggregate.ts +92 -14
  239. package/src/analyze.ts +2 -2
  240. package/src/answer-info.ts +45 -0
  241. package/src/anthropic/adapter.ts +40 -11
  242. package/src/ask.ts +866 -115
  243. package/src/cache.ts +20 -5
  244. package/src/citations.ts +294 -0
  245. package/src/encoding.ts +6 -4
  246. package/src/error-info.ts +290 -0
  247. package/src/errors.ts +131 -15
  248. package/src/events.ts +112 -24
  249. package/src/evidence.ts +35 -5
  250. package/src/extract.ts +56 -34
  251. package/src/gemini/adapter.ts +196 -43
  252. package/src/gemini/chat.ts +63 -78
  253. package/src/gemini/endpoints.ts +89 -16
  254. package/src/gemini/errors.ts +74 -11
  255. package/src/gemini/generate.ts +147 -57
  256. package/src/gemini/index.ts +4 -4
  257. package/src/http.ts +65 -4
  258. package/src/index.ts +13 -8
  259. package/src/ingest.ts +958 -0
  260. package/src/library.ts +711 -651
  261. package/src/map-reduce.ts +858 -70
  262. package/src/model.ts +113 -9
  263. package/src/node/handlers.ts +709 -221
  264. package/src/node/index.ts +14 -2
  265. package/src/node/ingest-child.ts +24 -6
  266. package/src/node/isolated.ts +11 -4
  267. package/src/node/originals.ts +78 -0
  268. package/src/node/spool.ts +379 -0
  269. package/src/node/sse.ts +9 -7
  270. package/src/openai/adapter.ts +56 -13
  271. package/src/output-limit.ts +5 -2
  272. package/src/pdf-layout.ts +69 -11
  273. package/src/pdf-outline.ts +400 -0
  274. package/src/plan.ts +287 -36
  275. package/src/prepare.ts +253 -0
  276. package/src/ranged.ts +48 -14
  277. package/src/retry.ts +6 -2
  278. package/src/scope.ts +63 -0
  279. package/src/search.ts +69 -13
  280. package/src/source.ts +178 -0
  281. package/src/stores.ts +702 -142
  282. package/src/testing/fake-fetch.ts +80 -0
  283. package/src/testing/fake-model.ts +78 -0
  284. package/src/testing/index.ts +11 -0
  285. package/src/testing/store-checks.ts +660 -0
  286. package/src/tools.ts +461 -73
  287. package/src/types.ts +151 -14
  288. package/src/whole-cost.ts +64 -0
package/src/ranged.ts CHANGED
@@ -4,6 +4,8 @@
4
4
  * large file in memory. The line index comes from the store (`getIndex`), or is built from the
5
5
  * text the first time an older document without one is opened, and saved for next time.
6
6
  */
7
+ import { holderOf } from "./cache.js";
8
+ import { DocumentStoreError } from "./errors.js";
7
9
  import type { Limiter } from "./limiter.js";
8
10
  import { pagesOfLines, pause, type DocumentSource, type ScanFeed, type TextChunk } from "./search.js";
9
11
  import { canSerialize, parseTextIndex, positionOf, serializeTextIndex, TextIndexBuilder, type TextIndex } from "./text-index.js";
@@ -17,8 +19,8 @@ export type ScanSettings = {
17
19
  chunkBytes: number;
18
20
  /** Bounds how many scans of whole documents run at once. */
19
21
  limiter: Limiter;
20
- /** Told when the stored text of a document did not agree with its index. */
21
- onBroken?: (id: string) => void;
22
+ /** Told, with the document's key (`RangedDocument.key`), when its stored text did not agree with its index. */
23
+ onBroken?: (key: string) => void;
22
24
  /**
23
25
  * Where decoded pieces of frequently searched documents are kept, within the cache's memory
24
26
  * limit, so that the next search of them reads and decodes nothing. A document whose decoded
@@ -37,8 +39,12 @@ export type PieceCache = {
37
39
  maxDocumentBytes: number;
38
40
  };
39
41
 
40
- /** The cache key of piece `at` of a document. All of them start with `${id}#`. */
41
- export const pieceKey = (id: string, at: number) => `${id}#${at}`;
42
+ /**
43
+ * The cache key of piece `at` of the document of key `key` (its ID, or the library's key of the
44
+ * document in one scope). All of them start with `${key}#`, and the document's key is all before
45
+ * the last "#".
46
+ */
47
+ export const pieceKey = (key: string, at: number) => `${key}#${at}`;
42
48
 
43
49
  /** Bytes read at a time to build an index from the text. */
44
50
  const BUILD_READ_BYTES = 4 * 1024 * 1024;
@@ -77,8 +83,11 @@ export class RangedDocument implements DocumentSource {
77
83
  readonly meta: DocumentMeta,
78
84
  readonly index: TextIndex,
79
85
  private readonly settings: ScanSettings,
86
+ /** What its pieces are kept under, and what `onBroken` is told: its ID unless given another. */
87
+ readonly key: string = meta.id,
80
88
  ) {
81
- this.pieceVersion = `${meta.createdAt}|${index.textBytes}|${index.characters}|${settings.chunkBytes}`;
89
+ // Whose it is too: a piece of one owner's or scope's text is never served for another's.
90
+ this.pieceVersion = `${meta.createdAt}|${index.textBytes}|${index.characters}|${settings.chunkBytes}|${holderOf(meta)}`;
82
91
  // Decoded text is one byte a character when it is all ASCII, two otherwise; and its lowercased copy as much again.
83
92
  const decoded = index.characters * (index.textBytes === index.characters ? 1 : 2) * 2 + index.characterStarts.byteLength;
84
93
  this.keepPieces = settings.pieces !== undefined && decoded <= settings.pieces.maxDocumentBytes;
@@ -245,7 +254,7 @@ export class RangedDocument implements DocumentSource {
245
254
  /** Piece `at`, from memory when it is kept there. */
246
255
  private async piece(at: number): Promise<TextChunk> {
247
256
  const cache = this.keepPieces ? this.settings.pieces : undefined;
248
- const kept = cache?.get(pieceKey(this.meta.id, at), this.pieceVersion);
257
+ const kept = cache?.get(pieceKey(this.key, at), this.pieceVersion);
249
258
  if (kept) return kept;
250
259
  const { firstLine, lastLine, start, end } = this.chunkRanges()[at]!;
251
260
  const text = await this.read(start, end);
@@ -272,7 +281,7 @@ export class RangedDocument implements DocumentSource {
272
281
  // The text and, once a search needs it, its lowercased copy.
273
282
  memoryBytes: text.length * (ascii ? 1 : 2) * 2 + starts.byteLength + 256,
274
283
  };
275
- cache?.set(pieceKey(this.meta.id, at), this.pieceVersion, piece);
284
+ cache?.set(pieceKey(this.key, at), this.pieceVersion, piece);
276
285
  return piece;
277
286
  }
278
287
 
@@ -310,7 +319,7 @@ export class RangedDocument implements DocumentSource {
310
319
  private mismatch(): Error {
311
320
  if (!this.broken) {
312
321
  this.broken = true;
313
- this.settings.onBroken?.(this.meta.id);
322
+ this.settings.onBroken?.(this.key);
314
323
  }
315
324
  return new Error(`The stored text of ${this.meta.name} did not match its index. Try the call again.`);
316
325
  }
@@ -335,30 +344,55 @@ export async function buildIndexFromStore(store: RangeStore, id: string, limiter
335
344
  }
336
345
  }
337
346
 
347
+ /**
348
+ * A read of the saved index, or of the end of the text, that failed: no saved index, so that it is
349
+ * built again from the text. Unless the store did not answer in time ("ETIMEDOUT"), or was not
350
+ * called because too many calls are stuck ("STORE_STUCK"): reading the whole text from that store
351
+ * would take longer still, and leave more calls stuck. That error is thrown (0.10.0).
352
+ */
353
+ function noSavedIndex(error: unknown): undefined {
354
+ if (DocumentStoreError.is(error) && (error.code === "ETIMEDOUT" || error.code === "STORE_STUCK")) throw error;
355
+ return undefined;
356
+ }
357
+
338
358
  /**
339
359
  * Opens a document to be read by range. Uses the saved index when there is one that fits the
340
360
  * document; otherwise builds it from the text and saves it (best effort: a store that cannot
341
361
  * write, or another server writing the same index, changes nothing). Undefined when the text is gone.
362
+ * `key` is what its pieces are kept under (see `RangedDocument.key`). A store that does not answer
363
+ * in time is thrown, not taken for one without an index (`noSavedIndex`, 0.10.0).
342
364
  */
343
365
  export async function openRangedDocument(
344
366
  store: RangeStore,
345
367
  meta: DocumentMeta,
346
368
  settings: ScanSettings,
347
- options: { ignoreSavedIndex?: boolean } = {},
369
+ options: { ignoreSavedIndex?: boolean; key?: string } = {},
348
370
  ): Promise<RangedDocument | undefined> {
349
371
  let index: TextIndex | undefined;
350
372
  if (!options.ignoreSavedIndex && store.getIndex) {
351
- const saved = await store.getIndex(meta.id).catch(() => undefined);
373
+ const saved = await store.getIndex(meta.id).catch(noSavedIndex);
352
374
  if (saved) index = parseTextIndex(saved, meta);
375
+ // A saved index that fits the metadata may still not fit the text: another document's text,
376
+ // written under the ID apart from its metadata and its index (two servers that ingest one ID at
377
+ // once). Its pieces are checked as they are read, but lines of the same lengths would pass. So
378
+ // the text must end where the index says: one byte is read across that end. Otherwise the index
379
+ // is built again from the text, and compared with the metadata below.
380
+ if (index && index.textBytes > 0) {
381
+ const tail = await store.readTextRange(meta.id, index.textBytes - 1, index.textBytes + 1).catch(noSavedIndex);
382
+ if (tail?.length !== 1) index = undefined;
383
+ }
353
384
  }
354
385
  if (!index) {
355
386
  index = await buildIndexFromStore(store, meta.id, settings.limiter);
356
387
  if (!index) return undefined;
357
- // An index that disagrees with the metadata describes a text that is not what was ingested.
358
- // It is used, since it is what the store holds, but not saved.
359
- if (store.putIndex && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters && (meta.textBytes === undefined || index.textBytes === meta.textBytes)) {
388
+ // An index of another number of lines or characters than the metadata describes a text that is
389
+ // not what was ingested: another document's, written under the ID apart from its metadata (two
390
+ // servers that ingest one ID at once). Missing, as a document read whole is (before 0.9.0 it was
391
+ // used, and not saved). Every version counted lines and characters as the index does.
392
+ if (index.lineCount !== meta.lines || index.characters !== meta.characters) return undefined;
393
+ if (store.putIndex && canSerialize(index) && (meta.textBytes === undefined || index.textBytes === meta.textBytes)) {
360
394
  await store.putIndex(meta.id, serializeTextIndex(index)).catch(() => undefined);
361
395
  }
362
396
  }
363
- return new RangedDocument(store, meta, index, settings);
397
+ return new RangedDocument(store, meta, index, settings, options.key);
364
398
  }
package/src/retry.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  // One rule for sending a model request again, used by the chat loop and by whole-file part reads.
2
+ import { modelErrorOf } from "./model.js";
2
3
 
3
4
  /**
4
5
  * How a model request that failed is sent again. A field that is not a finite number (NaN,
@@ -118,7 +119,9 @@ export type RetryNotice = {
118
119
  * - An error of kind "quota" (a daily cap, no credit left) is not retried: a wait does not mend it.
119
120
  * Nor is one of kind "context_overflow", whatever its status: only a smaller request can pass
120
121
  * (OpenAI's request larger than a minute's allowance of tokens comes as HTTP 429). Nor is one
121
- * whose provider said not to try again (Claude's `x-should-retry: false`).
122
+ * whose provider said not to try again (Claude's `x-should-retry: false`). An error without a
123
+ * kind of its own (an adapter of your own) has the kind its status and `code` give, as its events
124
+ * do: a 429 of code "insufficient_quota" is a quota.
122
125
  * - An error of kind "timeout" with status 0 (nothing came from the model for the adapter's whole
123
126
  * wait) is retried once: another such wait is long, and a model that went silent twice will most
124
127
  * likely do so again. A timeout the provider reports (HTTP 408) is retried like any other.
@@ -146,7 +149,8 @@ export async function withRetry<T>(run: () => Promise<T>, options: {
146
149
  return await run();
147
150
  } catch (error) {
148
151
  if (options.signal?.aborted || options.canRetry?.() === false) throw error;
149
- const kind = (error as { kind?: unknown } | null)?.kind;
152
+ // As its events and errorInfoOf tell it (modelErrorOf).
153
+ const kind = modelErrorOf(error)?.kind;
150
154
  if (kind === "quota" || kind === "context_overflow") throw error;
151
155
  if (typeof error === "object" && error !== null && notToRetry.has(error)) throw error;
152
156
  if (kind === "timeout" && statusOf(error) === 0) {
package/src/scope.ts ADDED
@@ -0,0 +1,63 @@
1
+ // Scopes (`DocumentScope`): where a document belongs, such as [userId, chatId]. New in 0.9.0.
2
+ import { DocumentScopeError } from "./errors.js";
3
+ import type { DocumentScope } from "./types.js";
4
+
5
+ /** The most segments a scope may have. */
6
+ export const MAX_SCOPE_SEGMENTS = 8;
7
+ /** The most UTF-16 units one segment may have. */
8
+ export const MAX_SCOPE_SEGMENT_LENGTH = 256;
9
+
10
+ /**
11
+ * What a segment may not hold: "/" and "\" (path separators on every system), control characters
12
+ * (NUL, line breaks, C1), and half of a surrogate pair, which has no UTF-8 form.
13
+ */
14
+ const FORBIDDEN = /[/\\\p{Cc}\p{Cs}]/u;
15
+
16
+ const SHAPE = `scope must be an array of 1 to ${MAX_SCOPE_SEGMENTS} strings, such as [userId, chatId].`;
17
+
18
+ /**
19
+ * A scope given to the library, checked: a frozen copy of it, or undefined when there is none.
20
+ * Throws a `DocumentScopeError` with code "scope_invalid" unless it is an array of 1 to 8 strings,
21
+ * each of 1 to 256 UTF-16 units, with no control characters, no "/" or "\", and none of them "." or
22
+ * "..". The message says which segment is wrong, not what it holds: a segment may be a user's ID.
23
+ */
24
+ export function checkScope(scope: unknown): DocumentScope | undefined {
25
+ if (scope === undefined) return undefined;
26
+ if (!Array.isArray(scope) || scope.length < 1 || scope.length > MAX_SCOPE_SEGMENTS) {
27
+ throw new DocumentScopeError("scope_invalid", SHAPE);
28
+ }
29
+ const segments: string[] = [];
30
+ // An index loop, not `map`: a hole in the array is a segment that is missing.
31
+ for (let index = 0; index < scope.length; index++) {
32
+ const segment: unknown = scope[index];
33
+ const which = `scope segment ${index + 1}`;
34
+ if (typeof segment !== "string" || segment.length < 1 || segment.length > MAX_SCOPE_SEGMENT_LENGTH) {
35
+ throw new DocumentScopeError("scope_invalid", `${which} must be a string of 1 to ${MAX_SCOPE_SEGMENT_LENGTH} characters. ${SHAPE}`);
36
+ }
37
+ if (segment === "." || segment === "..") throw new DocumentScopeError("scope_invalid", `${which} cannot be "." or "..".`);
38
+ if (FORBIDDEN.test(segment)) throw new DocumentScopeError("scope_invalid", `${which} cannot hold "/", "\\" or control characters.`);
39
+ segments.push(segment);
40
+ }
41
+ return Object.freeze(segments);
42
+ }
43
+
44
+ /**
45
+ * A scope as one string, to key maps and caches by: its segments, each URI-encoded, joined with
46
+ * "/". Two scopes give the same key only when they are the same, and no scope gives "", which is
47
+ * the key of no scope. Check the scope first (`checkScope`): a segment with half of a surrogate
48
+ * pair cannot be encoded.
49
+ */
50
+ export function scopeKey(scope: DocumentScope | undefined): string {
51
+ return scope === undefined ? "" : scope.map(encodeURIComponent).join("/");
52
+ }
53
+
54
+ /**
55
+ * Whether two scopes are the same, segment by segment. No scope is the same as no scope only; null
56
+ * counts as no scope, as a database may give it for a field that was left out.
57
+ */
58
+ export function sameScope(left: DocumentScope | null | undefined, right: DocumentScope | null | undefined): boolean {
59
+ if (left === undefined || left === null || right === undefined || right === null) {
60
+ return (left === undefined || left === null) && (right === undefined || right === null);
61
+ }
62
+ return left.length === right.length && left.every((segment, index) => segment === right[index]);
63
+ }
package/src/search.ts CHANGED
@@ -6,6 +6,12 @@ import { composed, foldCase, LineIndex, sliceWhole } from "./text.js";
6
6
  import type { DocumentMeta, StoredDocument } from "./types.js";
7
7
 
8
8
  const MAX_OCCURRENCES_PER_TERM = 200_000;
9
+ /**
10
+ * Past this many matching lines, an exact search goes on counting them within the time of a regex
11
+ * search (`REGEX_TIME_LIMIT_MS`, or the search's own `timeLimitMs`), and stops when that is up. It
12
+ * keeps no more of them than before: the lines it shows, and the last one. Until 0.10.0 it stopped
13
+ * here, and a count of 1,200,000 lines read 1,000,000, a lower bound.
14
+ */
9
15
  const MAX_EXACT_MATCHES = 1_000_000;
10
16
  const MAX_PHRASE_PASSAGES = 10_000;
11
17
  /** The most time one regex search may spend matching. */
@@ -599,6 +605,8 @@ class LineSearch {
599
605
  private batch?: { lines: Int32Array; columns: Int32Array; keys: Array<string | undefined> };
600
606
  /** Exact mode: the scan of the piece that stopped at the end of a time slice. */
601
607
  private exactLeft?: ExactScan;
608
+ /** Exact mode: true once `MAX_EXACT_MATCHES` lines were counted, and the scan goes on within a time limit. */
609
+ private pastCap = false;
602
610
  /** The lines looked at: matches outside them are neither counted nor shown. */
603
611
  private readonly fromLine: number;
604
612
  private readonly toLine: number;
@@ -635,7 +643,7 @@ class LineSearch {
635
643
  }
636
644
  // A plain exact search runs to the end, in slices with pauses: its time follows the text, and its
637
645
  // count must be whole. Only the work that grows with each occurrence (a whole-word check, a group
638
- // key) has a limit, as a regex search does.
646
+ // key) has a limit, as a regex search does; and the lines past `MAX_EXACT_MATCHES` (`scanExact`).
639
647
  this.timeLeft = settings.timeLimitMs ?? (settings.regex ? REGEX_TIME_LIMIT_MS : settings.wholeWord || settings.groupBy ? EXACT_TIME_LIMIT_MS : Number.POSITIVE_INFINITY);
640
648
  this.lastOnes = settings.order === "last";
641
649
  if (settings.groupBy) {
@@ -842,9 +850,11 @@ class LineSearch {
842
850
  const lineText = lines.line(local);
843
851
  this.record(line, at - lines.startOf(local), lineText, this.groups?.keyOf(lineText, undefined));
844
852
  if (this.done) break;
845
- if (this.total >= MAX_EXACT_MATCHES) {
846
- this.stop();
847
- break;
853
+ if (this.total >= MAX_EXACT_MATCHES && !this.pastCap) {
854
+ // The count goes on, within the time of a regex search from here: a plain exact search
855
+ // has no limit of its own, and the lines past this many cost a step each.
856
+ this.pastCap = true;
857
+ this.timeLeft = Math.min(this.timeLeft, this.settings.timeLimitMs ?? REGEX_TIME_LIMIT_MS);
848
858
  }
849
859
  }
850
860
  at = next >= text.length ? -1 : this.find(text, next);
@@ -1152,6 +1162,55 @@ export function queryTerms(query: string): string[] {
1152
1162
 
1153
1163
  export type RankedPassage = { from: number; to: number; score: number };
1154
1164
 
1165
+ /**
1166
+ * The `count` entries of `scores` with the highest score, best first, of those `keep` keeps: what a
1167
+ * stable sort by score, then a slice, gives (of two equal scores, the one met first comes first),
1168
+ * with a heap of `count` entries in place of a sort of all of them. A keyword search of a large
1169
+ * file scores tens of thousands of passages and shows 10 at most. New in 0.10.0 (P9).
1170
+ */
1171
+ export function topScored<K>(scores: Iterable<readonly [K, number]>, count: number, keep: (key: K) => boolean = () => true): Array<[K, number]> {
1172
+ const most = Math.max(0, Math.trunc(count));
1173
+ if (most === 0) return [];
1174
+ // A heap with the worst entry kept at its root: the lowest score, and of equal scores the one met last.
1175
+ const heap: Array<{ key: K; score: number; order: number }> = [];
1176
+ const worse = (left: (typeof heap)[number], right: (typeof heap)[number]) => left.score < right.score || (left.score === right.score && left.order > right.order);
1177
+ const swap = (at: number, other: number) => {
1178
+ const entry = heap[at]!;
1179
+ heap[at] = heap[other]!;
1180
+ heap[other] = entry;
1181
+ };
1182
+ let order = 0;
1183
+ for (const [key, score] of scores) {
1184
+ if (!keep(key)) continue;
1185
+ const entry = { key, score, order: order++ };
1186
+ if (heap.length < most) {
1187
+ heap.push(entry);
1188
+ for (let at = heap.length - 1; at > 0;) {
1189
+ const parent = (at - 1) >> 1;
1190
+ if (!worse(heap[at]!, heap[parent]!)) break;
1191
+ swap(at, parent);
1192
+ at = parent;
1193
+ }
1194
+ continue;
1195
+ }
1196
+ // An entry met later is worse than one met earlier with the same score: it takes the place of
1197
+ // the worst only with a higher score.
1198
+ if (!(score > heap[0]!.score)) continue;
1199
+ heap[0] = entry;
1200
+ for (let at = 0; ;) {
1201
+ const left = 2 * at + 1;
1202
+ const right = left + 1;
1203
+ let worst = at;
1204
+ if (left < heap.length && worse(heap[left]!, heap[worst]!)) worst = left;
1205
+ if (right < heap.length && worse(heap[right]!, heap[worst]!)) worst = right;
1206
+ if (worst === at) break;
1207
+ swap(at, worst);
1208
+ at = worst;
1209
+ }
1210
+ }
1211
+ return heap.sort((left, right) => right.score - left.score || left.order - right.order).map(({ key, score }) => [key, score]);
1212
+ }
1213
+
1155
1214
  /**
1156
1215
  * BM25 over fixed passages, computed at query time from substring hits, over a document fed a
1157
1216
  * piece at a time (pieces start at passage starts). No index to build or store, works for any
@@ -1276,15 +1335,12 @@ class PassageRank {
1276
1335
  }
1277
1336
  if (this.phrase) for (const passage of this.phrase.passages) scores.set(passage, (scores.get(passage) ?? 0) * 1.5 + 1);
1278
1337
  const range = this.range;
1279
- return [...scores.entries()]
1280
- .filter(([passage]) => {
1281
- if (!range) return true;
1282
- const { from, to } = this.rangeOf(passage);
1283
- return to >= range.from && from <= range.to;
1284
- })
1285
- .sort((left, right) => right[1] - left[1])
1286
- .slice(0, topK)
1287
- .map(([passage, score]) => ({ ...this.rangeOf(passage), score: Math.round(score * 100) / 100 }));
1338
+ const inRange = (passage: number) => {
1339
+ if (!range) return true;
1340
+ const { from, to } = this.rangeOf(passage);
1341
+ return to >= range.from && from <= range.to;
1342
+ };
1343
+ return topScored(scores, topK, inRange).map(([passage, score]) => ({ ...this.rangeOf(passage), score: Math.round(score * 100) / 100 }));
1288
1344
  }
1289
1345
 
1290
1346
  private passageOf(line: number): number {
package/src/source.ts ADDED
@@ -0,0 +1,178 @@
1
+ // Files ingested from a path (`IngestFromSource`), and the SHA-256 of what is ingested. New in 0.9.0.
2
+ // A file is looked at before the ingest's turn without being read (its size), read once when its
3
+ // turn comes, never past the upload limit, and hashed a slice at a time as it is read. Nothing
4
+ // here writes, moves or deletes a file.
5
+ import { createHash } from "node:crypto";
6
+ import { constants, type Stats } from "node:fs";
7
+ import { lstat, open } from "node:fs/promises";
8
+ import nodePath, { type PlatformPath } from "node:path";
9
+ import type { TimeSlicer } from "./pause.js";
10
+
11
+ /**
12
+ * How a file is opened to be read: never through a link at its name, where the platform can
13
+ * (`O_NOFOLLOW`; Windows has none), and without waiting for a writer when it is a pipe
14
+ * (`O_NONBLOCK`, which changes nothing for a file). What is opened is then checked to be a file.
15
+ */
16
+ export const READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
17
+
18
+ /**
19
+ * `path` made absolute, as text: an absolute path as it is, a relative one after the working
20
+ * directory and a separator. Nothing in it is normalized, so a ".." after a link, and a "/" at the
21
+ * end, are the system's to resolve, as they are in an absolute path: both spellings of a path read
22
+ * the same file. (`path.resolve` would remove them as text first.) On Windows, a path relative to
23
+ * the working directory of a drive ("C:notes.txt") is made absolute by `path.resolve`, which alone
24
+ * knows that directory. The working directory is asked for only for a relative path: an absolute
25
+ * one is read even when the working directory has been removed (where `process.cwd()` throws).
26
+ * `paths` and `cwd` are given by tests.
27
+ */
28
+ export function absolutePath(path: string, paths: PlatformPath = nodePath, cwd?: string): string {
29
+ if (paths.isAbsolute(path)) return path;
30
+ if (paths.sep === "\\" && /^[A-Za-z]:/.test(path)) return paths.resolve(path);
31
+ const base = cwd ?? process.cwd();
32
+ return base.endsWith(paths.sep) ? base + path : base + paths.sep + path;
33
+ }
34
+
35
+ /** How much is read, and hashed, between two looks at the clock: 1 MB. */
36
+ export const SLICE_BYTES = 1024 * 1024;
37
+
38
+ /**
39
+ * The error of a path that names no file the library reads, in the shape of a system error: a code
40
+ * and a system call, so that it is passed on as the server's trouble, not told as a file a user
41
+ * sent that cannot be read. Its message names no path.
42
+ */
43
+ function pathError(message: string, code: string, syscall: string): Error {
44
+ return Object.assign(new Error(message), { code, syscall });
45
+ }
46
+
47
+ /** Throws unless `info` is that of a file: not a link, a folder, a pipe or a device. */
48
+ function checkFile(info: Stats, syscall: string): void {
49
+ if (info.isSymbolicLink()) throw pathError("The file to ingest is a link, which is not followed.", "ELOOP", syscall);
50
+ if (info.isDirectory()) throw pathError("The path to ingest is a folder, not a file.", "EISDIR", syscall);
51
+ if (!info.isFile()) throw pathError("The path to ingest is not a file.", "EINVAL", syscall);
52
+ }
53
+
54
+ /**
55
+ * The size of the file at `path`, from `lstat`: a link is refused, not followed, and so is anything
56
+ * that is not a file. Nothing of the file is read.
57
+ */
58
+ export async function statSource(path: string): Promise<number> {
59
+ const info = await lstat(path);
60
+ checkFile(info, "lstat");
61
+ return info.size;
62
+ }
63
+
64
+ /** An array of exactly `size` bytes, not filled: every byte is written before it is used. */
65
+ function unfilled(size: number): Uint8Array {
66
+ const buffer = Buffer.allocUnsafeSlow(size);
67
+ // A plain Uint8Array over the whole of its own memory, which is exactly `size` bytes: once it is
68
+ // filled, nothing under it is left unwritten.
69
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, size);
70
+ }
71
+
72
+ /** What `readSource` read: the bytes when they were kept, how many there were, and their SHA-256. */
73
+ export type SourceRead = {
74
+ /** The bytes read, in an array of exactly `size` bytes, when they were kept. */
75
+ bytes?: Uint8Array;
76
+ /** How many bytes were read: the size of the file, or `maxBytes + 1` when it has more than `maxBytes`. */
77
+ size: number;
78
+ /** The SHA-256 of the bytes read, as 64 lowercase hex digits. */
79
+ sha256: string;
80
+ };
81
+
82
+ /**
83
+ * Reads the file at `path` once, from its start: at most `maxBytes + 1` bytes, so that a file that
84
+ * has grown past `maxBytes` since it was looked at is told (`size` above `maxBytes`) without
85
+ * reading the rest: the caller refuses it. The bytes are hashed a slice (`SLICE_BYTES`) at a time, `slicer` may pause
86
+ * between two slices, and `signal` stops the read between two slices. `keep` false hashes the bytes
87
+ * and lets each slice go: only the size and the SHA-256 come back.
88
+ */
89
+ export async function readSource(path: string, maxBytes: number, options: { keep: boolean; slicer?: TimeSlicer; signal?: AbortSignal }): Promise<SourceRead> {
90
+ const { keep, slicer, signal } = options;
91
+ signal?.throwIfAborted();
92
+ const limit = maxBytes + 1;
93
+ const handle = await open(path, READ_FLAGS);
94
+ try {
95
+ const info = await handle.stat();
96
+ checkFile(info, "fstat");
97
+ const hash = createHash("sha256");
98
+ // Kept: the first array has the size the file has now (no more than the limit), so the usual
99
+ // file is read into one array of its exact size; a file that grows meanwhile goes on in arrays
100
+ // of a slice. Not kept: one slice is read into again and again.
101
+ const full: Uint8Array[] = [];
102
+ let current = unfilled(keep ? Math.min(info.size, limit) : SLICE_BYTES);
103
+ let filled = 0;
104
+ let size = 0;
105
+ while (size < limit) {
106
+ if (filled === current.byteLength) {
107
+ if (keep) {
108
+ if (filled > 0) full.push(current);
109
+ current = unfilled(Math.min(SLICE_BYTES, limit - size));
110
+ }
111
+ filled = 0;
112
+ }
113
+ // Never past the limit: the slice read into again and again (not kept) is larger than what is left.
114
+ const { bytesRead } = await handle.read(current, filled, Math.min(SLICE_BYTES, current.byteLength - filled, limit - size), size);
115
+ if (bytesRead === 0) break;
116
+ hash.update(current.subarray(filled, filled + bytesRead));
117
+ filled += bytesRead;
118
+ size += bytesRead;
119
+ signal?.throwIfAborted();
120
+ await slicer?.maybePause();
121
+ }
122
+ const sha256 = hash.digest("hex");
123
+ if (!keep) return { size, sha256 };
124
+ if (full.length === 0 && filled === current.byteLength) return { bytes: current, size, sha256 };
125
+ if (full.length === 1 && filled === 0) return { bytes: full[0]!, size, sha256 };
126
+ // A file that shrank, or grew, while it was read: its bytes in one array of their exact size.
127
+ const bytes = unfilled(size);
128
+ let at = 0;
129
+ for (const part of [...full, current.subarray(0, filled)]) {
130
+ bytes.set(part, at);
131
+ at += part.byteLength;
132
+ }
133
+ return { bytes, size, sha256 };
134
+ } finally {
135
+ await handle.close();
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Bytes `start` (inclusive) to `end` (exclusive) of each range of the file at `path`, read in one
141
+ * opening of it, as `readSource` opens it: fewer at the end of a file that has shrunk.
142
+ */
143
+ export async function readRanges(path: string, ranges: ReadonlyArray<readonly [number, number]>): Promise<Uint8Array[]> {
144
+ const handle = await open(path, READ_FLAGS);
145
+ try {
146
+ checkFile(await handle.stat(), "fstat");
147
+ const parts: Uint8Array[] = [];
148
+ for (const [start, end] of ranges) {
149
+ const part = new Uint8Array(Math.max(0, end - start));
150
+ let filled = 0;
151
+ while (filled < part.byteLength) {
152
+ const { bytesRead } = await handle.read(part, filled, part.byteLength - filled, start + filled);
153
+ if (bytesRead === 0) break;
154
+ filled += bytesRead;
155
+ }
156
+ parts.push(part.subarray(0, filled));
157
+ }
158
+ return parts;
159
+ } finally {
160
+ await handle.close();
161
+ }
162
+ }
163
+
164
+ /**
165
+ * The SHA-256 of `bytes`, as 64 lowercase hex digits, hashed a slice (`SLICE_BYTES`) at a time:
166
+ * `slicer` may pause between two slices, so that a large file does not hold the server.
167
+ */
168
+ export async function sha256InSlices(bytes: Uint8Array, slicer?: TimeSlicer): Promise<string> {
169
+ const hash = createHash("sha256");
170
+ for (let at = 0; at < bytes.byteLength; at += SLICE_BYTES) {
171
+ hash.update(bytes.subarray(at, at + SLICE_BYTES));
172
+ await slicer?.maybePause();
173
+ }
174
+ return hash.digest("hex");
175
+ }
176
+
177
+ /** Whether `value` is a SHA-256 as the library writes it: 64 lowercase hex digits. */
178
+ export const isSha256 = (value: unknown): value is string => typeof value === "string" && /^[0-9a-f]{64}$/.test(value);