llm-large-files 0.8.1 → 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 (204) hide show
  1. package/CHANGELOG.md +631 -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 +176 -34
  56. package/dist/library.d.ts.map +1 -1
  57. package/dist/library.js +332 -512
  58. package/dist/library.js.map +1 -1
  59. package/dist/limiter.d.ts +2 -2
  60. package/dist/limiter.js +2 -2
  61. package/dist/map-reduce.js +3 -3
  62. package/dist/map-reduce.js.map +1 -1
  63. package/dist/model.d.ts +43 -2
  64. package/dist/model.d.ts.map +1 -1
  65. package/dist/model.js +63 -3
  66. package/dist/model.js.map +1 -1
  67. package/dist/node/handlers.d.ts +234 -7
  68. package/dist/node/handlers.d.ts.map +1 -1
  69. package/dist/node/handlers.js +482 -121
  70. package/dist/node/handlers.js.map +1 -1
  71. package/dist/node/index.d.ts +3 -2
  72. package/dist/node/index.d.ts.map +1 -1
  73. package/dist/node/index.js +2 -1
  74. package/dist/node/index.js.map +1 -1
  75. package/dist/node/ingest-child.d.ts +7 -1
  76. package/dist/node/ingest-child.d.ts.map +1 -1
  77. package/dist/node/ingest-child.js +18 -3
  78. package/dist/node/ingest-child.js.map +1 -1
  79. package/dist/node/isolated.d.ts +3 -1
  80. package/dist/node/isolated.d.ts.map +1 -1
  81. package/dist/node/isolated.js +11 -4
  82. package/dist/node/isolated.js.map +1 -1
  83. package/dist/node/originals.d.ts +19 -0
  84. package/dist/node/originals.d.ts.map +1 -0
  85. package/dist/node/originals.js +82 -0
  86. package/dist/node/originals.js.map +1 -0
  87. package/dist/node/spool.d.ts +102 -0
  88. package/dist/node/spool.d.ts.map +1 -0
  89. package/dist/node/spool.js +365 -0
  90. package/dist/node/spool.js.map +1 -0
  91. package/dist/node/sse.d.ts +4 -3
  92. package/dist/node/sse.d.ts.map +1 -1
  93. package/dist/node/sse.js +7 -6
  94. package/dist/node/sse.js.map +1 -1
  95. package/dist/pdf-layout.d.ts.map +1 -1
  96. package/dist/pdf-layout.js +71 -12
  97. package/dist/pdf-layout.js.map +1 -1
  98. package/dist/ranged.d.ts +22 -11
  99. package/dist/ranged.d.ts.map +1 -1
  100. package/dist/ranged.js +50 -12
  101. package/dist/ranged.js.map +1 -1
  102. package/dist/retry.d.ts +3 -1
  103. package/dist/retry.d.ts.map +1 -1
  104. package/dist/retry.js +6 -2
  105. package/dist/retry.js.map +1 -1
  106. package/dist/scope.d.ts +25 -0
  107. package/dist/scope.d.ts.map +1 -0
  108. package/dist/scope.js +60 -0
  109. package/dist/scope.js.map +1 -0
  110. package/dist/source.d.ts +60 -0
  111. package/dist/source.d.ts.map +1 -0
  112. package/dist/source.js +170 -0
  113. package/dist/source.js.map +1 -0
  114. package/dist/stores.d.ts +120 -31
  115. package/dist/stores.d.ts.map +1 -1
  116. package/dist/stores.js +582 -139
  117. package/dist/stores.js.map +1 -1
  118. package/dist/testing/fake-fetch.d.ts +31 -0
  119. package/dist/testing/fake-fetch.d.ts.map +1 -0
  120. package/dist/testing/fake-fetch.js +66 -0
  121. package/dist/testing/fake-fetch.js.map +1 -0
  122. package/dist/testing/fake-model.d.ts +38 -0
  123. package/dist/testing/fake-model.d.ts.map +1 -0
  124. package/dist/testing/fake-model.js +62 -0
  125. package/dist/testing/fake-model.js.map +1 -0
  126. package/dist/testing/index.d.ts +7 -0
  127. package/dist/testing/index.d.ts.map +1 -0
  128. package/dist/testing/index.js +9 -0
  129. package/dist/testing/index.js.map +1 -0
  130. package/dist/testing/store-checks.d.ts +72 -0
  131. package/dist/testing/store-checks.d.ts.map +1 -0
  132. package/dist/testing/store-checks.js +619 -0
  133. package/dist/testing/store-checks.js.map +1 -0
  134. package/dist/tools.d.ts +25 -0
  135. package/dist/tools.d.ts.map +1 -1
  136. package/dist/tools.js +135 -13
  137. package/dist/tools.js.map +1 -1
  138. package/dist/types.d.ts +116 -13
  139. package/dist/types.d.ts.map +1 -1
  140. package/docs/README.md +17 -8
  141. package/docs/getting-started.md +18 -13
  142. package/docs/guides/anthropic.md +12 -8
  143. package/docs/guides/conversations.md +112 -47
  144. package/docs/guides/costs-and-limits.md +16 -7
  145. package/docs/guides/deployment.md +309 -87
  146. package/docs/guides/errors-and-reliability.md +161 -23
  147. package/docs/guides/own-adapter-and-loop.md +27 -10
  148. package/docs/guides/pdfs.md +123 -29
  149. package/docs/guides/storage.md +634 -143
  150. package/docs/guides/testing.md +78 -129
  151. package/docs/guides/vertex-and-gemini.md +10 -7
  152. package/docs/guides/web-app.md +322 -77
  153. package/docs/how-it-works.md +35 -8
  154. package/docs/measurements.md +63 -8
  155. package/docs/publishing.md +112 -36
  156. package/docs/reference/ask.md +154 -13
  157. package/docs/reference/errors-and-retries.md +166 -14
  158. package/docs/reference/events.md +53 -20
  159. package/docs/reference/gemini.md +70 -21
  160. package/docs/reference/library.md +709 -165
  161. package/docs/reference/node.md +633 -104
  162. package/docs/reference/testing.md +311 -0
  163. package/docs/reference/tools.md +15 -5
  164. package/docs/security.md +316 -70
  165. package/docs/troubleshooting.md +165 -58
  166. package/docs/upgrading-0.9.md +890 -0
  167. package/package.json +12 -3
  168. package/src/access.ts +144 -0
  169. package/src/ask.ts +230 -19
  170. package/src/cache.ts +20 -5
  171. package/src/encoding.ts +6 -4
  172. package/src/error-info.ts +255 -0
  173. package/src/errors.ts +129 -15
  174. package/src/events.ts +86 -21
  175. package/src/evidence.ts +14 -3
  176. package/src/extract.ts +50 -33
  177. package/src/gemini/adapter.ts +97 -11
  178. package/src/gemini/chat.ts +20 -6
  179. package/src/gemini/index.ts +1 -1
  180. package/src/index.ts +9 -6
  181. package/src/ingest.ts +927 -0
  182. package/src/library.ts +482 -523
  183. package/src/limiter.ts +2 -2
  184. package/src/map-reduce.ts +3 -3
  185. package/src/model.ts +69 -5
  186. package/src/node/handlers.ts +691 -117
  187. package/src/node/index.ts +13 -2
  188. package/src/node/ingest-child.ts +23 -5
  189. package/src/node/isolated.ts +11 -4
  190. package/src/node/originals.ts +78 -0
  191. package/src/node/spool.ts +365 -0
  192. package/src/node/sse.ts +7 -6
  193. package/src/pdf-layout.ts +69 -11
  194. package/src/ranged.ts +42 -14
  195. package/src/retry.ts +6 -2
  196. package/src/scope.ts +63 -0
  197. package/src/source.ts +178 -0
  198. package/src/stores.ts +635 -140
  199. package/src/testing/fake-fetch.ts +80 -0
  200. package/src/testing/fake-model.ts +78 -0
  201. package/src/testing/index.ts +11 -0
  202. package/src/testing/store-checks.ts +660 -0
  203. package/src/tools.ts +150 -14
  204. package/src/types.ts +106 -13
