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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "llm-large-files",
3
- "version": "0.8.2",
3
+ "version": "0.10.0",
4
4
  "description": "Let an LLM answer questions about books, logs, and other files larger than its request limit or context window: upload, plan, search and read tools, map-reduce, a look at the pages of a PDF, and one tool loop for any model. Adapters for Gemini and Vertex AI, OpenAI-compatible endpoints, and Claude.",
5
5
  "keywords": [
6
6
  "llm",
@@ -34,7 +34,7 @@
34
34
  "type": "module",
35
35
  "sideEffects": false,
36
36
  "engines": {
37
- "node": ">=20.19"
37
+ "node": ">=22.12"
38
38
  },
39
39
  "main": "./dist/index.js",
40
40
  "types": "./dist/index.d.ts",
@@ -59,6 +59,10 @@
59
59
  "types": "./dist/node/index.d.ts",
60
60
  "default": "./dist/node/index.js"
61
61
  },
62
+ "./testing": {
63
+ "types": "./dist/testing/index.d.ts",
64
+ "default": "./dist/testing/index.js"
65
+ },
62
66
  "./node/ingest-child.js": "./dist/node/ingest-child.js",
63
67
  "./package.json": "./package.json"
64
68
  },
@@ -75,6 +79,9 @@
75
79
  ],
76
80
  "node": [
77
81
  "./dist/node/index.d.ts"
82
+ ],
83
+ "testing": [
84
+ "./dist/testing/index.d.ts"
78
85
  ]
79
86
  }
80
87
  },
@@ -89,7 +96,12 @@
89
96
  "typecheck": "tsc --noEmit",
90
97
  "test": "vitest run",
91
98
  "test:watch": "vitest",
99
+ "coverage": "vitest run --coverage --project unit --testTimeout=60000",
92
100
  "check": "npm run typecheck && npm test && npm run build",
101
+ "eval:replay": "node evals/cli.mjs replay",
102
+ "eval:record": "node evals/cli.mjs record",
103
+ "eval:live": "node evals/cli.mjs live",
104
+ "eval:recheck": "node evals/cli.mjs recheck",
93
105
  "prepublishOnly": "npm run check"
94
106
  },
95
107
  "peerDependencies": {
@@ -110,7 +122,8 @@
110
122
  },
