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/scope.js ADDED
@@ -0,0 +1,60 @@
1
+ // Scopes (`DocumentScope`): where a document belongs, such as [userId, chatId]. New in 0.9.0.
2
+ import { DocumentScopeError } from "./errors.js";
3
+ /** The most segments a scope may have. */
4
+ export const MAX_SCOPE_SEGMENTS = 8;
5
+ /** The most UTF-16 units one segment may have. */
6
+ export const MAX_SCOPE_SEGMENT_LENGTH = 256;
7
+ /**
8
+ * What a segment may not hold: "/" and "\" (path separators on every system), control characters
9
+ * (NUL, line breaks, C1), and half of a surrogate pair, which has no UTF-8 form.
10
+ */
11
+ const FORBIDDEN = /[/\\\p{Cc}\p{Cs}]/u;
12
+ const SHAPE = `scope must be an array of 1 to ${MAX_SCOPE_SEGMENTS} strings, such as [userId, chatId].`;
13
+ /**
14
+ * A scope given to the library, checked: a frozen copy of it, or undefined when there is none.
15
+ * Throws a `DocumentScopeError` with code "scope_invalid" unless it is an array of 1 to 8 strings,
16
+ * each of 1 to 256 UTF-16 units, with no control characters, no "/" or "\", and none of them "." or
17
+ * "..". The message says which segment is wrong, not what it holds: a segment may be a user's ID.
18
+ */
19
+ export function checkScope(scope) {
20
+ if (scope === undefined)
21
+ return undefined;
22
+ if (!Array.isArray(scope) || scope.length < 1 || scope.length > MAX_SCOPE_SEGMENTS) {
23
+ throw new DocumentScopeError("scope_invalid", SHAPE);
24
+ }
25
+ const segments = [];
26
+ // An index loop, not `map`: a hole in the array is a segment that is missing.
27
+ for (let index = 0; index < scope.length; index++) {
28
+ const segment = scope[index];
29
+ const which = `scope segment ${index + 1}`;
30
+ if (typeof segment !== "string" || segment.length < 1 || segment.length > MAX_SCOPE_SEGMENT_LENGTH) {
31
+ throw new DocumentScopeError("scope_invalid", `${which} must be a string of 1 to ${MAX_SCOPE_SEGMENT_LENGTH} characters. ${SHAPE}`);
32
+ }
33
+ if (segment === "." || segment === "..")
34
+ throw new DocumentScopeError("scope_invalid", `${which} cannot be "." or "..".`);
35
+ if (FORBIDDEN.test(segment))
36
+ throw new DocumentScopeError("scope_invalid", `${which} cannot hold "/", "\\" or control characters.`);
37
+ segments.push(segment);
38
+ }
39
+ return Object.freeze(segments);
40
+ }
41
+ /**
42
+ * A scope as one string, to key maps and caches by: its segments, each URI-encoded, joined with
43
+ * "/". Two scopes give the same key only when they are the same, and no scope gives "", which is
44
+ * the key of no scope. Check the scope first (`checkScope`): a segment with half of a surrogate
45
+ * pair cannot be encoded.
46
+ */
47
+ export function scopeKey(scope) {
48
+ return scope === undefined ? "" : scope.map(encodeURIComponent).join("/");
49
+ }
50
+ /**
51
+ * Whether two scopes are the same, segment by segment. No scope is the same as no scope only; null
52
+ * counts as no scope, as a database may give it for a field that was left out.
53
+ */
54
+ export function sameScope(left, right) {
55
+ if (left === undefined || left === null || right === undefined || right === null) {
56
+ return (left === undefined || left === null) && (right === undefined || right === null);
57
+ }
58
+ return left.length === right.length && left.every((segment, index) => segment === right[index]);
59
+ }
60
+ //# sourceMappingURL=scope.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scope.js","sourceRoot":"","sources":["../src/scope.ts"],"names":[],"mappings":"AAAA,8FAA8F;AAC9F,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAGjD,0CAA0C;AAC1C,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,CAAC;AACpC,kDAAkD;AAClD,MAAM,CAAC,MAAM,wBAAwB,GAAG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AC,IAAI,CAAC,OAAO,CAAC,CAAC;IACzB,CAAC;IACD,OAAO,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AACjC,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,QAAQ,CAAC,KAAgC;IACvD,OAAO,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC5E,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,SAAS,CAAC,IAAsC,EAAE,KAAuC;IACvG,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;QACjF,OAAO,CAAC,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,IAAI,CAAC,IAAI,CAAC,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI,CAAC,CAAC;IAC1F,CAAC;IACD,OAAO,IAAI,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE,CAAC,OAAO,KAAK,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;AAClG,CAAC"}
@@ -0,0 +1,60 @@
1
+ import { type PlatformPath } from "node:path";
2
+ import type { TimeSlicer } from "./pause.js";
3
+ /**
4
+ * How a file is opened to be read: never through a link at its name, where the platform can
5
+ * (`O_NOFOLLOW`; Windows has none), and without waiting for a writer when it is a pipe
6
+ * (`O_NONBLOCK`, which changes nothing for a file). What is opened is then checked to be a file.
7
+ */
8
+ export declare const READ_FLAGS: number;
9
+ /**
10
+ * `path` made absolute, as text: an absolute path as it is, a relative one after the working
11
+ * directory and a separator. Nothing in it is normalized, so a ".." after a link, and a "/" at the
12
+ * end, are the system's to resolve, as they are in an absolute path: both spellings of a path read
13
+ * the same file. (`path.resolve` would remove them as text first.) On Windows, a path relative to
14
+ * the working directory of a drive ("C:notes.txt") is made absolute by `path.resolve`, which alone
15
+ * knows that directory. The working directory is asked for only for a relative path: an absolute
16
+ * one is read even when the working directory has been removed (where `process.cwd()` throws).
17
+ * `paths` and `cwd` are given by tests.
18
+ */
19
+ export declare function absolutePath(path: string, paths?: PlatformPath, cwd?: string): string;
20
+ /** How much is read, and hashed, between two looks at the clock: 1 MB. */
21
+ export declare const SLICE_BYTES: number;
22
+ /**
23
+ * The size of the file at `path`, from `lstat`: a link is refused, not followed, and so is anything
24
+ * that is not a file. Nothing of the file is read.
25
+ */
26
+ export declare function statSource(path: string): Promise<number>;
27
+ /** What `readSource` read: the bytes when they were kept, how many there were, and their SHA-256. */
28
+ export type SourceRead = {
29
+ /** The bytes read, in an array of exactly `size` bytes, when they were kept. */
30
+ bytes?: Uint8Array;
31
+ /** How many bytes were read: the size of the file, or `maxBytes + 1` when it has more than `maxBytes`. */
32
+ size: number;
33
+ /** The SHA-256 of the bytes read, as 64 lowercase hex digits. */
34
+ sha256: string;
35
+ };
36
+ /**
37
+ * Reads the file at `path` once, from its start: at most `maxBytes + 1` bytes, so that a file that
38
+ * has grown past `maxBytes` since it was looked at is told (`size` above `maxBytes`) without
39
+ * reading the rest: the caller refuses it. The bytes are hashed a slice (`SLICE_BYTES`) at a time, `slicer` may pause
40
+ * between two slices, and `signal` stops the read between two slices. `keep` false hashes the bytes
41
+ * and lets each slice go: only the size and the SHA-256 come back.
42
+ */
43
+ export declare function readSource(path: string, maxBytes: number, options: {
44
+ keep: boolean;
45
+ slicer?: TimeSlicer;
46
+ signal?: AbortSignal;
47
+ }): Promise<SourceRead>;
48
+ /**
49
+ * Bytes `start` (inclusive) to `end` (exclusive) of each range of the file at `path`, read in one
50
+ * opening of it, as `readSource` opens it: fewer at the end of a file that has shrunk.
51
+ */
52
+ export declare function readRanges(path: string, ranges: ReadonlyArray<readonly [number, number]>): Promise<Uint8Array[]>;
53
+ /**
54
+ * The SHA-256 of `bytes`, as 64 lowercase hex digits, hashed a slice (`SLICE_BYTES`) at a time:
55
+ * `slicer` may pause between two slices, so that a large file does not hold the server.
56
+ */
57
+ export declare function sha256InSlices(bytes: Uint8Array, slicer?: TimeSlicer): Promise<string>;
58
+ /** Whether `value` is a SHA-256 as the library writes it: 64 lowercase hex digits. */
59
+ export declare const isSha256: (value: unknown) => value is string;
60
+ //# sourceMappingURL=source.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"source.d.ts","sourceRoot":"","sources":["../src/source.ts"],"names":[],"mappings":"AAOA,OAAiB,EAAE,KAAK,YAAY,EAAE,MAAM,WAAW,CAAC;AACxD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE7C;;;;GAIG;AACH,eAAO,MAAM,UAAU,QAAiF,CAAC;AAEzG;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,GAAE,YAAuB,EAAE,GAAG,CAAC,EAAE,MAAM,GAAG,MAAM,CAK/F;AAED,0EAA0E;AAC1E,eAAO,MAAM,WAAW,QAAc,CAAC;AAkBvC;;;GAGG;AACH,wBAAsB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAI9D;AAUD,qGAAqG;AACrG,MAAM,MAAM,UAAU,GAAG;IACvB,gFAAgF;IAChF,KAAK,CAAC,EAAE,UAAU,CAAC;IACnB,0GAA0G;IAC1G,IAAI,EAAE,MAAM,CAAC;IACb,iEAAiE;IACjE,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;;;;;GAMG;AACH,wBAAsB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,MAAM,CAAC,EAAE,UAAU,CAAC;IAAC,MAAM,CAAC,EAAE,WAAW,CAAA;CAAE,GAAG,OAAO,CAAC,UAAU,CAAC,CAgD3J;AAED;;;GAGG;AACH,wBAAsB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,aAAa,CAAC,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GAAG,OAAO,CAAC,UAAU,EAAE,CAAC,CAmBtH;AAED;;;GAGG;AACH,wBAAsB,cAAc,CAAC,KAAK,EAAE,UAAU,EAAE,MAAM,CAAC,EAAE,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAO5F;AAED,sFAAsF;AACtF,eAAO,MAAM,QAAQ,GAAI,OAAO,OAAO,KAAG,KAAK,IAAI,MAAmE,CAAC"}
package/dist/source.js ADDED
@@ -0,0 +1,170 @@
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 } from "node:fs";
7
+ import { lstat, open } from "node:fs/promises";
8
+ import nodePath from "node:path";
9
+ /**
10
+ * How a file is opened to be read: never through a link at its name, where the platform can
11
+ * (`O_NOFOLLOW`; Windows has none), and without waiting for a writer when it is a pipe
12
+ * (`O_NONBLOCK`, which changes nothing for a file). What is opened is then checked to be a file.
13
+ */
14
+ export const READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
15
+ /**
16
+ * `path` made absolute, as text: an absolute path as it is, a relative one after the working
17
+ * directory and a separator. Nothing in it is normalized, so a ".." after a link, and a "/" at the
18
+ * end, are the system's to resolve, as they are in an absolute path: both spellings of a path read
19
+ * the same file. (`path.resolve` would remove them as text first.) On Windows, a path relative to
20
+ * the working directory of a drive ("C:notes.txt") is made absolute by `path.resolve`, which alone
21
+ * knows that directory. The working directory is asked for only for a relative path: an absolute
22
+ * one is read even when the working directory has been removed (where `process.cwd()` throws).
23
+ * `paths` and `cwd` are given by tests.
24
+ */
25
+ export function absolutePath(path, paths = nodePath, cwd) {
26
+ if (paths.isAbsolute(path))
27
+ return path;
28
+ if (paths.sep === "\\" && /^[A-Za-z]:/.test(path))
29
+ return paths.resolve(path);
30
+ const base = cwd ?? process.cwd();
31
+ return base.endsWith(paths.sep) ? base + path : base + paths.sep + path;
32
+ }
33
+ /** How much is read, and hashed, between two looks at the clock: 1 MB. */
34
+ export const SLICE_BYTES = 1024 * 1024;
35
+ /**
36
+ * The error of a path that names no file the library reads, in the shape of a system error: a code
37
+ * and a system call, so that it is passed on as the server's trouble, not told as a file a user
38
+ * sent that cannot be read. Its message names no path.
39
+ */
40
+ function pathError(message, code, syscall) {
41
+ return Object.assign(new Error(message), { code, syscall });
42
+ }
43
+ /** Throws unless `info` is that of a file: not a link, a folder, a pipe or a device. */
44
+ function checkFile(info, syscall) {
45
+ if (info.isSymbolicLink())
46
+ throw pathError("The file to ingest is a link, which is not followed.", "ELOOP", syscall);
47
+ if (info.isDirectory())
48
+ throw pathError("The path to ingest is a folder, not a file.", "EISDIR", syscall);
49
+ if (!info.isFile())
50
+ throw pathError("The path to ingest is not a file.", "EINVAL", syscall);
51
+ }
52
+ /**
53
+ * The size of the file at `path`, from `lstat`: a link is refused, not followed, and so is anything
54
+ * that is not a file. Nothing of the file is read.
55
+ */
56
+ export async function statSource(path) {
57
+ const info = await lstat(path);
58
+ checkFile(info, "lstat");
59
+ return info.size;
60
+ }
61
+ /** An array of exactly `size` bytes, not filled: every byte is written before it is used. */
62
+ function unfilled(size) {
63
+ const buffer = Buffer.allocUnsafeSlow(size);
64
+ // A plain Uint8Array over the whole of its own memory, which is exactly `size` bytes: once it is
65
+ // filled, nothing under it is left unwritten.
66
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, size);
67
+ }
68
+ /**
69
+ * Reads the file at `path` once, from its start: at most `maxBytes + 1` bytes, so that a file that
70
+ * has grown past `maxBytes` since it was looked at is told (`size` above `maxBytes`) without
71
+ * reading the rest: the caller refuses it. The bytes are hashed a slice (`SLICE_BYTES`) at a time, `slicer` may pause
72
+ * between two slices, and `signal` stops the read between two slices. `keep` false hashes the bytes
73
+ * and lets each slice go: only the size and the SHA-256 come back.
74
+ */
75
+ export async function readSource(path, maxBytes, options) {
76
+ const { keep, slicer, signal } = options;
77
+ signal?.throwIfAborted();
78
+ const limit = maxBytes + 1;
79
+ const handle = await open(path, READ_FLAGS);
80
+ try {
81
+ const info = await handle.stat();
82
+ checkFile(info, "fstat");
83
+ const hash = createHash("sha256");
84
+ // Kept: the first array has the size the file has now (no more than the limit), so the usual
85
+ // file is read into one array of its exact size; a file that grows meanwhile goes on in arrays
86
+ // of a slice. Not kept: one slice is read into again and again.
87
+ const full = [];
88
+ let current = unfilled(keep ? Math.min(info.size, limit) : SLICE_BYTES);
89
+ let filled = 0;
90
+ let size = 0;
91
+ while (size < limit) {
92
+ if (filled === current.byteLength) {
93
+ if (keep) {
94
+ if (filled > 0)
95
+ full.push(current);
96
+ current = unfilled(Math.min(SLICE_BYTES, limit - size));
97
+ }
98
+ filled = 0;
99
+ }
100
+ // Never past the limit: the slice read into again and again (not kept) is larger than what is left.
101
+ const { bytesRead } = await handle.read(current, filled, Math.min(SLICE_BYTES, current.byteLength - filled, limit - size), size);
102
+ if (bytesRead === 0)
103
+ break;
104
+ hash.update(current.subarray(filled, filled + bytesRead));
105
+ filled += bytesRead;
106
+ size += bytesRead;
107
+ signal?.throwIfAborted();
108
+ await slicer?.maybePause();
109
+ }
110
+ const sha256 = hash.digest("hex");
111
+ if (!keep)
112
+ return { size, sha256 };
113
+ if (full.length === 0 && filled === current.byteLength)
114
+ return { bytes: current, size, sha256 };
115
+ if (full.length === 1 && filled === 0)
116
+ return { bytes: full[0], size, sha256 };
117
+ // A file that shrank, or grew, while it was read: its bytes in one array of their exact size.
118
+ const bytes = unfilled(size);
119
+ let at = 0;
120
+ for (const part of [...full, current.subarray(0, filled)]) {
121
+ bytes.set(part, at);
122
+ at += part.byteLength;
123
+ }
124
+ return { bytes, size, sha256 };
125
+ }
126
+ finally {
127
+ await handle.close();
128
+ }
129
+ }
130
+ /**
131
+ * Bytes `start` (inclusive) to `end` (exclusive) of each range of the file at `path`, read in one
132
+ * opening of it, as `readSource` opens it: fewer at the end of a file that has shrunk.
133
+ */
134
+ export async function readRanges(path, ranges) {
135
+ const handle = await open(path, READ_FLAGS);
136
+ try {
137
+ checkFile(await handle.stat(), "fstat");
138
+ const parts = [];
139
+ for (const [start, end] of ranges) {
140
+ const part = new Uint8Array(Math.max(0, end - start));
141
+ let filled = 0;
142
+ while (filled < part.byteLength) {
143
+ const { bytesRead } = await handle.read(part, filled, part.byteLength - filled, start + filled);
144
+ if (bytesRead === 0)
145
+ break;
146
+ filled += bytesRead;
147
+ }
148
+ parts.push(part.subarray(0, filled));
149
+ }
150
+ return parts;
151
+ }
152
+ finally {
153
+ await handle.close();
154
+ }
155
+ }
156
+ /**
157
+ * The SHA-256 of `bytes`, as 64 lowercase hex digits, hashed a slice (`SLICE_BYTES`) at a time:
158
+ * `slicer` may pause between two slices, so that a large file does not hold the server.
159
+ */
160
+ export async function sha256InSlices(bytes, slicer) {
161
+ const hash = createHash("sha256");
162
+ for (let at = 0; at < bytes.byteLength; at += SLICE_BYTES) {
163
+ hash.update(bytes.subarray(at, at + SLICE_BYTES));
164
+ await slicer?.maybePause();
165
+ }
166
+ return hash.digest("hex");
167
+ }
168
+ /** Whether `value` is a SHA-256 as the library writes it: 64 lowercase hex digits. */
169
+ export const isSha256 = (value) => typeof value === "string" && /^[0-9a-f]{64}$/.test(value);
170
+ //# sourceMappingURL=source.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"source.js","sourceRoot":"","sources":["../src/source.ts"],"names":[],"mappings":"AAAA,sGAAsG;AACtG,iGAAiG;AACjG,+FAA+F;AAC/F,wCAAwC;AACxC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,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AAmB,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,gBAAgB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC"}
package/dist/stores.d.ts CHANGED
@@ -1,55 +1,139 @@
1
- import type { DocumentMeta, DocumentStore, StoredDocument } from "./types.js";
1
+ import type { DocumentContext, DocumentMeta, DocumentStore, StoredDocument } from "./types.js";
2
+ /** The shape of the document IDs the library makes: "doc_" and 32 hex digits. */
2
3
  export declare const DOCUMENT_ID_PATTERN: RegExp;