package/src/cache.ts CHANGED
@@ -4,12 +4,22 @@ import type { DocumentMeta } from "./types.js";
4
4
  export type Sized = { readonly memoryBytes: number };
5
5
 
6
6
  /**
7
- * What identifies the contents of a document. A document ID is never reused, but a store can be
8
- * restored from a backup or written by another program: a cached copy is used only while the
9
- * store still describes the same text.
7
+ * Whose a document is: its owner and its scope, as one string. Part of every version of a document
8
+ * kept in memory, so that a copy of one owner's or scope's document is never served to another.
9
+ */
10
+ export function holderOf(meta: DocumentMeta): string {
11
+ return JSON.stringify([meta.owner ?? null, meta.scope ?? null]);
12
+ }
13
+
14
+ /**
15
+ * What identifies the contents of a document. An application's ID (0.9.0) is reused: a document is
16
+ * deleted and another stored under its ID, by another owner or in another scope, possibly within
17
+ * the same millisecond and with a text of the same size. A store can also be restored from a backup
18
+ * or written by another program. So a cached copy is used only while the store still describes the
19
+ * same text, of the same owner and scope.
10
20
  */
11
21
  export function documentVersion(meta: DocumentMeta): string {
12
- return `${meta.createdAt}|${meta.textBytes}|${meta.characters}|${meta.lines}`;
22
+ return `${meta.createdAt}|${meta.textBytes}|${meta.characters}|${meta.lines}|${holderOf(meta)}`;
13
23
  }
14
24
 
15
25
  /**
@@ -102,6 +112,11 @@ export class DocumentCache<T extends Sized> {
102
112
 
103
113
  /** Drops every entry whose key starts with `prefix`: all the pieces of one document. */