111
123
  "devDependencies": {
112
124
  "@cantoo/pdf-lib": "2.11.1",
113
- "@types/node": "^22.10.2",
125
+ "@types/node": "^22.12.0",
126
+ "@vitest/coverage-v8": "4.1.12",
114
127
  "jszip": "3.10.1",
115
128
  "typescript": "5.9.3",
116
129
  "unpdf": "1.4.0",
package/src/access.ts ADDED
@@ -0,0 +1,267 @@
1
+ // Who is asking, and what they may use: the owner and the scope of a call, the context the store is
2
+ // given for it, and the rule that decides which documents serve it. New in 0.9.0.
3
+ import { DocumentScopeError, DocumentStoreError, type DocumentStoreOperation } from "./errors.js";
4
+ import { until } from "./http.js";
5
+ import { checkScope, sameScope, scopeKey } from "./scope.js";
6
+ import { DOCUMENT_META_VERSION } from "./stores.js";
7
+ import type { DocumentContext, DocumentMeta, DocumentScope } from "./types.js";
8
+
9
+ /** The TypeError of a call without an owner, when the library requires one (`requireOwner`). */
10
+ export const OWNER_REQUIRED = "owner is required: requireOwner is on";
11
+ /** The TypeError of a call without a scope, when the library requires one (`requireScope`). */
12
+ export const SCOPE_REQUIRED = "scope is required: requireScope is on";
13
+
14
+ /**
15
+ * Refuses an owner that every caller without a user would share: an empty string (what
16
+ * `user?.id ?? ""` gives), one of spaces only, or null. Undefined is no owner. A number is let
17
+ * through, as before, for JavaScript code that passes numeric user IDs.
18
+ */
19
+ export function checkOwner(owner: unknown): void {
20
+ if (owner === undefined || (typeof owner === "string" && owner.trim() !== "") || (typeof owner === "number" && Number.isFinite(owner))) return;
21
+ 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.");
22
+ }
23
+
24
+ /** What a library requires of every call (`LargeFilesOptions.requireOwner` and `requireScope`). */
25
+ export type AccessRules = { readonly requireOwner: boolean; readonly requireScope: boolean };
26
+
27
+ /** A caller, checked: its owner, its scope (a frozen copy), and what the store calls made for it carry. */
28
+ export type Caller = {
29
+ readonly owner?: string;
30
+ readonly scope?: DocumentScope;
31
+ /** The context of the store calls made for this caller. */
32
+ readonly context: DocumentContext;
33
+ /** The key of the scope (`scopeKey`): what this caller's copies of documents are kept under in memory. */
34
+ readonly key: string;
35
+ /**
36
+ * Ends this caller's waits for the store (`AccessOptions.signal`), with its reason: never a store
37
+ * call that other callers wait on too. New in 0.10.0.
38
+ */
39
+ readonly signal?: AbortSignal;
40
+ };
41
+
42
+ /** The context of a store call: a frozen object, without the fields that are absent. */
43
+ export function storeContext(scope: DocumentScope | undefined, owner: string | undefined): DocumentContext {
44
+ return Object.freeze({ ...(scope !== undefined ? { scope } : {}), ...(owner !== undefined ? { owner } : {}) });
45
+ }
46
+
47
+ /**
48
+ * The caller of a call made with `access`. Null is no owner and no scope, as a database gives a
49
+ * field that was left out. The scope is checked (`checkScope`: a `DocumentScopeError` when it is
50
+ * not valid). Under `requireOwner`, a call without an owner, or with one that `checkOwner` refuses,
51
+ * is a TypeError; under `requireScope`, a call without a scope. A `signal` that is not an
52
+ * `AbortSignal` is a TypeError (0.10.0).
53
+ */
54
+ export function callerOf(access: { readonly owner?: unknown; readonly scope?: unknown; readonly signal?: unknown } | undefined, rules: AccessRules): Caller {
55
+ const owner = (access?.owner ?? undefined) as string | undefined;
56
+ if (rules.requireOwner) {
57
+ if (owner === undefined) throw new TypeError(OWNER_REQUIRED);
58
+ checkOwner(owner);
59
+ }
60
+ const scope = checkScope(access?.scope ?? undefined);
61
+ if (rules.requireScope && scope === undefined) throw new TypeError(SCOPE_REQUIRED);
62
+ const signal: unknown = access?.signal ?? undefined;
63
+ if (signal !== undefined && !(signal instanceof AbortSignal)) throw new TypeError("signal must be an AbortSignal.");
64
+ return {
65
+ ...(owner !== undefined ? { owner } : {}),
66
+ ...(scope !== undefined ? { scope } : {}),
67
+ context: storeContext(scope, owner),
68
+ key: scopeKey(scope),
69
+ ...(signal !== undefined ? { signal } : {}),
70
+ };
71
+ }
72
+
73
+ /**
74
+ * Whether `caller` may use the document `meta` describes. A document with an owner serves only that
75
+ * owner, and one with a scope only a caller of the same scope, segment by segment. A document
76
+ * without an owner serves any caller, unless the library requires owners; the same for scopes.
77
+ * Null is no owner and no scope, as a database gives a field that was left out. A refusal is never
78
+ * told: the document reads as missing.
79
+ */
80
+ export function mayUse(meta: DocumentMeta, caller: Caller, rules: AccessRules): boolean {
81
+ const owner: unknown = meta.owner ?? undefined;
82
+ if (owner === undefined ? rules.requireOwner : owner !== caller.owner) return false;
83
+ const scope: unknown = meta.scope ?? undefined;
84
+ if (scope === undefined) return !rules.requireScope;
85
+ // A scope that is not a list of segments (damaged, or written by hand) serves nobody.
86
+ return Array.isArray(scope) && sameScope(scope as string[], caller.scope);
87
+ }
88
+
89
+ /**
90
+ * Whether the document `found` has exactly this owner and this scope: no owner is the same as no
91
+ * owner only, and so for scopes. An owner or a scope of null counts as none. A scope that is not a
92
+ * list of segments (damaged, or written by hand) is nobody's.
93
+ */
94
+ export function heldBy(found: DocumentMeta, owner: string | undefined, scope: DocumentScope | undefined): boolean {
95
+ const theirs: unknown = found.scope ?? undefined;
96
+ if ((found.owner ?? undefined) !== owner) return false;
97
+ return theirs === undefined ? scope === undefined : Array.isArray(theirs) && sameScope(theirs as string[], scope);
98
+ }
99
+
100
+ /**
101
+ * The context of the reads of a document's text (`get`, `readTextRange`, `getIndex`, and `putIndex`
102
+ * when its index is built again), once `caller` may use it (`mayUse`): the caller's scope, where
103
+ * `getMeta` found the document, and the owner only when the document has one. The copy kept in memory
104
+ * is kept under the caller's scope, and shared by every caller of it, whose owners differ when the
105
+ * document has none: so its reads carry one context whoever makes them. A document whose metadata
106
+ * has no scope (one of 0.8, moved into a scope) is still read in the scope it was found in. The
107
+ * owner sent is the caller's, which `mayUse` found the same as the document's; it is left out when
108
+ * the document has none.
109
+ */
110
+ export function documentContext(meta: DocumentMeta, caller: Caller): DocumentContext {
111
+ return storeContext(caller.scope, (meta.owner ?? undefined) === undefined ? undefined : caller.owner);
112
+ }
113
+
114
+ /**
115
+ * The metadata a store gave for `id`, when it is that of `id`: metadata of another document (a
116
+ * store that looked up the wrong one) is none. An owner or a scope of null, as a database gives a
117
+ * field that was left out, is left out.
118
+ */
119
+ export function metaOf(found: DocumentMeta | undefined, id: string): DocumentMeta | undefined {
120
+ if (typeof found !== "object" || found === null || found.id !== id) return undefined;
121
+ const { owner, scope } = found as { owner?: unknown; scope?: unknown };
122
+ if (owner !== null && scope !== null) return found;
123
+ const { owner: _owner, scope: _scope, ...rest } = found;
124
+ return { ...rest, ...(owner !== null && owner !== undefined ? { owner: owner as string } : {}), ...(scope !== null && scope !== undefined ? { scope: scope as string[] } : {}) };
125
+ }
126
+
127
+ /** The longest a Node.js timer waits: a longer time limit is no limit. */
128
+ const LONGEST_TIMER_MS = 2 ** 31 - 1;
129
+
130
+ /** Whether `ms` is a time limit a timer can keep: 0, and a time past what a timer can wait, are none. */
131
+ export const isTimeLimit = (ms: number): boolean => ms > 0 && ms <= LONGEST_TIMER_MS;
132
+
133
+ /** A time limit in the words of a message: "500 ms", "30 s", "2 min". */
134
+ export function formatDuration(ms: number): string {
135
+ if (ms < 1_000) return `${Math.max(1, Math.round(ms))} ms`;
136
+ if (ms < 120_000) return `${Number((ms / 1_000).toFixed(1))} s`;
137
+ return `${Number((ms / 60_000).toFixed(1))} min`;
138
+ }
139
+
140
+ /**
141
+ * The calls of this process that ran past their time limit and have not settled. One count for
142
+ * every library, and for every copy of the package (two versions side by side, or one bundled):
143
+ * the calls of a process share one pool of threads (libuv's, `UV_THREADPOOL_SIZE`), and a call
144
+ * that does not answer holds one of them. New in 0.10.0.
145
+ */
146
+ const STUCK = Symbol.for("llm-large-files.stuckCalls");
147
+ const stuck = (() => {
148
+ const shared = globalThis as typeof globalThis & { [STUCK]?: { count: number } };
149
+ const found = shared[STUCK];
150
+ if (typeof found === "object" && found !== null && typeof found.count === "number") return found;
151
+ return (shared[STUCK] = { count: 0 });
152
+ })();
153
+
154
+ /** Store calls of this process past their time limit that have not settled, and calls to the disk of the upload handlers. New in 0.10.0. */
155
+ export function stuckCalls(): number {
156
+ return stuck.count;
157
+ }
158
+
159
+ /**
160
+ * Counts `call` as stuck once it has run `ms` without settling, until it settles: whether or not
161
+ * anyone still waits for it. A call that settles within `ms` never counts, and nothing counts
162
+ * without a time limit (`isTimeLimit`). `late` is called when it passes `ms`. Returns `call`.
163
+ * New in 0.10.0.
164
+ */
165
+ export function watchStuck<T>(call: Promise<T>, ms: number, late?: () => void): Promise<T> {
166
+ if (!isTimeLimit(ms)) return call;
167
+ let counted = false;
168
+ // The timer keeps the process alive: a call that never ends may hold nothing that does, and a
169
+ // caller that waits on it would be lost.
170
+ const timer = setTimeout(() => {
171
+ counted = true;
172
+ stuck.count++;
173
+ late?.();
174
+ }, ms);
175
+ const settle = () => {
176
+ clearTimeout(timer);
177
+ if (counted) stuck.count--;
178
+ };
179
+ call.then(settle, settle);
180
+ return call;
181
+ }
182
+
183
+ /** The time limit of a store call, and the limit on calls left stuck, of one library (`storeTimeoutMs`, `maxStuckStoreCalls`). New in 0.10.0. */
184
+ export type StoreCallOptions = {
185
+ /** The most time the call may take, in milliseconds. 0, or a time past what a timer can wait, sets none. */
186
+ timeoutMs?: number;
187
+ /**
188
+ * While this many calls of the process are stuck (`stuckCalls`), the call is refused at once, with
189
+ * a `DocumentStoreError` of code "STORE_STUCK", and the store is not called. Defaults to no limit.
190
+ */
191
+ maxStuck?: number;
192
+ /** Whether the call counts as stuck once past `timeoutMs`. Defaults to true; false for a sweep. */
193
+ counts?: boolean;
194
+ /** Ends the caller's wait with its reason. The call itself goes on: a store call cannot be stopped. */
195
+ signal?: AbortSignal;
196
+ };
197
+
198
+ /** Refuses a call of `operation` while `maxStuck` calls of the process are stuck: the store is not answering. New in 0.10.0. */
199
+ export function checkStuck(operation: DocumentStoreOperation, maxStuck: number): void {
200
+ if (stuck.count < maxStuck) return;
201
+ const found = Object.assign(new Error(`${stuck.count} store calls of this process ran past their time limit and have not ended (the limit is ${maxStuck}): the store is not answering.`), { code: "STORE_STUCK" });
202
+ throw new DocumentStoreError(found, { operation, code: "STORE_STUCK" });
203
+ }
204
+
205
+ /** A store call that did not end within `ms`. */
206
+ export const storeTimeout = (operation: DocumentStoreOperation, ms: number) => new DocumentStoreError(
207
+ Object.assign(new Error(`The store did not answer within ${formatDuration(ms)}.`), { code: "ETIMEDOUT" }),
208
+ { operation, code: "ETIMEDOUT" },
209
+ );
210
+
211
+ /**
212
+ * A call of the store. What it throws is passed on as a `DocumentStoreError` of `operation`, with
213
+ * the store's error as `cause`: the store's own error may name a path, a host or a bucket, and a
214
+ * store that failed is not a document that is gone. A `DocumentStoreError` is passed on as it is,
215
+ * and so is a `DocumentScopeError`: a scope the store cannot use is a mistake of the call, and the
216
+ * same call would fail again.
217
+ *
218
+ * New in 0.10.0, `options`: a call that does not end within `timeoutMs` is a `DocumentStoreError`
219
+ * of code "ETIMEDOUT", and counts as stuck until it ends; while `maxStuck` calls are stuck, it is
220
+ * refused at once ("STORE_STUCK"); `signal` ends the caller's wait with its reason, as it is.
221
+ */
222
+ export async function storeCall<T>(operation: DocumentStoreOperation, call: () => Promise<T>, options: StoreCallOptions = {}): Promise<T> {
223
+ const { timeoutMs = 0, maxStuck = Number.POSITIVE_INFINITY, counts = true, signal } = options;
224
+ checkStuck(operation, maxStuck);
225
+ // A caller that has left starts no call. (Its signal may be an object made like an AbortSignal,
226
+ // which `ToolOptions.signal` takes as before 0.10.0.)
227
+ if (signal?.aborted) throw signal.reason;
228
+ let running: Promise<T>;
229
+ try {
230
+ running = Promise.resolve(call());
231
+ } catch (error) {
232
+ running = Promise.reject(error);
233
+ }
234
+ let waited: Promise<T> = running;
235
+ if (isTimeLimit(timeoutMs)) {
236
+ waited = new Promise<T>((resolve, reject) => {
237
+ const late = () => reject(storeTimeout(operation, timeoutMs));
238
+ if (counts) watchStuck(running, timeoutMs, late);
239
+ else {
240
+ const timer = setTimeout(late, timeoutMs);
241
+ const settle = () => clearTimeout(timer);
242
+ running.then(settle, settle);
243
+ }
244
+ running.then(resolve, reject);
245
+ });
246
+ }
247
+ try {
248
+ return await until(waited, signal);
249
+ } catch (error) {
250
+ if (signal?.aborted && error === signal.reason) throw error;
251
+ throw DocumentStoreError.is(error) || DocumentScopeError.is(error) ? error : new DocumentStoreError(error, { operation });
252
+ }
253
+ }
254
+
255
+ /**
256
+ * Refuses metadata written by a newer version of the package (`metaVersion` above
257
+ * `DOCUMENT_META_VERSION`), which may mean what this version cannot tell: a `DocumentStoreError`
258
+ * with code "NEWER_VERSION", not a document that is missing, so that an application does not
259
+ * ingest the file again over it. Metadata without a version (before 0.9.0), or with null as a
260
+ * database gives a field that was left out, is read as before.
261
+ */
262
+ export function checkMetaVersion(meta: DocumentMeta): void {
263
+ const version: unknown = meta.metaVersion ?? 0;
264
+ if (typeof version === "number" && version <= DOCUMENT_META_VERSION) return;
265
+ const found = new RangeError(`The metadata of ${String(meta.id)} has metaVersion ${String(version)}; this version of llm-large-files reads up to ${DOCUMENT_META_VERSION}.`);
266
+ throw new DocumentStoreError(found, { operation: "read", code: "NEWER_VERSION" });
267
+ }
package/src/aggregate.ts CHANGED
@@ -94,6 +94,8 @@ export type AggregateResult = {
94
94
  distinctCapped: boolean;
95
95
  /** For each numeric metric, how many matched rows had a value in its column that is not a number (left out). */
96
96
  notNumbers: Record<string, number>;
97
+ /** The filters whose value named a column: each row's cell of `column` was compared with its cell of `with` (since 0.10.0). */
98
+ compared?: Array<{ column: string; op: FilterOp; with: string }>;
97
99
  };
98
100
 
99
101
  /**
@@ -224,11 +226,30 @@ function splitCsvLine(line: string, separator: string, carry?: { fields: string[
224
226
  return { fields, open: false, field: "" };
225
227
  }
226
228
 
227
- /** A column a request names, resolved against the header: its index, and the part of a date to group by. */
228
- type ColumnRef = { index: number; name: string; datePart?: DatePart };
229
+ /**
230
+ * A column a request names, resolved against the header: its index, the part of a date to group
231
+ * by, and whether it was named by its letter ("C").
232
+ */
233
+ type ColumnRef = { index: number; name: string; datePart?: DatePart; byLetter?: boolean };
234
+
235
+ /**
236
+ * The number of a column named by its letters ("C" is 3, "AA" is 27), or undefined when `name` is
237
+ * not one to three letters A to Z.
238
+ */
239
+ function letterNumber(name: string): number | undefined {
240
+ if (!/^[A-Z]{1,3}$/i.test(name)) return undefined;
241
+ let number = 0;
242
+ for (const letter of name.toUpperCase()) number = number * 26 + letter.charCodeAt(0) - 64;
243
+ return number;
244
+ }
229
245
 
230
- /** Finds a column by its header name (ignoring case and spaces), its letter ("C"), or its number ("3"). */
231
- function columnOf(header: string[], given: string, letters: boolean): ColumnRef {
246
+ /**
247
+ * Finds a column by its header name (ignoring case and spaces), the lower name of a joined header
248
+ * when only one column has it, its letter ("C"), or its number ("3"). A letter or a number names a
249
+ * column only when no column has that name. Until 0.10.0 a letter named a column only in a sheet
250
+ * with no header, though the tool's description says it works in every table.
251
+ */
252
+ function columnOf(header: string[], given: string): ColumnRef {
232
253
  let name = given.trim();
233
254
  let datePart: DatePart | undefined;
234
255
  const part = /:(year|month|day)$/i.exec(name);
@@ -246,21 +267,67 @@ function columnOf(header: string[], given: string, letters: boolean): ColumnRef
246
267
  throw new Error(`${JSON.stringify(sliceWhole(name, 80))} names ${lower.length} columns of this table: ${lower.map((at) => JSON.stringify(header[at])).join(", ")}. Name one of them in full.`);
247
268
  }
248
269
  }
249
- if (index === -1 && letters && /^[A-Z]{1,3}$/i.test(name)) {
250
- let number = 0;
251
- for (const letter of name.toUpperCase()) number = number * 26 + letter.charCodeAt(0) - 64;
252
- if (number <= header.length) index = number - 1;
270
+ let byLetter = false;
271
+ if (index === -1) {
272
+ const number = letterNumber(name);
273
+ if (number !== undefined && number <= header.length) {
274
+ index = number - 1;
275
+ byLetter = true;
276
+ }
253
277
  }
254
278
  if (index === -1 && /^\d+$/.test(name) && Number(name) >= 1 && Number(name) <= header.length) index = Number(name) - 1;
255
279
  if (index === -1) {
256
280
  const listed = header.slice(0, 40).map((column) => JSON.stringify(column)).join(", ");
257
281
  throw new Error(`No column ${JSON.stringify(sliceWhole(name, 80))} in this table. Its columns are: ${listed}${header.length > 40 ? ", …" : ""}.`);
258
282
  }
259
- return { index, name: header[index]!, ...(datePart ? { datePart } : {}) };
283
+ return { index, name: header[index]!, ...(datePart ? { datePart } : {}), ...(byLetter ? { byLetter } : {}) };
284
+ }
285
+
286
+ /** The filters that order a column against a value: when the value names a column, against that column. */
287
+ const ORDER_OPS: ReadonlySet<FilterOp> = new Set(["<", "<=", ">", ">="]);
288
+
289
+ /**
290
+ * The columns the value of a filter names, when the filter orders its column against it (`>`,
291
+ * `>=`, `<`, `<=`) and the value is not a number: the column of that full name, else the columns
292
+ * whose lower name (of a joined header) it is, else the column of that letter when the filter's own
293
+ * column was named by its letter ("C" > "B"). Such a value compared as text matched no row, with no
294
+ * word of why: "Q1 / Actual" > "Q1 / Budget" is meant cell against cell. Empty for any other
295
+ * filter: `=`, `!=` and the text filters may well look for a value that is also a column's name
296
+ * ("Department" != "Total").
297
+ */
298
+ function columnsNamedBy(header: string[], filter: { op: FilterOp; value: string; number: number | undefined }, column: ColumnRef): number[] {
299
+ if (!ORDER_OPS.has(filter.op) || filter.number !== undefined) return [];
300
+ const wanted = valueKey(filter.value);
301
+ if (!wanted) return [];
302
+ const full = header.flatMap((name, at) => (valueKey(name) === wanted ? [at] : []));
303
+ if (full.length) return full;
304
+ const lower = header.flatMap((name, at) => (valueKey(name.split(" / ").at(-1) ?? "") === wanted ? [at] : []));
305
+ if (lower.length) return lower;
306
+ const number = column.byLetter ? letterNumber(filter.value.trim()) : undefined;
307
+ return number !== undefined && number <= header.length ? [number - 1] : [];
308
+ }
309
+
310
+ /**
311
+ * Whether the cell `left` stands in `op` (`>`, `>=`, `<`, `<=`) to the cell `right` of the same
312
+ * row, for a filter whose value names a column (`columnsNamedBy`): two numbers compare as numbers,
313
+ * two texts (ISO dates among them) as text, ignoring case. A number and a text, or an empty cell,
314
+ * never match: "n/a" is neither more nor less than 900.
315
+ */
316
+ function compareCells(left: string, right: string, op: FilterOp): boolean {
317
+ const leftKey = valueKey(left);
318
+ const rightKey = valueKey(right);
319
+ const leftNumber = parseNumber(left);
320
+ const rightNumber = parseNumber(right);
321
+ if (!leftKey || !rightKey || (leftNumber === undefined) !== (rightNumber === undefined)) return false;
322
+ const order = leftNumber !== undefined && rightNumber !== undefined
323
+ ? Math.sign(leftNumber - rightNumber)
324
+ : leftKey === rightKey ? 0 : leftKey < rightKey ? -1 : 1;
325
+ return op === ">" ? order > 0 : op === ">=" ? order >= 0 : op === "<" ? order < 0 : order <= 0;
260
326
  }
261
327
 
262
328
  type Metric = { name: string; op: AggregateOp; column?: ColumnRef };
263
- type Filter = { column: ColumnRef; op: FilterOp; value: string; number: number | undefined; key: string };
329
+ /** A filter, resolved; `against` is the column its value names, whose cell of each row it is compared with (since 0.10.0). */
330
+ type Filter = { column: ColumnRef; op: FilterOp; value: string; number: number | undefined; key: string; against?: ColumnRef };
264
331
  type GroupState = { key: Record<string, string>; count: number; sums: number[]; numbers: number[]; minimums: Array<number | string | undefined>; maximums: Array<number | string | undefined>; distinct: Array<Set<string> | undefined>; lines: number[] };
265
332
 
266
333
  /** The value of a cell for comparing: a number when it is one, a date as written, or folded text. */
@@ -353,9 +420,17 @@ export async function aggregateTable(source: DocumentSource, request: AggregateR
353
420
  if (!FILTER_OPS.includes(filter.op)) throw new Error(`A filter's op must be one of ${FILTER_OPS.map((op) => `"${op}"`).join(", ")}.`);
354
421
  const value = filter.value === undefined || filter.value === null ? "" : String(filter.value);
355
422
  if (value === "" && filter.op !== "empty" && filter.op !== "not_empty" && filter.op !== "=" && filter.op !== "!=") throw new Error(`The filter on ${JSON.stringify(filter.column)} needs a value.`);
356
- return { column: columnOf(columns, String(filter.column ?? ""), letters), op: filter.op, value, number: parseNumber(value), key: valueKey(value) };
423
+ const resolved: Filter = { column: columnOf(columns, String(filter.column ?? "")), op: filter.op, value, number: parseNumber(value), key: valueKey(value) };
424
+ // A value that names a column: each row's cell is compared with that column's (since 0.10.0).
425
+ const named = columnsNamedBy(columns, resolved, resolved.column);
426
+ if (named.length > 1) {
427
+ const names = named.slice(0, 10).map((at) => JSON.stringify(columns[at])).join(", ");
428
+ throw new Error(`${JSON.stringify(sliceWhole(value.trim(), 80))} names ${named.length} columns of this table: ${names}${named.length > 10 ? ", …" : ""}. Name one of them in full, to compare ${JSON.stringify(resolved.column.name)} with it in each row.`);
429
+ }
430
+ if (named.length === 1) resolved.against = { index: named[0]!, name: columns[named[0]!]! };
431
+ return resolved;
357
432
  });