3
- /** Keeps documents in process memory. Good for tests and single-process demos. */
4
+ /**
5
+ * The shape of a document ID an application may choose (`IngestInput.id`): lowercase letters,
6
+ * digits, "_" and "-", up to 64 characters, starting with a letter or a digit, and not a name
7
+ * Windows keeps for a device (`con`, `prn`, `aux`, `nul`, `com0`-`com9`, `lpt0`-`lpt9`), which
8
+ * cannot name a file there. The IDs the library makes have it too. New in 0.9.0.
9
+ */
10
+ export declare const APP_DOCUMENT_ID_PATTERN: RegExp;
11
+ /**
12
+ * The version of `DocumentMeta` this package writes (`metaVersion`), and the highest it reads.
13
+ * New in 0.9.0: metadata without a version is that of an earlier version, and is read as before.
14
+ */
15
+ export declare const DOCUMENT_META_VERSION = 1;
16
+ /**
17
+ * Keeps documents in process memory. Good for tests and single-process demos.
18
+ *
19
+ * The documents of each scope (`DocumentContext.scope`) are kept apart: one ID in two scopes is two
20
+ * documents. Calls without a scope share the documents of no scope, as every call did before 0.9.0.
21
+ */
4
22
  export declare class MemoryDocumentStore implements DocumentStore {
23
+ #private;
24
+ /** The documents of no scope, by ID, as all documents were kept before 0.9.0. */
5
25
  private readonly documents;
26
+ /** The original files of the documents of no scope. */
6
27
  private readonly originals;
7
28
  private readonly now;
8
29
  constructor(options?: {
9
30
  now?: () => Date;
10
31
  });
11
- put(document: StoredDocument): Promise<void>;
12
- get(id: string): Promise<StoredDocument | undefined>;
13
- getMeta(id: string): Promise<DocumentMeta | undefined>;
14
- delete(id: string): Promise<boolean>;
15
- sweep(now?: Date): Promise<number>;
16
- putOriginal(id: string, bytes: Uint8Array): Promise<void>;
17
- getOriginal(id: string): Promise<Uint8Array | undefined>;
32
+ put(document: StoredDocument, context?: DocumentContext): Promise<void>;
33
+ get(id: string, context?: DocumentContext): Promise<StoredDocument | undefined>;
34
+ getMeta(id: string, context?: DocumentContext): Promise<DocumentMeta | undefined>;
35
+ delete(id: string, context?: DocumentContext): Promise<boolean>;
36
+ /** Removes expired documents: those of the scope of `context`, or those of every scope when it has none. */
37
+ sweep(now?: Date, context?: DocumentContext): Promise<number>;
38
+ putOriginal(id: string, bytes: Uint8Array, context?: DocumentContext): Promise<void>;
39
+ getOriginal(id: string, context?: DocumentContext): Promise<Uint8Array | undefined>;
18
40
  }