104
114
  deletePrefix(prefix: string): void {
105
- for (const key of [...this.entries.keys()]) if (key.startsWith(prefix)) this.delete(key);
115
+ this.deleteWhere((key) => key.startsWith(prefix));
116
+ }
117
+
118
+ /** Drops every entry whose key passes `test`: one document in every scope, with its pieces. */
119
+ deleteWhere(test: (key: string) => boolean): void {
120
+ for (const key of [...this.entries.keys()]) if (test(key)) this.delete(key);
106
121
  }
107
122
  }
package/src/encoding.ts CHANGED
@@ -506,11 +506,13 @@ function fits(sample: Uint8Array, encoding: string, script: Script): boolean {
506
506
  }
507
507
 
508
508
  /**
509
- * A decoder for an older encoding. Node 20 reads windows-1252 (and its other Latin-1 labels) as
510
- * Latin-1 in a decode call that is not streamed, so 0x80-0x9F come out as control characters
511
- * ("’" as U+0092), until the decoder has been called once streamed: that call is made here.
509
+ * A decoder for an older encoding. Some versions of Node read windows-1252 (and its other Latin-1
510
+ * labels) as Latin-1 in a decode call that is not streamed, so 0x80-0x9F come out as control
511
+ * characters ("’" as U+0092), until the decoder has been called once streamed: that call is made
512
+ * here. Not only Node 20 (20.18.3 and later): Node 22.13.0 brought the same bug
513
+ * (nodejs/node#60888), which 22.23.5 no longer has. Keep the call while such a 22.x is supported.
512
514
  */