358
- groupColumns = (request.groupBy ?? []).map((name) => columnOf(columns, String(name), letters));
433
+ groupColumns = (request.groupBy ?? []).map((name) => columnOf(columns, String(name)));
359
434
  metrics = metricsGiven.map((given) => {
360
435
  const text = String(given).trim();
361
436
  const [rawOp, ...rest] = text.split(":");
@@ -364,7 +439,7 @@ export async function aggregateTable(source: DocumentSource, request: AggregateR
364
439
  const columnName = rest.join(":").trim();
365
440
  if (op === "count") return { name: "count", op };
366
441
  if (!columnName) throw new Error(`The metric "${op}" needs a column: "${op}:<column>".`);
367
- const column = columnOf(columns, columnName, letters);
442
+ const column = columnOf(columns, columnName);
368
443
  return { name: `${op}:${column.name}`, op, column };
369
444
  });
370
445
  notNumbers = metrics.map(() => 0);
@@ -455,7 +530,9 @@ export async function aggregateTable(source: DocumentSource, request: AggregateR
455
530
  if (row.slice(header.length).some((cell) => cell !== "") || (kind === "csv" && row.length !== header.length)) irregularRows++;
456
531
  rowsRead++;
457
532
  const cell = (column: ColumnRef) => row[column.index] ?? "";
458
- for (const filter of filters) if (!compare(cell(filter.column), filter)) return;
533
+ for (const filter of filters) {
534
+ if (!(filter.against ? compareCells(cell(filter.column), cell(filter.against), filter.op) : compare(cell(filter.column), filter))) return;
535
+ }
459
536
  rowsMatched++;
460
537
  const values = groupColumns.map((column) => groupValue(cell(column), column));
461
538
  const key = values.map(valueKey).join("\u0000");
@@ -650,6 +727,7 @@ export async function aggregateTable(source: DocumentSource, request: AggregateR
650
727
  irregularRows,
651
728
  distinctCapped,
652
729
  notNumbers: Object.fromEntries(metrics.flatMap((metric, index) => (notNumbers[index]! > 0 && (metric.op === "sum" || metric.op === "avg" || metric.op === "min" || metric.op === "max") ? [[metric.name, notNumbers[index]!]] : []))),
730
+ ...(filters.some((filter) => filter.against) ? { compared: filters.flatMap((filter) => (filter.against ? [{ column: filter.column.name, op: filter.op, with: filter.against.name }] : [])) } : {}),
653
731
  };
654
732
  }
655
733
 
package/src/analyze.ts CHANGED
@@ -166,8 +166,8 @@ function outlineEntry(lines: string[], index: number, hashes: HashHeadings = "al
166
166
  return undefined;
167
167
  }
168
168
 
169
- /** The outline kept from all the headings found: at most 400 of them. */
170
- function pickOutline(entries: OutlineEntry[]): OutlineEntry[] {
169
+ /** The outline kept from all the headings found: at most 400 of them. Also picks a PDF's headings from type sizes (pdf-outline.ts). */
170
+ export function pickOutline<T extends { level: number }>(entries: T[]): T[] {
171
171
  if (entries.length <= MAX_OUTLINE_ENTRIES) return entries;
172
172
  // Keep the top-level headings when there are at least 20 of them. A pool that fits is kept whole;
173
173
  // a larger one is sampled evenly, so the outline still spans the document.
@@ -0,0 +1,45 @@
1
+ // How an answer ended, in one value an application can switch on for the message it shows: the
2
+ // answer's own counterpart of `errorInfoOf`. New in 0.10.0.
3
+ import type { AskResult } from "./ask.js";
4
+
5
+ /** How an answer ended (`answerInfoOf`). New in 0.10.0. */
6
+ export type AnswerInfo = {
7
+ /** True when the answer came whole: not stopped by a filter or the output limit, and not refused. */
8
+ complete: boolean;
9
+ /**
10
+ * Why it is not complete: "filtered" by the provider's filters, "cut" at the output limit,
11
+ * "blocked" (the prompt was refused), "language" (Gemini's LANGUAGE: a language the model does
12
+ * not take), "no_answer" (no text came), or "other".
13
+ */
14
+ reason?: "filtered" | "cut" | "blocked" | "language" | "no_answer" | "other";
15
+ /** `AskResult.finish`. */
16
+ finish?: AskResult["finish"];
17
+ /** The provider's own word (`AskResult.finishReason`). */
18
+ finishReason?: string;
19
+ };
20
+
21
+ /**
22
+ * How the answer of `result` ended, for the message to show: complete, or why not. The reasons
23
+ * are tried in this order: a refused prompt ("blocked"), a filter ("filtered"), the output limit
24
+ * ("cut"), Gemini's LANGUAGE ("language": the model does not take the language of the question,
25
+ * which is no filter), another reason that asking again does not mend ("other"), and no text at
26
+ * all ("no_answer"). A result that was built by hand without `finish` is told by `answered`,
27
+ * `blockReason` and `finishReason` alone. New in 0.10.0.
28
+ */
29
+ export function answerInfoOf(result: Pick<AskResult, "answered" | "finish" | "finishReason" | "blockReason">): AnswerInfo {
30
+ const { answered, finish, finishReason, blockReason } = result;
31
+ const told = {
32
+ ...(finish !== undefined ? { finish } : {}),
33
+ ...(typeof finishReason === "string" ? { finishReason } : {}),
34
+ };
35
+ const incomplete = (reason: NonNullable<AnswerInfo["reason"]>): AnswerInfo => ({ complete: false, reason, ...told });
36
+ if (typeof blockReason === "string" && blockReason) return incomplete("blocked");
37
+ if (finish === "filtered") return incomplete("filtered");
38
+ if (finish === "cut") return incomplete("cut");
39
+ // Gemini's word for a language the model does not take. An adapter maps it to "other" (asking
40
+ // again would not mend it); an older one leaves `finish` unset. Either way it is not a filter.
41
+ if (finish !== "complete" && typeof finishReason === "string" && finishReason.toUpperCase() === "LANGUAGE") return incomplete("language");
42
+ if (finish === "other") return incomplete("other");
43
+ if (answered !== true) return incomplete("no_answer");
44
+ return { complete: true, ...told };
45
+ }