41
+ /**
42
+ * Whether `value` can name a folder of a scope in a `FileDocumentStore` with `scopes`: lowercase
43
+ * letters, digits, "_" and "-", 1 to 64 characters, starting with a letter or a digit, and not a
44
+ * name Windows keeps for a device (`con`, `prn`, `aux`, `nul`, `com0`-`com9`, `lpt0`-`lpt9`). Lower
45
+ * case only, because SMB and Azure Files ignore case: `Alice` and `alice` would be one folder. Use
46
+ * `hashedScopeSegment` for an ID that does not pass. New in 0.9.0.
47
+ */
48
+ export declare function isSafeScopeSegment(value: string): boolean;
49
+ /**
50
+ * A segment that `isSafeScopeSegment` accepts, made from any string: "h" and the first 40 hex
51
+ * digits of its SHA-256. For user or chat IDs in mixed case, or in Hebrew. The same value always
52
+ * gives the same segment, and two values almost surely two. Use it for every value of that level of
53
+ * the scope, not only for those that would not pass, and pass the result as the scope's segment:
54
+ * the store never hashes on its own. New in 0.9.0.
55
+ */
56
+ export declare function hashedScopeSegment(value: string): string;
57
+ /** Where the documents of a scope go, when the store keeps each scope in a folder of its own. New in 0.9.0. */
58
+ export type FileDocumentScopes = {
59
+ /**
60
+ * How many segments every scope has, from 1 to 8: 2 for `[userId, chatId]`. A scope of another
61
+ * length is a `DocumentScopeError` of code "scope_invalid".
62
+ */
63
+ depth: number;
64
+ /**
65
+ * The folder of the store in the folder of each scope: `<directory>/<scope...>/<folder>/<id>.json`.
66
+ * Defaults to ".llm-large-files". "" puts the files in the scope's folder itself, beside files of
67
+ * the application's own. The names `<id>.json`, `.txt`, `.idx` and `.bin`, and their temporary
68
+ * files, are then the store's for every ID it is given: keep files of your own in a subfolder.
69
+ */
70
+ folder?: string;
71
+ /**
72
+ * Whether a write makes the folders of a scope that has none. Defaults to false: the folders of a
73
+ * scope are the application's, and the store only makes its own `folder` in them. A write into a
74
+ * scope whose folder is gone (the chat was deleted) is then a `DocumentScopeError` of code
75
+ * "scope_missing", and the folder is not made again. With true, they are made one level at a time,
76
+ * each checked to be a folder and not a link before the next is made in it.
77
+ */
78
+ createScopeFolders?: boolean;
79
+ /**
80
+ * What a call without a scope does. "refuse", the default: it throws a `DocumentScopeError` of
81
+ * code "scope_required". "root": it uses the files directly in the directory, as a store without
82
+ * `scopes` does, to keep reading documents written there before.
83
+ */
84
+ unscoped?: "refuse" | "root";
85
+ };
86
+ /** The options of a `FileDocumentStore`. */
87
+ export type FileDocumentStoreOptions = {
88
+ /** The clock that decides expiry, and the default `now` of `sweep`. Defaults to `() => new Date()`. */
89
+ now?: () => Date;
90
+ /**
91
+ * `sweep` removes files that belong to no document (an upload that failed, a server that
92
+ * stopped while writing) once they are this old. Younger ones may be an upload in progress,
93
+ * on this server or another one. Defaults to one hour.
94
+ */
95
+ orphanAgeMs?: number;
96
+ /** Keep the documents of each scope in a folder of their own. Without it, every document is in `directory`. New in 0.9.0. */
97
+ scopes?: FileDocumentScopes;
98
+ /** The mode of every file the store writes, minus the umask of the process. Defaults to 0o600. New in 0.9.0. */
99
+ fileMode?: number;
100
+ /** The mode of every folder the store makes, minus the umask of the process. Defaults to 0o700. New in 0.9.0. */
101
+ directoryMode?: number;
102
+ /** How many reads of metadata, listings and checks of a file's age `sweep` runs at once. Defaults to 16. New in 0.9.0. */
103
+ sweepConcurrency?: number;
104
+ };
19
105
  /**
20
106
  * Keeps each document as `<id>.txt` plus `<id>.json` in one directory, so files survive a
21
107
  * server restart, its line index as `<id>.idx`, and its original file as `<id>.bin` when one is
22
- * kept. Only IDs matching DOCUMENT_ID_PATTERN ever reach the file system.
108
+ * kept. Only IDs matching APP_DOCUMENT_ID_PATTERN (which leaves out names Windows keeps for
109
+ * devices) ever reach the file system. Those names, for every ID it is given, are the store's: keep
110
+ * files of your own in a subfolder. A read does not follow a link at a file name, except on Windows.
111
+ *
112
+ * With `scopes`, the documents of each scope are kept in a folder of their own:
113
+ * `<directory>/<userId>/<chatId>/.llm-large-files/<id>.json`. New in 0.9.0.
23
114
  *
24
115
  * Several servers may share the directory (a network volume): every file is written whole under
25
116
  * a temporary name and then renamed, a tool call reads only the lines it needs (`readTextRange`),
26
117
  * and `sweep` never removes the files of an upload that is still being written.
27
118
  */