513
- function decoderFor(encoding: string, options?: TextDecoderOptions): TextDecoder {
515
+ function decoderFor(encoding: string, options?: ConstructorParameters<typeof TextDecoder>[1]): InstanceType<typeof TextDecoder> {
514
516
  const decoder = new TextDecoder(encoding, options);
515
517
  decoder.decode(new Uint8Array(0), { stream: true });
516
518
  return decoder;
@@ -0,0 +1,255 @@
1
+ // What an error means for an application: one record to choose a status, a retry and words of
2
+ // your own by, in any language. New in 0.9.0.
3
+ import { DocumentScopeError, DocumentStoreError, IngestError, isErrorCode, type DocumentScopeErrorCode, type IngestErrorCode } from "./errors.js";
4
+ import { eventErrorOf, isPlainData } from "./events.js";
5
+ import { modelFailureReason } from "./map-reduce.js";
6
+ import { classifyModelError, DocumentsNotFoundError, isModelStatus, ModelRequestError, type ModelErrorKind } from "./model.js";
7
+
8
+ /**
9
+ * What kind of failure an error is (`ErrorInfo.category`):
10
+ * - "ingest": a file `ingest` refused (`IngestError`): `code` says why;
11
+ * - "store": the document store failed just now (`DocumentStoreError`);
12
+ * - "missing": documents that are gone (`DocumentsNotFoundError`), or the chat of a scope that is
13
+ * gone (`DocumentScopeError` "scope_missing");
14
+ * - "model": a model request failed (`ModelRequestError`): `code` is its kind;
15
+ * - "aborted": stopped by a signal (an `AbortError`, or a `TimeoutError` of `AbortSignal.timeout`);
16
+ * - "input": a mistake in the call (a `TypeError` or `RangeError`, or a `DocumentScopeError`
17
+ * "scope_invalid" or "scope_required", and the `EventError` of each): a bug of the server, not
18
+ * of the user;
19
+ * - "unknown": anything else.
20
+ *
21
+ * A switch over every category must handle the categories added in a later version.
22
+ */
23
+ export type ErrorCategory = "ingest" | "store" | "missing" | "model" | "aborted" | "input" | "unknown";
24
+
25
+ /** What `errorInfoOf` tells of an error. New in 0.9.0. */
26
+ export type ErrorInfo = {
27
+ category: ErrorCategory;
28
+ /**
29
+ * More precise than the category, when there is more to say: the `IngestErrorCode` ("too_large",
30
+ * "busy"…), the `ModelErrorKind` ("rate_limit"…), "documents_missing", the `DocumentScopeError`
31
+ * code, "aborted" or "timeout", or the code of the system error behind it ("EIO").
32
+ */
33
+ code?: string;
34
+ /** The HTTP status to answer with: 400 to 599. */
35
+ status: number;
36
+ /** Whether the same call may work when it is made again, later. */
37
+ retryable: boolean;
38
+ /** How long to wait before trying again, in milliseconds, when that is known. */
39
+ retryAfterMs?: number;
40
+ /**
41
+ * Words a user may see, in English. Never a path, a host, a stack or the provider's own words:
42
+ * those stay on the error, for your log. Show your own words for the category and code instead,
43
+ * in your users' language.
44
+ */
45
+ message: string;
46
+ };
47
+
48
+ /** How long to wait after a store failed, before the same call is made again. */
49
+ export const STORE_RETRY_AFTER_MS = 5_000;
50
+
51
+ const SOMETHING_WENT_WRONG = "Something went wrong.";
52
+ /**
53
+ * What a user is told of an "unreadable" file, whose message is a parser's or an extractor's of
54
+ * your own (which may name a host): by `errorInfoOf`, and by the upload handlers.
55
+ */
56
+ export const UNREADABLE_MESSAGE = "This file could not be read. It may be damaged, or not of the type its name says.";
57
+ const CHAT_GONE = "This chat no longer exists.";
58
+
59
+ /** The HTTP status of a model error, by its kind: the answer of a server that asked a model for its user. */
60
+ const MODEL_STATUS: Record<ModelErrorKind, number> = {
61
+ context_overflow: 413,
62
+ rate_limit: 429,
63
+ quota: 503,
64
+ timeout: 504,
65
+ unreachable: 502,
66
+ server: 502,
67
+ auth: 500,
68
+ invalid: 500,
69
+ };
70
+ const RETRYABLE_KINDS = new Set<ModelErrorKind>(["rate_limit", "timeout", "unreachable", "server"]);
71
+
72
+ /** Every `DocumentScopeErrorCode`, to read the `code` of an `EventError`. */
73
+ const SCOPE_CODES: Record<DocumentScopeErrorCode, true> = { scope_required: true, scope_invalid: true, scope_missing: true };
74
+ /** Statuses of plain data that say "try again later": too many requests, and a server that could not answer. */
75
+ const RETRY_STATUSES = new Set([429, 502, 503, 504]);
76
+
77
+ /** Every `IngestErrorCode`, to read the `code` of an `EventError`. */
78
+ const INGEST_CODES: Record<IngestErrorCode, true> = {
79
+ empty: true, too_large: true, too_much_text: true, too_many_pages: true, not_text: true, compressed: true, legacy_office: true,
80
+ encrypted: true, no_text: true, hostile: true, timeout: true, out_of_memory: true, busy: true, missing_dependency: true, unreadable: true, exists: true,
81
+ };
82
+
83
+ const isKind = (value: unknown): value is ModelErrorKind => typeof value === "string" && Object.hasOwn(MODEL_STATUS, value);
84
+ const isStatus = (value: unknown): value is number => typeof value === "number" && Number.isInteger(value) && value >= 400 && value <= 599;
85
+ const isWait = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value) && value >= 0;
86
+
87
+ /** The code of a Node system error (one with a `code` and a `syscall`), whose message names paths or hosts. */
88
+ function systemCode(error: object): string | undefined {
89
+ const { code, syscall } = error as { code?: unknown; syscall?: unknown };
90
+ return typeof syscall === "string" && isErrorCode(code) ? code : undefined;
91
+ }
92
+
93
+ /**
94
+ * The kind of a model error: its own, or the one its status (0, or 400 to 599), message and code
95
+ * give (an error of an adapter of your own), as its `EventError` and its message have it.
96
+ */
97
+ function modelKindOf(error: object): ModelErrorKind | undefined {
98
+ const { kind, status, message, code } = error as { kind?: unknown; status?: unknown; message?: unknown; code?: unknown };
99
+ if (isKind(kind)) return kind;
100
+ if (ModelRequestError.is(error) || isModelStatus(status)) {
101
+ return classifyModelError(typeof status === "number" ? status : 0, typeof message === "string" ? message : "", { code: typeof code === "string" ? code : undefined }).kind;
102
+ }
103
+ return undefined;
104
+ }
105
+
106
+ /**
107
+ * The code in the library's own words for a system error, as an `EventError` holds them: "The
108
+ * file could not be read from storage (ELOOP)." of `ingest.error` and `run.error`, "Upload failed
109
+ * (ENOSPC)." of the upload handlers' `ingest.error`. The error itself has the code: its event, only
110
+ * these words.
111
+ */
112
+ function codeInWords(message: unknown): string | undefined {
113
+ const code = typeof message === "string" ? /^(?:The file could not be read from storage|Upload failed) \(([A-Z][A-Z0-9_]{0,31})\)\.$/.exec(message)?.[1] : undefined;
114
+ return isErrorCode(code) ? code : undefined;
115
+ }
116
+
117
+ /**
118
+ * Whether `message` is the library's own words for a model's error of `kind`, with any status:
119
+ * "The model was busy (HTTP 429).". An `EventError` holds them, and the upload handlers' names the
120
+ * provider's status in them and the answer's in `status` ("The model failed on its side (HTTP
121
+ * 503).", 502): they are kept. Any other words, a provider's, are not.
122
+ */
123
+ function isModelWords(kind: ModelErrorKind, message: unknown): message is string {
124
+ if (typeof message !== "string") return false;
125
+ const status = /\(HTTP (\d{1,3})\)\.$/.exec(message)?.[1];
126
+ return message === modelFailureReason({ kind, ...(status !== undefined ? { status: Number(status) } : {}) });
127
+ }
128
+
129
+ /** A refused file, from an `IngestError` or the `EventError` of one. */
130
+ function ingestInfo(code: string, status: unknown, retryAfterMs: unknown, message: unknown): ErrorInfo {
131
+ return {
132
+ category: "ingest",
133
+ code,
134
+ status: isStatus(status) ? status : 422,
135
+ retryable: code === "busy",
136
+ ...(code === "busy" && isWait(retryAfterMs) ? { retryAfterMs } : {}),
137
+ // An unreadable file has the parser's message, or that of an extractor of your own: not words for a user.
138
+ message: code === "unreadable" || typeof message !== "string" || !message ? UNREADABLE_MESSAGE : message,
139
+ };
140
+ }
141
+
142
+ const storeInfo = (code: unknown, message: string): ErrorInfo => ({
143
+ category: "store",
144
+ // As the store's message does, a code is given only when it reads as one.
145
+ ...(isErrorCode(code) ? { code } : {}),
146
+ status: 503,
147
+ retryable: true,
148
+ retryAfterMs: STORE_RETRY_AFTER_MS,
149
+ message,
150
+ });
151
+
152
+ /**
153
+ * A scope that cannot be used: a chat that is gone, or a scope the server should have given, or
154
+ * given right (its bug, not the user's). Its own words are not used: a store of your own wrote them.
155
+ */
156
+ function scopeInfo(code: unknown): ErrorInfo {
157
+ if (code === "scope_missing") return { category: "missing", code: "scope_missing", status: 404, retryable: false, message: CHAT_GONE };
158
+ const known = typeof code === "string" && Object.hasOwn(SCOPE_CODES, code);
159
+ return { category: "input", ...(known ? { code } : {}), status: 500, retryable: false, message: SOMETHING_WENT_WRONG };
160
+ }
161
+
162
+ /**
163
+ * An `EventError`: the plain data of `run.error`, `request.end`, `retry` and `ingest.error`, which
164
+ * the library made from an error with words safe to show. It is read by its `name` and `code`;
165
+ * a model error by its `kind`, below, as any error with one. Undefined for other data.
166
+ */
167
+ function eventInfoOf(record: { name?: unknown; code?: unknown; kind?: unknown; status?: unknown; message?: unknown }): ErrorInfo | undefined {
168
+ const { name, code, kind, status, message } = record;
169
+ if (typeof message !== "string" || kind !== undefined) return undefined;
170
+ // `ingest.error` of the upload handler has no name for a refused file.
171
+ if (typeof code === "string" && Object.hasOwn(INGEST_CODES, code) && (name === undefined || name === "IngestError")) return ingestInfo(code, status, undefined, message);
172
+ if (name === "DocumentStoreError") return storeInfo(undefined, message || "The document store could not be used. Try again.");
173
+ if (name === "DocumentsNotFoundError") return { category: "missing", code: "documents_missing", status: 404, retryable: false, message: message || "A document is no longer available. Upload it again." };
174
+ if (name === "DocumentScopeError") return scopeInfo(code);
175
+ // A mistake in the call, as the error itself is read (`ingest.error` of a TypeError of ingest).
176
+ if (name === "TypeError" || name === "RangeError") return inputInfo();
177
+ return undefined;
178
+ }
179
+
180
+ /** A `TypeError` or `RangeError`: a mistake in the call, the server's bug and not the user's. */
181
+ const inputInfo = (): ErrorInfo => ({ category: "input", status: 500, retryable: false, message: SOMETHING_WENT_WRONG });
182
+
183
+ function infoOf(error: unknown): ErrorInfo {
184
+ if (IngestError.is(error)) return ingestInfo(error.code, error.status, error.retryAfterMs, error.message);
185
+ // Written to be shown: the operation and a code, never a path or a host.
186
+ if (DocumentStoreError.is(error)) return storeInfo(error.code, eventErrorOf(error).message);
187
+ if (DocumentsNotFoundError.is(error)) {
188
+ return { category: "missing", code: "documents_missing", status: 404, retryable: false, message: eventErrorOf(error).message };
189
+ }
190
+ if (DocumentScopeError.is(error)) return scopeInfo(error.code);
191
+ if (typeof error !== "object" || error === null) return { category: "unknown", status: 500, retryable: false, message: SOMETHING_WENT_WRONG };
192
+ const { name, retryAfterMs } = error as { name?: unknown; retryAfterMs?: unknown };
193
+ if (name === "AbortError") return { category: "aborted", code: "aborted", status: 503, retryable: true, message: "It was stopped before it finished." };
194
+ if (name === "TimeoutError") return { category: "aborted", code: "timeout", status: 504, retryable: true, message: "It took too long, and was stopped. Try again." };
195
+ const plain = isPlainData(error);
196
+ if (plain) {
197
+ const fromEvent = eventInfoOf(error);
198
+ if (fromEvent) return fromEvent;
199
+ // Plain data without a `kind` is not a model's error: an `EventError` of one always has its
200
+ // kind. The `ingest.error` of the upload handler for a hook that failed ({ message, status })
201
+ // keeps its status, and that of a system error its code.
202
+ const { kind, status, message } = error as { kind?: unknown; status?: unknown; message?: unknown };
203
+ if (typeof kind !== "string") return plainInfo(error, status, systemCode(error) ?? codeInWords(message));
204
+ }
205
+ const kind = modelKindOf(error);
206
+ if (kind !== undefined) {
207
+ const { message } = error as { message?: unknown };
208
+ return {
209
+ category: "model",
210
+ code: kind,
211
+ status: MODEL_STATUS[kind],
212
+ retryable: RETRYABLE_KINDS.has(kind),
213
+ ...(isWait(retryAfterMs) ? { retryAfterMs } : {}),
214
+ // By its kind and status, never in the provider's words (eventErrorOf). The library's own
215
+ // words, in an EventError, are kept.
216
+ message: plain && isModelWords(kind, message) ? message : eventErrorOf(error).message,
217
+ };
218
+ }
219
+ if (error instanceof TypeError || error instanceof RangeError) return inputInfo();
220
+ return plainInfo(error, undefined);
221
+ }
222
+
223
+ /**
224
+ * Anything else: "unknown", with the code of a system error (of its event, from the library's
225
+ * words), never its message. `status`, of plain data, is kept when it is one of an error (400 to
226
+ * 599), and says whether to retry.
227
+ */
228
+ function plainInfo(error: object, status: unknown, code = systemCode(error)): ErrorInfo {
229
+ return {
230
+ category: "unknown",
231
+ ...(code ? { code } : {}),
232
+ status: isStatus(status) ? status : 500,
233
+ retryable: RETRY_STATUSES.has(status as number),
234
+ message: code ? `Something went wrong (${code}).` : SOMETHING_WENT_WRONG,
235
+ };
236
+ }
237
+
238
+ /**
239
+ * What an error of the library means, for an application that tells its users in its own words:
240
+ * its category and code, the HTTP status to answer with, whether to retry it, and a message in
241
+ * English that is safe to show (never a path, a host, a stack or a provider's words). It reads
242
+ * the errors of every copy of the package (two versions side by side, or one bundled), and the
243
+ * `EventError` of an event (`run.error`, `ingest.error`, the upload handlers' `ingest.error` too),
244
+ * by its `code`, `name` and `kind`, keeping the words the library wrote. Plain data with none of
245
+ * them is "unknown", with its status. It never throws: what it cannot read is "unknown". New in
246
+ * 0.9.0.
247
+ */
248
+ export function errorInfoOf(error: unknown): ErrorInfo {
249
+ try {
250
+ return infoOf(error);
251
+ } catch {
252
+ // An error whose fields throw when read (a getter, a proxy).
253
+ return { category: "unknown", status: 500, retryable: false, message: SOMETHING_WENT_WRONG };
254
+ }
255
+ }
package/src/errors.ts CHANGED
@@ -1,3 +1,10 @@
1
+ /**
2
+ * Whether `value` reads as a code (EIO, ETIMEDOUT, NEWER_VERSION): capitals, digits and "_", 32 at
3
+ * most. A driver may put a host in the `code` of an error ("db-prod.internal:27017"): such a code is
4
+ * never shown.
5
+ */
6
+ export const isErrorCode = (value: unknown): value is string => typeof value === "string" && /^[A-Z][A-Z0-9_]{0,31}$/.test(value);
7
+
1
8
  /** The code and system call of a Node system error (`EIO`, `open`), when the value is one. */
2
9
  function systemError(value: unknown): { code?: string; syscall?: string } {
3
10
  const { code, syscall } = (value ?? {}) as { code?: unknown; syscall?: unknown };
@@ -8,27 +15,124 @@ function systemError(value: unknown): { code?: string; syscall?: string } {
8
15
  }
9
16
 
10
17
  /**
11
- * The store could not be read just now: a volume that did not answer, too many open files, a
12
- * database that is down. It does not mean that the document is gone, and the same call may work a
13
- * moment later, so retry it rather than ask the user to upload the file again.
18
+ * Whether `value` carries the brand `key` (`Symbol.for`), which every copy of this package gives
19
+ * its errors of one class: `instanceof` fails for an error made by another copy of the package (two
20
+ * versions installed side by side, or one bundled), and the brand does not.
21
+ */
22
+ export function branded(value: unknown, key: symbol): boolean {
23
+ try {
24
+ return typeof value === "object" && value !== null && (value as Record<symbol, unknown>)[key] === true;
25
+ } catch {
26
+ // A proxy whose traps throw.
27
+ return false;
28
+ }
29
+ }
30
+
31
+ /** Puts the brand `key` on the instances of a class, through its prototype (see `branded`). */
32
+ export function brand(target: { prototype: object }, key: symbol): void {
33
+ Object.defineProperty(target.prototype, key, { value: true });
34
+ }
35
+
36
+ const DOCUMENT_STORE_ERROR = Symbol.for("llm-large-files.DocumentStoreError");
37
+ const DOCUMENT_SCOPE_ERROR = Symbol.for("llm-large-files.DocumentScopeError");
38
+ const INGEST_ERROR = Symbol.for("llm-large-files.IngestError");
39
+
40
+ /**
41
+ * What the store was doing when it failed: reading, writing a document at ingest, deleting one, or
42
+ * removing expired ones. New in 0.9.0.
43
+ */
44
+ export type DocumentStoreOperation = "read" | "write" | "delete" | "sweep";
45
+
46
+ /** The message of a `DocumentStoreError`, by what failed: words for a user, with no path and no host. */
47
+ function storeMessage(operation: DocumentStoreOperation, code: string | undefined): string {
48
+ if (code === "NEWER_VERSION") return "The document was stored by a newer version of llm-large-files. Try again.";
49
+ const what = operation === "write" ? "The document could not be stored"
50
+ : operation === "delete" ? "The document could not be deleted"
51
+ : operation === "sweep" ? "The document store could not be cleaned up"
52
+ : "The document store could not be read";
53
+ // A code is shown only when it reads as one (EIO, ETIMEDOUT): a driver may put a host in `code`.
54
+ return `${what}${isErrorCode(code) ? ` (${code})` : ""}. Try again.`;
55
+ }
56
+
57
+ /**
58
+ * The store failed just now: a volume that did not answer, too many open files, a database that
59
+ * is down. It does not mean that the document is gone, and the same call may work a moment later,
60
+ * so retry it rather than ask the user to upload the file again.
14
61
  *
15
62
  * The message names no path and no host. The error that was caught is `cause`: log that one on
16
63
  * the server, and show this one to a user or a model.
64
+ *
65
+ * New in 0.9.0: `operation` says what failed, `status` is 503, and code "NEWER_VERSION" is
66
+ * metadata written by a newer version of the package, which this one does not read. Before 0.9.0
67
+ * it was only made for reads, and `new DocumentStoreError(cause)` still makes one.
17
68
  */
18
69
  export class DocumentStoreError extends Error {
19
- /** The code of the system error behind it (`EIO`, `EMFILE`, `ETIMEDOUT`), when there is one. */
70
+ /**
71
+ * The code of the system error behind it (`EIO`, `EMFILE`, `ETIMEDOUT`), when there is one, or
72
+ * the code it was made with: "NEWER_VERSION".
73
+ */
20
74
  readonly code?: string;
21
75
  /** The system call that failed (`open`, `read`), when there is one. */
22
76
  readonly syscall?: string;
77
+ /** What the store was doing. "read" unless it was made with another. */
78
+ readonly operation: DocumentStoreOperation;
79
+ /** The HTTP status to answer with: the server cannot serve the request now. */
80
+ readonly status: 503 = 503;
23
81
 
24
- constructor(cause: unknown) {
25
- const { code, syscall } = systemError(cause);
26
- super(`The document store could not be read${code ? ` (${code})` : ""}. Try again.`, { cause });
82
+ constructor(cause: unknown, options: { operation?: DocumentStoreOperation; code?: string } = {}) {
83
+ const found = systemError(cause);
84
+ const code = options.code ?? found.code;
85
+ const operation = options.operation ?? "read";
86
+ super(storeMessage(operation, code), { cause });
27
87
  this.name = "DocumentStoreError";
88
+ this.operation = operation;
28
89
  if (code) this.code = code;
29
- if (syscall) this.syscall = syscall;
90
+ if (found.syscall) this.syscall = found.syscall;
91
+ }
92
+
93
+ /** Whether `value` is a `DocumentStoreError`, made by this copy of the package or another one. New in 0.9.0. */
94
+ static is(value: unknown): value is DocumentStoreError {
95
+ return branded(value, DOCUMENT_STORE_ERROR);
30
96
  }
31
97
  }
98
+ brand(DocumentStoreError, DOCUMENT_STORE_ERROR);
99
+
100
+ /**
101
+ * Why a scope was refused (see `DocumentScopeError`):
102
+ * - "scope_invalid": not an array of 1 to 8 segments of 1 to 256 characters, without control
103
+ * characters, "/" or "\", and not "." or "..", or not one the store can keep;
104
+ * - "scope_required": the store needs a scope, and the call had none;
105
+ * - "scope_missing": the store keeps the scope in a folder that is gone (the chat was deleted).
106
+ */
107
+ export type DocumentScopeErrorCode = "scope_required" | "scope_invalid" | "scope_missing";
108
+
109
+ const SCOPE_MESSAGES: Record<DocumentScopeErrorCode, string> = {
110
+ scope_invalid: "The scope is not valid.",
111
+ scope_required: "A scope is required: pass the scope of the document, such as [userId, chatId].",
112
+ scope_missing: "The scope no longer exists.",
113
+ };
114
+
115
+ /**
116
+ * A scope (`DocumentScope`) that cannot be used: one that is not valid, a call without one to a
117
+ * store that needs one, or a scope whose place in the store is gone. A mistake in the call, not a
118
+ * failure of the store: the library passes it on as it is, and retrying the same call fails again.
119
+ * The message names no segment of the scope. New in 0.9.0.
120
+ */
121
+ export class DocumentScopeError extends TypeError {
122
+ readonly code: DocumentScopeErrorCode;
123
+
124
+ constructor(code: DocumentScopeErrorCode, message: string = SCOPE_MESSAGES[code], options: { cause?: unknown } = {}) {
125
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
126
+ this.name = "DocumentScopeError";
127
+ this.code = code;
128
+ }
129
+
130
+ /** Whether `value` is a `DocumentScopeError`, made by this copy of the package or another one. */
131
+ static is(value: unknown): value is DocumentScopeError {
132
+ return branded(value, DOCUMENT_SCOPE_ERROR);
133
+ }
134
+ }
135
+ brand(DocumentScopeError, DOCUMENT_SCOPE_ERROR);
32
136
 
33
137
  /**
34
138
  * The errors a store threw while `ingest` wrote a document. `ingest` passes them on as they are,
@@ -49,12 +153,13 @@ export function isStoreWriteFailure(error: unknown): boolean {
49
153
 
50
154
  /**
51
155
  * What to tell a model, or a user, about an error: its message, unless it is a system error, whose
52
- * message names a path or a host of the server. Of that one only the code is passed on.
156
+ * message names a path or a host of the server. Of that one only the code is passed on, when it
157
+ * reads as one (`isErrorCode`).
53
158
  */
54
159
  export function safeErrorMessage(error: unknown): string {
55
- if (error instanceof DocumentStoreError) return error.message;
160
+ if (DocumentStoreError.is(error)) return (error as Error).message;
56
161
  const { code, syscall } = systemError(error);
57
- if (code && syscall) return `The file could not be read from storage (${code}). Try the call again.`;
162
+ if (code && syscall) return `The file could not be read from storage${isErrorCode(code) ? ` (${code})` : ""}. Try the call again.`;
58
163
  return error instanceof Error ? error.message : String(error);
59
164
  }
60
165
 
@@ -81,6 +186,8 @@ export function safeErrorMessage(error: unknown): string {
81
186
  * - "missing_dependency": the optional dependency for the format is not installed, could not be
82
187
  * loaded, or (`unpdf`) is of a version that cannot read PDFs on this Node.
83
188
  * - "unreadable": the file is damaged, or not of the type its name says.
189
+ * - "exists": a document with the ID the application gave (`IngestInput.id`) is already stored.
190
+ * Status 409. New in 0.9.0.
84
191
  */
85
192
  export type IngestErrorCode =
86
193
  | "empty"
@@ -97,7 +204,8 @@ export type IngestErrorCode =
97
204
  | "out_of_memory"
98
205
  | "busy"
99
206
  | "missing_dependency"
100
- | "unreadable";
207
+ | "unreadable"
208
+ | "exists";
101
209
 
102
210
  /**
103
211
  * `ingest` could not read a file. The message says why, in words for the person who uploaded it,
@@ -109,17 +217,23 @@ export class IngestError extends Error {
109
217
  readonly code: IngestErrorCode;
110
218
  /** For "busy": how long to wait before trying again, in milliseconds. */
111
219
  declare readonly retryAfterMs?: number;
112
- /** The HTTP status the upload handler answers with: 422 for a file that cannot be read, 413 for "too_large", 503 for "busy". */
220
+ /** The HTTP status the upload handler answers with: 422 for a file that cannot be read, 413 for "too_large", 409 for "exists", 503 for "busy". */
113
221
  readonly status: number;
114
222
 
115
223
  constructor(code: IngestErrorCode, message: string, options: { cause?: unknown; retryAfterMs?: number } = {}) {
116
224
  super(message, options.cause === undefined ? undefined : { cause: options.cause });
117
225
  this.name = "IngestError";
118
226
  this.code = code;
119
- this.status = code === "busy" ? 503 : code === "too_large" ? 413 : 422;
227
+ this.status = code === "busy" ? 503 : code === "too_large" ? 413 : code === "exists" ? 409 : 422;
120
228
  if (options.retryAfterMs !== undefined) (this as { retryAfterMs?: number }).retryAfterMs = options.retryAfterMs;
121
229
  }
230
+
231
+ /** Whether `value` is an `IngestError`, made by this copy of the package or another one. New in 0.9.0. */
232
+ static is(value: unknown): value is IngestError {
233
+ return branded(value, INGEST_ERROR);
234
+ }
122
235
  }
236
+ brand(IngestError, INGEST_ERROR);
123
237
 
124
238
  /** The refusals of the library, by the words of their messages: the extractors give plain `Error`s. */
125
239
  const REFUSALS: Array<[RegExp, IngestErrorCode]> = [
@@ -159,7 +273,7 @@ export function ingestErrorCodeOf(message: string): IngestErrorCode {
159
273
  * own that reads a file).
160
274
  */
161
275
  export function toIngestError(error: unknown): unknown {
162
- if (error instanceof IngestError || !(error instanceof Error)) return error;
276
+ if (IngestError.is(error) || !(error instanceof Error)) return error;
163
277
  const { code, syscall } = systemError(error);
164
278
  const { status, statusCode } = error as { status?: unknown; statusCode?: unknown };
165
279
  if ((code && syscall) || typeof status === "number" || typeof statusCode === "number") return error;