28
119
  export declare class FileDocumentStore implements DocumentStore {
120
+ #private;
29
121
  private readonly directory;
30
122
  private readonly now;
31
123
  private readonly orphanAgeMs;
32
- constructor(directory: string, options?: {
33
- now?: () => Date;
34
- /**
35
- * `sweep` removes files that belong to no document (an upload that failed, a server that
36
- * stopped while writing) once they are this old. Younger ones may be an upload in progress,
37
- * on this server or another one. Defaults to one hour.
38
- */
39
- orphanAgeMs?: number;
40
- });
41
- private paths;
42
- put(document: StoredDocument): Promise<void>;
43
- getMeta(id: string): Promise<DocumentMeta | undefined>;
44
- get(id: string): Promise<StoredDocument | undefined>;
45
- readTextRange(id: string, start: number, end: number): Promise<Uint8Array | undefined>;
46
- putIndex(id: string, index: Uint8Array): Promise<void>;
47
- getIndex(id: string): Promise<Uint8Array | undefined>;
48
- delete(id: string): Promise<boolean>;
49
- putOriginal(id: string, bytes: Uint8Array): Promise<void>;
50
- getOriginal(id: string): Promise<Uint8Array | undefined>;
124
+ constructor(directory: string, options?: FileDocumentStoreOptions);
125
+ put(document: StoredDocument, context?: DocumentContext): Promise<void>;
126
+ getMeta(id: string, context?: DocumentContext): Promise<DocumentMeta | undefined>;
127
+ get(id: string, context?: DocumentContext): Promise<StoredDocument | undefined>;
128
+ readTextRange(id: string, start: number, end: number, context?: DocumentContext): Promise<Uint8Array | undefined>;
129
+ putIndex(id: string, index: Uint8Array, context?: DocumentContext): Promise<void>;
130
+ getIndex(id: string, context?: DocumentContext): Promise<Uint8Array | undefined>;
131
+ delete(id: string, context?: DocumentContext): Promise<boolean>;
132
+ putOriginal(id: string, bytes: Uint8Array, context?: DocumentContext): Promise<void>;
133
+ getOriginal(id: string, context?: DocumentContext): Promise<Uint8Array | undefined>;
51
134
  /**
52
- * Removes expired documents and returns how many. Also removes files that belong to no
135
+ * Removes expired documents and returns how many: those whose metadata this sweep removed, so
136
+ * that two sweeps at once count each document once. Also removes files that belong to no
53
137
  * document, and temporary files, once they are older than `orphanAgeMs`. A document whose
54
138
  * metadata is not valid is removed only when that file is that old too: it may be being
55
139
  * written by a server of an older version, which does not write whole files.
@@ -57,7 +141,12 @@ export declare class FileDocumentStore implements DocumentStore {
57
141
  * A document whose metadata could not be read at all (the volume did not answer, too many files
58
142
  * were open) is left alone, whatever its age: the next sweep looks at it again. A document that
59
143
  * cannot be removed is left for the next sweep too, and does not stop this one.
144
+ *
145
+ * With `scopes`: with a scope in `context`, the folder of that scope only. Without one, every
146
+ * scope's: it goes down exactly `scopes.depth` levels of folders, into folders whose names pass
147
+ * `isSafeScopeSegment` only, and follows no link. With `unscoped: "root"`, the directory itself too.
148
+ * Without `scopes`, the context is not used.
60
149
  */
61
- sweep(now?: Date): Promise<number>;
150
+ sweep(now?: Date, context?: DocumentContext): Promise<number>;
62
151
  }
63
152
  //# sourceMappingURL=stores.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"stores.d.ts","sourceRoot":"","sources":["../src/stores.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAE9E,eAAO,MAAM,mBAAmB,QAAuB,CAAC;AAMxD,kFAAkF;AAClF,qBAAa,mBAAoB,YAA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