llm-large-files 0.8.2 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (288) hide show
  1. package/CHANGELOG.md +981 -0
  2. package/README.md +22 -17
  3. package/dist/access.d.ts +128 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +234 -0
  6. package/dist/access.js.map +1 -0
  7. package/dist/aggregate.d.ts +6 -0
  8. package/dist/aggregate.d.ts.map +1 -1
  9. package/dist/aggregate.js +86 -13
  10. package/dist/aggregate.js.map +1 -1
  11. package/dist/analyze.d.ts +4 -0
  12. package/dist/analyze.d.ts.map +1 -1
  13. package/dist/analyze.js +2 -2
  14. package/dist/analyze.js.map +1 -1
  15. package/dist/answer-info.d.ts +26 -0
  16. package/dist/answer-info.d.ts.map +1 -0
  17. package/dist/answer-info.js +32 -0
  18. package/dist/answer-info.js.map +1 -0
  19. package/dist/anthropic/adapter.d.ts +5 -1
  20. package/dist/anthropic/adapter.d.ts.map +1 -1
  21. package/dist/anthropic/adapter.js +35 -10
  22. package/dist/anthropic/adapter.js.map +1 -1
  23. package/dist/ask.d.ts +159 -14
  24. package/dist/ask.d.ts.map +1 -1
  25. package/dist/ask.js +743 -113
  26. package/dist/ask.js.map +1 -1
  27. package/dist/cache.d.ts +12 -3
  28. package/dist/cache.d.ts.map +1 -1
  29. package/dist/cache.js +18 -5
  30. package/dist/cache.js.map +1 -1
  31. package/dist/citations.d.ts +36 -0
  32. package/dist/citations.d.ts.map +1 -0
  33. package/dist/citations.js +291 -0
  34. package/dist/citations.js.map +1 -0
  35. package/dist/encoding.js +5 -3
  36. package/dist/encoding.js.map +1 -1
  37. package/dist/error-info.d.ts +70 -0
  38. package/dist/error-info.d.ts.map +1 -0
  39. package/dist/error-info.js +253 -0
  40. package/dist/error-info.js.map +1 -0
  41. package/dist/errors.d.ts +74 -8
  42. package/dist/errors.d.ts.map +1 -1
  43. package/dist/errors.js +104 -15
  44. package/dist/errors.js.map +1 -1
  45. package/dist/events.d.ts +57 -13
  46. package/dist/events.d.ts.map +1 -1
  47. package/dist/events.js +42 -11
  48. package/dist/events.js.map +1 -1
  49. package/dist/evidence.d.ts +4 -2
  50. package/dist/evidence.d.ts.map +1 -1
  51. package/dist/evidence.js +35 -5
  52. package/dist/evidence.js.map +1 -1
  53. package/dist/extract.d.ts +32 -8
  54. package/dist/extract.d.ts.map +1 -1
  55. package/dist/extract.js +52 -36
  56. package/dist/extract.js.map +1 -1
  57. package/dist/gemini/adapter.d.ts +54 -7
  58. package/dist/gemini/adapter.d.ts.map +1 -1
  59. package/dist/gemini/adapter.js +152 -41
  60. package/dist/gemini/adapter.js.map +1 -1
  61. package/dist/gemini/chat.d.ts +38 -53
  62. package/dist/gemini/chat.d.ts.map +1 -1
  63. package/dist/gemini/chat.js +20 -25
  64. package/dist/gemini/chat.js.map +1 -1
  65. package/dist/gemini/endpoints.d.ts +59 -11
  66. package/dist/gemini/endpoints.d.ts.map +1 -1
  67. package/dist/gemini/endpoints.js +33 -7
  68. package/dist/gemini/endpoints.js.map +1 -1
  69. package/dist/gemini/errors.d.ts +39 -5
  70. package/dist/gemini/errors.d.ts.map +1 -1
  71. package/dist/gemini/errors.js +70 -9
  72. package/dist/gemini/errors.js.map +1 -1
  73. package/dist/gemini/generate.d.ts +53 -2
  74. package/dist/gemini/generate.d.ts.map +1 -1
  75. package/dist/gemini/generate.js +100 -50
  76. package/dist/gemini/generate.js.map +1 -1
  77. package/dist/gemini/index.d.ts +4 -4
  78. package/dist/gemini/index.d.ts.map +1 -1
  79. package/dist/http.d.ts +41 -3
  80. package/dist/http.d.ts.map +1 -1
  81. package/dist/http.js +40 -2
  82. package/dist/http.js.map +1 -1
  83. package/dist/index.d.ts +13 -8
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.js +8 -5
  86. package/dist/index.js.map +1 -1
  87. package/dist/ingest.d.ts +78 -0
  88. package/dist/ingest.d.ts.map +1 -0
  89. package/dist/ingest.js +893 -0
  90. package/dist/ingest.js.map +1 -0
  91. package/dist/library.d.ts +295 -33
  92. package/dist/library.d.ts.map +1 -1
  93. package/dist/library.js +458 -650
  94. package/dist/library.js.map +1 -1
  95. package/dist/map-reduce.d.ts +176 -10
  96. package/dist/map-reduce.d.ts.map +1 -1
  97. package/dist/map-reduce.js +807 -61
  98. package/dist/map-reduce.js.map +1 -1
  99. package/dist/model.d.ts +79 -6
  100. package/dist/model.d.ts.map +1 -1
  101. package/dist/model.js +80 -4
  102. package/dist/model.js.map +1 -1
  103. package/dist/node/handlers.d.ts +247 -14
  104. package/dist/node/handlers.d.ts.map +1 -1
  105. package/dist/node/handlers.js +491 -227
  106. package/dist/node/handlers.js.map +1 -1
  107. package/dist/node/index.d.ts +3 -2
  108. package/dist/node/index.d.ts.map +1 -1
  109. package/dist/node/index.js +2 -1
  110. package/dist/node/index.js.map +1 -1
  111. package/dist/node/ingest-child.d.ts +7 -1
  112. package/dist/node/ingest-child.d.ts.map +1 -1
  113. package/dist/node/ingest-child.js +19 -4
  114. package/dist/node/ingest-child.js.map +1 -1
  115. package/dist/node/isolated.d.ts +3 -1
  116. package/dist/node/isolated.d.ts.map +1 -1
  117. package/dist/node/isolated.js +11 -4
  118. package/dist/node/isolated.js.map +1 -1
  119. package/dist/node/originals.d.ts +19 -0
  120. package/dist/node/originals.d.ts.map +1 -0
  121. package/dist/node/originals.js +82 -0
  122. package/dist/node/originals.js.map +1 -0
  123. package/dist/node/spool.d.ts +106 -0
  124. package/dist/node/spool.d.ts.map +1 -0
  125. package/dist/node/spool.js +378 -0
  126. package/dist/node/spool.js.map +1 -0
  127. package/dist/node/sse.d.ts +6 -4
  128. package/dist/node/sse.d.ts.map +1 -1
  129. package/dist/node/sse.js +9 -7
  130. package/dist/node/sse.js.map +1 -1
  131. package/dist/openai/adapter.d.ts +5 -1
  132. package/dist/openai/adapter.d.ts.map +1 -1
  133. package/dist/openai/adapter.js +53 -12
  134. package/dist/openai/adapter.js.map +1 -1
  135. package/dist/output-limit.d.ts +2 -1
  136. package/dist/output-limit.d.ts.map +1 -1
  137. package/dist/output-limit.js +5 -2
  138. package/dist/output-limit.js.map +1 -1
  139. package/dist/pdf-layout.d.ts.map +1 -1
  140. package/dist/pdf-layout.js +71 -12
  141. package/dist/pdf-layout.js.map +1 -1
  142. package/dist/pdf-outline.d.ts +71 -0
  143. package/dist/pdf-outline.d.ts.map +1 -0
  144. package/dist/pdf-outline.js +414 -0
  145. package/dist/pdf-outline.js.map +1 -0
  146. package/dist/plan.d.ts +137 -7
  147. package/dist/plan.d.ts.map +1 -1
  148. package/dist/plan.js +248 -26
  149. package/dist/plan.js.map +1 -1
  150. package/dist/prepare.d.ts +50 -0
  151. package/dist/prepare.d.ts.map +1 -0
  152. package/dist/prepare.js +207 -0
  153. package/dist/prepare.js.map +1 -0
  154. package/dist/ranged.d.ts +16 -11
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +56 -12
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +3 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +6 -2
  161. package/dist/retry.js.map +1 -1
  162. package/dist/scope.d.ts +25 -0
  163. package/dist/scope.d.ts.map +1 -0
  164. package/dist/scope.js +60 -0
  165. package/dist/scope.js.map +1 -0
  166. package/dist/search.d.ts +7 -0
  167. package/dist/search.d.ts.map +1 -1
  168. package/dist/search.js +72 -10
  169. package/dist/search.js.map +1 -1
  170. package/dist/source.d.ts +60 -0
  171. package/dist/source.d.ts.map +1 -0
  172. package/dist/source.js +170 -0
  173. package/dist/source.js.map +1 -0
  174. package/dist/stores.d.ts +126 -31
  175. package/dist/stores.d.ts.map +1 -1
  176. package/dist/stores.js +655 -141
  177. package/dist/stores.js.map +1 -1
  178. package/dist/testing/fake-fetch.d.ts +31 -0
  179. package/dist/testing/fake-fetch.d.ts.map +1 -0
  180. package/dist/testing/fake-fetch.js +66 -0
  181. package/dist/testing/fake-fetch.js.map +1 -0
  182. package/dist/testing/fake-model.d.ts +38 -0
  183. package/dist/testing/fake-model.d.ts.map +1 -0
  184. package/dist/testing/fake-model.js +62 -0
  185. package/dist/testing/fake-model.js.map +1 -0
  186. package/dist/testing/index.d.ts +7 -0
  187. package/dist/testing/index.d.ts.map +1 -0
  188. package/dist/testing/index.js +9 -0
  189. package/dist/testing/index.js.map +1 -0
  190. package/dist/testing/store-checks.d.ts +72 -0
  191. package/dist/testing/store-checks.d.ts.map +1 -0
  192. package/dist/testing/store-checks.js +619 -0
  193. package/dist/testing/store-checks.js.map +1 -0
  194. package/dist/tools.d.ts +47 -2
  195. package/dist/tools.d.ts.map +1 -1
  196. package/dist/tools.js +440 -71
  197. package/dist/tools.js.map +1 -1
  198. package/dist/types.d.ts +165 -14
  199. package/dist/types.d.ts.map +1 -1
  200. package/dist/whole-cost.d.ts +37 -0
  201. package/dist/whole-cost.d.ts.map +1 -0
  202. package/dist/whole-cost.js +46 -0
  203. package/dist/whole-cost.js.map +1 -0
  204. package/docs/README.md +21 -8
  205. package/docs/getting-started.md +18 -13
  206. package/docs/guides/anthropic.md +17 -10
  207. package/docs/guides/conversations.md +112 -47
  208. package/docs/guides/costs-and-limits.md +147 -42
  209. package/docs/guides/deployment.md +380 -86
  210. package/docs/guides/errors-and-reliability.md +317 -67
  211. package/docs/guides/explorer-model.md +4 -1
  212. package/docs/guides/openai-compatible.md +47 -7
  213. package/docs/guides/own-adapter-and-loop.md +60 -16
  214. package/docs/guides/pdfs.md +219 -36
  215. package/docs/guides/storage.md +676 -145
  216. package/docs/guides/testing.md +149 -129
  217. package/docs/guides/vertex-and-gemini.md +169 -57
  218. package/docs/guides/web-app.md +318 -80
  219. package/docs/how-it-works.md +155 -30
  220. package/docs/measurements.md +215 -13
  221. package/docs/publishing.md +185 -37
  222. package/docs/reference/anthropic.md +12 -7
  223. package/docs/reference/ask.md +415 -47
  224. package/docs/reference/errors-and-retries.md +194 -14
  225. package/docs/reference/events.md +77 -27
  226. package/docs/reference/gemini.md +252 -87
  227. package/docs/reference/library.md +886 -178
  228. package/docs/reference/node.md +659 -111
  229. package/docs/reference/openai.md +21 -10
  230. package/docs/reference/testing.md +311 -0
  231. package/docs/reference/tools.md +285 -30
  232. package/docs/security.md +404 -78
  233. package/docs/troubleshooting.md +151 -70
  234. package/docs/upgrading-0.10.md +472 -0
  235. package/docs/upgrading-0.9.md +890 -0
  236. package/package.json +16 -3
  237. package/src/access.ts +267 -0
  238. package/src/aggregate.ts +92 -14
  239. package/src/analyze.ts +2 -2
  240. package/src/answer-info.ts +45 -0
  241. package/src/anthropic/adapter.ts +40 -11
  242. package/src/ask.ts +866 -115
  243. package/src/cache.ts +20 -5
  244. package/src/citations.ts +294 -0
  245. package/src/encoding.ts +6 -4
  246. package/src/error-info.ts +290 -0
  247. package/src/errors.ts +131 -15
  248. package/src/events.ts +112 -24
  249. package/src/evidence.ts +35 -5
  250. package/src/extract.ts +56 -34
  251. package/src/gemini/adapter.ts +196 -43
  252. package/src/gemini/chat.ts +63 -78
  253. package/src/gemini/endpoints.ts +89 -16
  254. package/src/gemini/errors.ts +74 -11
  255. package/src/gemini/generate.ts +147 -57
  256. package/src/gemini/index.ts +4 -4
  257. package/src/http.ts +65 -4
  258. package/src/index.ts +13 -8
  259. package/src/ingest.ts +958 -0
  260. package/src/library.ts +711 -651
  261. package/src/map-reduce.ts +858 -70
  262. package/src/model.ts +113 -9
  263. package/src/node/handlers.ts +709 -221
  264. package/src/node/index.ts +14 -2
  265. package/src/node/ingest-child.ts +24 -6
  266. package/src/node/isolated.ts +11 -4
  267. package/src/node/originals.ts +78 -0
  268. package/src/node/spool.ts +379 -0
  269. package/src/node/sse.ts +9 -7
  270. package/src/openai/adapter.ts +56 -13
  271. package/src/output-limit.ts +5 -2
  272. package/src/pdf-layout.ts +69 -11
  273. package/src/pdf-outline.ts +400 -0
  274. package/src/plan.ts +287 -36
  275. package/src/prepare.ts +253 -0
  276. package/src/ranged.ts +48 -14
  277. package/src/retry.ts +6 -2
  278. package/src/scope.ts +63 -0
  279. package/src/search.ts +69 -13
  280. package/src/source.ts +178 -0
  281. package/src/stores.ts +702 -142
  282. package/src/testing/fake-fetch.ts +80 -0
  283. package/src/testing/fake-model.ts +78 -0
  284. package/src/testing/index.ts +11 -0
  285. package/src/testing/store-checks.ts +660 -0
  286. package/src/tools.ts +461 -73
  287. package/src/types.ts +151 -14
  288. package/src/whole-cost.ts +64 -0
package/src/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,126 @@ 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"; since 0.10.0, "ETIMEDOUT" for a store call that did
73
+ * not end within `storeTimeoutMs`, and "STORE_STUCK" for one refused at once because too many
74
+ * calls of the process are stuck (`maxStuckStoreCalls`).
75
+ */
20
76
  readonly code?: string;
21
77
  /** The system call that failed (`open`, `read`), when there is one. */
22
78
  readonly syscall?: string;
79
+ /** What the store was doing. "read" unless it was made with another. */
80
+ readonly operation: DocumentStoreOperation;
81
+ /** The HTTP status to answer with: the server cannot serve the request now. */
82
+ readonly status: 503 = 503;
23
83
 
24
- constructor(cause: unknown) {
25
- const { code, syscall } = systemError(cause);
26
- super(`The document store could not be read${code ? ` (${code})` : ""}. Try again.`, { cause });
84
+ constructor(cause: unknown, options: { operation?: DocumentStoreOperation; code?: string } = {}) {
85
+ const found = systemError(cause);
86
+ const code = options.code ?? found.code;
87
+ const operation = options.operation ?? "read";
88
+ super(storeMessage(operation, code), { cause });
27
89
  this.name = "DocumentStoreError";
90
+ this.operation = operation;
28
91
  if (code) this.code = code;
29
- if (syscall) this.syscall = syscall;
92
+ if (found.syscall) this.syscall = found.syscall;
93
+ }
94
+
95
+ /** Whether `value` is a `DocumentStoreError`, made by this copy of the package or another one. New in 0.9.0. */
96
+ static is(value: unknown): value is DocumentStoreError {
97
+ return branded(value, DOCUMENT_STORE_ERROR);
30
98
  }
31
99
  }
100
+ brand(DocumentStoreError, DOCUMENT_STORE_ERROR);
101
+
102
+ /**
103
+ * Why a scope was refused (see `DocumentScopeError`):
104
+ * - "scope_invalid": not an array of 1 to 8 segments of 1 to 256 characters, without control
105
+ * characters, "/" or "\", and not "." or "..", or not one the store can keep;
106
+ * - "scope_required": the store needs a scope, and the call had none;
107
+ * - "scope_missing": the store keeps the scope in a folder that is gone (the chat was deleted).
108
+ */
109
+ export type DocumentScopeErrorCode = "scope_required" | "scope_invalid" | "scope_missing";
110
+
111
+ const SCOPE_MESSAGES: Record<DocumentScopeErrorCode, string> = {
112
+ scope_invalid: "The scope is not valid.",
113
+ scope_required: "A scope is required: pass the scope of the document, such as [userId, chatId].",
114
+ scope_missing: "The scope no longer exists.",
115
+ };
116
+
117
+ /**
118
+ * A scope (`DocumentScope`) that cannot be used: one that is not valid, a call without one to a
119
+ * store that needs one, or a scope whose place in the store is gone. A mistake in the call, not a
120
+ * failure of the store: the library passes it on as it is, and retrying the same call fails again.
121
+ * The message names no segment of the scope. New in 0.9.0.
122
+ */
123
+ export class DocumentScopeError extends TypeError {
124
+ readonly code: DocumentScopeErrorCode;
125
+
126
+ constructor(code: DocumentScopeErrorCode, message: string = SCOPE_MESSAGES[code], options: { cause?: unknown } = {}) {
127
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
128
+ this.name = "DocumentScopeError";
129
+ this.code = code;
130
+ }
131
+
132
+ /** Whether `value` is a `DocumentScopeError`, made by this copy of the package or another one. */
133
+ static is(value: unknown): value is DocumentScopeError {
134
+ return branded(value, DOCUMENT_SCOPE_ERROR);
135
+ }
136
+ }
137
+ brand(DocumentScopeError, DOCUMENT_SCOPE_ERROR);
32
138
 
33
139
  /**
34
140
  * The errors a store threw while `ingest` wrote a document. `ingest` passes them on as they are,
@@ -49,12 +155,13 @@ export function isStoreWriteFailure(error: unknown): boolean {
49
155
 
50
156
  /**
51
157
  * 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.
158
+ * message names a path or a host of the server. Of that one only the code is passed on, when it
159
+ * reads as one (`isErrorCode`).
53
160
  */
54
161
  export function safeErrorMessage(error: unknown): string {
55
- if (error instanceof DocumentStoreError) return error.message;
162
+ if (DocumentStoreError.is(error)) return (error as Error).message;
56
163
  const { code, syscall } = systemError(error);
57
- if (code && syscall) return `The file could not be read from storage (${code}). Try the call again.`;
164
+ if (code && syscall) return `The file could not be read from storage${isErrorCode(code) ? ` (${code})` : ""}. Try the call again.`;
58
165
  return error instanceof Error ? error.message : String(error);
59
166
  }
60
167
 
@@ -81,6 +188,8 @@ export function safeErrorMessage(error: unknown): string {
81
188
  * - "missing_dependency": the optional dependency for the format is not installed, could not be
82
189
  * loaded, or (`unpdf`) is of a version that cannot read PDFs on this Node.
83
190
  * - "unreadable": the file is damaged, or not of the type its name says.
191
+ * - "exists": a document with the ID the application gave (`IngestInput.id`) is already stored.
192
+ * Status 409. New in 0.9.0.
84
193
  */
85
194
  export type IngestErrorCode =
86
195
  | "empty"
@@ -97,7 +206,8 @@ export type IngestErrorCode =
97
206
  | "out_of_memory"
98
207
  | "busy"
99
208
  | "missing_dependency"
100
- | "unreadable";
209
+ | "unreadable"
210
+ | "exists";
101
211
 
102
212
  /**
103
213
  * `ingest` could not read a file. The message says why, in words for the person who uploaded it,
@@ -109,17 +219,23 @@ export class IngestError extends Error {
109
219
  readonly code: IngestErrorCode;
110
220
  /** For "busy": how long to wait before trying again, in milliseconds. */
111
221
  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". */
222
+ /** 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
223
  readonly status: number;
114
224
 
115
225
  constructor(code: IngestErrorCode, message: string, options: { cause?: unknown; retryAfterMs?: number } = {}) {
116
226
  super(message, options.cause === undefined ? undefined : { cause: options.cause });
117
227
  this.name = "IngestError";
118
228
  this.code = code;
119
- this.status = code === "busy" ? 503 : code === "too_large" ? 413 : 422;
229
+ this.status = code === "busy" ? 503 : code === "too_large" ? 413 : code === "exists" ? 409 : 422;
120
230
  if (options.retryAfterMs !== undefined) (this as { retryAfterMs?: number }).retryAfterMs = options.retryAfterMs;
121
231
  }
232
+
233
+ /** Whether `value` is an `IngestError`, made by this copy of the package or another one. New in 0.9.0. */
234
+ static is(value: unknown): value is IngestError {
235
+ return branded(value, INGEST_ERROR);
236
+ }
122
237
  }
238
+ brand(IngestError, INGEST_ERROR);
123
239
 
124
240
  /** The refusals of the library, by the words of their messages: the extractors give plain `Error`s. */
125
241
  const REFUSALS: Array<[RegExp, IngestErrorCode]> = [
@@ -159,7 +275,7 @@ export function ingestErrorCodeOf(message: string): IngestErrorCode {
159
275
  * own that reads a file).
160
276
  */
161
277
  export function toIngestError(error: unknown): unknown {
162
- if (error instanceof IngestError || !(error instanceof Error)) return error;
278
+ if (IngestError.is(error) || !(error instanceof Error)) return error;
163
279
  const { code, syscall } = systemError(error);
164
280
  const { status, statusCode } = error as { status?: unknown; statusCode?: unknown };
165
281
  if ((code && syscall) || typeof status === "number" || typeof statusCode === "number") return error;
package/src/events.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  // What a question or an ingest does while it runs, as typed data in order. The callbacks of
2
2
  // earlier versions (onText, onActivity, onStep) still get the same strings, at the same moments.
3
3
  import type { AskResult } from "./ask.js";
4
- import { DocumentStoreError, IngestError, type IngestErrorCode } from "./errors.js";
4
+ import { DocumentScopeError, DocumentStoreError, IngestError, isErrorCode, type DocumentScopeErrorCode, type IngestErrorCode } from "./errors.js";
5
5
  import type { Evidence } from "./evidence.js";
6
6
  import { modelFailureReason } from "./map-reduce.js";
7
- import type { ModelErrorKind, ModelReply, ModelUsage, ToolTurn } from "./model.js";
7
+ import { classifyModelError, DocumentsNotFoundError, isModelStatus, type ModelErrorKind, type ModelReply, type ModelUsage, type ToolTurn } from "./model.js";
8
8
  import type { DocumentFormat, DocumentMeta, DocumentSummary, ToolResult } from "./types.js";
9
9
 
10
10
  /** What every event carries. */
@@ -35,7 +35,10 @@ export type EventError = {
35
35
  * code only.
36
36
  */
37
37
  message: string;
38
- /** For a model error: what kind it is (`errorKindOf`). */
38
+ /**
39
+ * For a model error: what kind it is (`errorKindOf`). Since 0.9.0 also for an error with a status
40
+ * (0, or 400 and more) and no kind of its own: the kind its status gives (`classifyModelError`).
41
+ */
39
42
  kind?: ModelErrorKind;
40
43
  /** For an HTTP error: its status. 0 when no answer came. */
41
44
  status?: number;
@@ -43,9 +46,11 @@ export type EventError = {
43
46
  name?: string;
44
47
  /**
45
48
  * For a file `ingest` could not read: why, as `IngestError.code` ("too_large", "no_text",
46
- * "busy"…), so a page can say it in its own words. New in 0.8.0.
49
+ * "busy"…), so a page can say it in its own words. New in 0.8.0. Since 0.9.0 also the code of a
50
+ * scope that cannot be used (`DocumentScopeError`, `name` "DocumentScopeError"): "scope_missing"
51
+ * when the chat was deleted.
47
52
  */
48
- code?: IngestErrorCode;
53
+ code?: IngestErrorCode | DocumentScopeErrorCode;
49
54
  };
50
55
 
51
56
  /**
@@ -77,9 +82,13 @@ export type RequestPurpose = "turn" | "nudge" | "closing" | "answer_again" | "di
77
82
  * - "refused": it was not run, for a limit of the question (cost, room, reads of a whole file);
78
83
  * - "already_shown": it repeated a call whose result is still in the conversation, and was answered
79
84
  * with a pointer to it;
80
- * - "not_run": the turn had more calls than `limits.callsPerTurn`.
85
+ * - "not_run": the turn had more calls than `limits.callsPerTurn`;
86
+ * - "redacted": it ran, and `AskOptions.onToolResult` replaced its result: the model was sent the
87
+ * replacement. New in 0.10.0.
88
+ *
89
+ * A switch over every outcome must handle the outcomes added in a later version.
81
90
  */
82
- export type ToolOutcome = "ok" | "error" | "refused" | "already_shown" | "not_run";
91
+ export type ToolOutcome = "ok" | "error" | "refused" | "already_shown" | "not_run" | "redacted";
83
92
 
84
93
  /**
85
94
  * Something the run did that is not a request or a tool call:
@@ -93,7 +102,19 @@ export type ToolOutcome = "ok" | "error" | "refused" | "already_shown" | "not_ru
93
102
  * - "calls_not_run": a turn had more calls than `limits.callsPerTurn`;
94
103
  * - "budget_reached": `limits.inputTokens` or `limits.requests` was reached, so no more tools run;
95
104
  * - "no_room": there is no room left in the conversation for another tool result;
96
- * - "blocked": the provider refused the prompt (`AskResult.blockReason`).
105
+ * - "blocked": the provider refused the prompt (`AskResult.blockReason`);
106
+ * - "documents_missing": documents of `documentIds` were missing, and the question is answered
107
+ * without them (`AskOptions.onMissingDocuments` "drop"; `AskResult.missing`). New in 0.9.0;
108
+ * - "document_gone": a tool call found a document gone during the question (deleted or expired
109
+ * since it was planned). The model was told so in the call's result. New in 0.9.0;
110
+ * - "page_looks_busy": a look at pages waited its turn (`maxConcurrentPageLooks`) longer than
111
+ * `pageLookWaitMs`, and was not run. The model was told so in the call's result. New in 0.9.0;
112
+ * - "answer_filtered": a filter of the provider stopped the answer, with or without text
113
+ * (`AskResult.finish` "filtered"). New in 0.10.0;
114
+ * - "answer_cut": the answer stopped at the output limit (`AskResult.finish` "cut"). New in
115
+ * 0.10.0.
116
+ *
117
+ * A switch over every code must handle the codes added in a later version.
97
118
  */
98
119
  export type NoticeCode =
99
120
  | "searching_instead"
@@ -106,7 +127,12 @@ export type NoticeCode =
106
127
  | "calls_not_run"
107
128
  | "budget_reached"
108
129
  | "no_room"
109
- | "blocked";
130
+ | "blocked"
131
+ | "documents_missing"
132
+ | "document_gone"
133
+ | "page_looks_busy"
134
+ | "answer_filtered"
135
+ | "answer_cut";
110
136
 
111
137
  /**
112
138
  * Where a notice went in the callbacks of earlier versions: "activity" to `onActivity`, "step" to
@@ -125,10 +151,15 @@ export type EventResult = Omit<AskResult, "toolTurns" | "plan"> & {
125
151
  toolTurns?: ToolTurn[];
126
152
  /**
127
153
  * Which documents went in whole and which were searched, named as `DocumentRef`s: their full
128
- * `DocumentMeta` (owner, outline headings, the commonest lines of a log) is left out unless
129
- * `eventResults` is true. The returned result has the full plan.
154
+ * `DocumentMeta` (owner, scope, the SHA-256 and the ref of the original, outline headings, the
155
+ * commonest lines of a log) is left out unless `eventResults` is true. The returned result has
156
+ * the full plan. Since 0.10.0 the type of the full metadata here has no owner, scope, `sha256`,
157
+ * `original` or `metaVersion`, which stay on the server: they are left out at run time too.
130
158
  */
131
- plan: { inline: Array<DocumentRef | DocumentMeta>; searchable: Array<DocumentRef | DocumentMeta> };
159
+ plan: {
160
+ inline: Array<DocumentRef | Omit<DocumentMeta, "owner" | "scope" | "sha256" | "original" | "metaVersion">>;
161
+ searchable: Array<DocumentRef | Omit<DocumentMeta, "owner" | "scope" | "sha256" | "original" | "metaVersion">>;
162
+ };
132
163
  };
133
164
 
134
165
  /** The events of a question (`askWithFiles`, `askStream`), in the order they happen. */
@@ -178,6 +209,10 @@ export type AskEvent =
178
209
  finishReason?: string;
179
210
  /** How many tool calls the reply asked for. */
180
211
  toolCalls?: number;
212
+ /** The provider's ID of the response (`ModelReply.responseId`), when the adapter gives one. New in 0.10.0. */
213
+ responseId?: string;
214
+ /** The model that wrote the response, as the provider names it (`ModelReply.responseModel`). New in 0.10.0. */
215
+ responseModel?: string;
181
216
  /** With outcome "error": why. A request that failed may still be followed by others (an overflow made smaller, a part read in halves). */
182
217
  error?: EventError;
183
218
  })
@@ -252,7 +287,22 @@ export type AskEvent =
252
287
  /** The result itself. Only with `AskOptions.eventResults: true`: it holds document text. */
253
288
  result?: ToolResult;
254
289
  })
255
- | (EventBase & { type: "notice"; code: NoticeCode; message: string; display: NoticeDisplay })
290
+ | (EventBase & {
291
+ type: "notice";
292
+ code: NoticeCode;
293
+ message: string;
294
+ display: NoticeDisplay;
295
+ /**
296
+ * The documents the notice is about: those left out ("documents_missing"), the one found gone
297
+ * ("document_gone"), the one whose pages were not looked at ("page_looks_busy"). New in 0.9.0.
298
+ */
299
+ documentIds?: string[];
300
+ /**
301
+ * With "answer_filtered", under `AskOptions.filteredAnswer: "drop"`: text of the answer was
302
+ * already sent (`text` events, `onText`), and the page should take it away. New in 0.10.0.
303
+ */
304
+ discardText?: true;
305
+ })
256
306
  /** Always last when the question returns. Nothing comes after it. */
257
307
  | (EventBase & { type: "run.finish"; result: EventResult })
258
308
  /**
@@ -280,7 +330,15 @@ export type IngestEvent =
280
330
  unit: "pages" | "parts" | "bytes" | "characters";
281
331
  })
282
332
  /** Always last when the ingest stores the document. */
283
- | (EventBase & { type: "ingest.finish"; document: DocumentSummary })
333
+ | (EventBase & {
334
+ type: "ingest.finish";
335
+ document: DocumentSummary;
336
+ /**
337
+ * What the upload handler's `onUploaded` returned as `answer`, for the page: only in the
338
+ * event the handler sends, never in the events of `files.ingest`. New in 0.9.0.
339
+ */
340
+ app?: Record<string, unknown>;
341
+ })
284
342
  /** Always last when the ingest throws (a refusal or an abort included). */
285
343
  | (EventBase & { type: "ingest.error"; error: EventError });
286
344
 
@@ -303,15 +361,32 @@ export function newRunId(prefix = "run"): string {
303
361
  export function eventErrorOf(error: unknown, message?: string): EventError {
304
362
  // It never throws: an error whose fields throw when read (a getter, a proxy) is told plainly.
305
363
  try {
306
- const record = (typeof error === "object" && error !== null ? error : {}) as { kind?: unknown; status?: unknown; name?: unknown };
307
- if (error instanceof IngestError) {
308
- // Its status is the upload's answer, not a model's.
309
- return { message: message ?? error.message, name: error.name, code: error.code, ...(error.code === "busy" || error.code === "too_large" ? { status: error.status } : {}) };
364
+ const record = (typeof error === "object" && error !== null ? error : {}) as { kind?: unknown; status?: unknown; name?: unknown; code?: unknown };
365
+ if (IngestError.is(error)) {
366
+ // Its status is the upload's answer, not a model's. A subclass of a name of its own (an
367
+ // extractor's) is told by the name errorInfoOf reads, as a store's own DocumentStoreError is.
368
+ return { message: message ?? error.message, name: "IngestError", code: error.code, ...(error.status !== 422 ? { status: error.status } : {}) };
369
+ }
370
+ // Its code tells a deleted chat from a scope the server gave wrong (errorInfoOf).
371
+ if (DocumentScopeError.is(error)) {
372
+ return { message: message ?? userMessageOf(error), name: "DocumentScopeError", ...(typeof error.code === "string" ? { code: error.code } : {}) };
310
373
  }
311
374
  const out: EventError = { message: message ?? userMessageOf(error) };
375
+ const own = DocumentStoreError.is(error) ? "DocumentStoreError" : DocumentsNotFoundError.is(error) ? "DocumentsNotFoundError" : undefined;
312
376
  if (typeof record.kind === "string") out.kind = record.kind as ModelErrorKind;
377
+ else if (isModelStatus(record.status) && own === undefined && !isPlainData(record)) {
378
+ // A model's error without a kind of its own (an adapter of yours, `httpError`): the kind its
379
+ // status gives, as its message is told, so that a model's EventError always has its kind.
380
+ // Plain data thrown is not an adapter's error, as errorInfoOf reads it. The message is read
381
+ // from any class, an Error or not (an SDK's own), as errorInfoOf and the loop read it.
382
+ const { code, message: text } = record as { code?: unknown; message?: unknown };
383
+ out.kind = classifyModelError(record.status, typeof text === "string" ? text : "", { code: typeof code === "string" ? code : undefined }).kind;
384
+ }
313
385
  if (typeof record.status === "number") out.status = record.status;
314
- if (typeof record.name === "string" && record.name) out.name = record.name;
386
+ // A store's own subclass of DocumentStoreError, of a name of its own, is told by the name
387
+ // errorInfoOf reads, as the upload handlers tell it.
388
+ if (own !== undefined) out.name = own;
389
+ else if (typeof record.name === "string" && record.name) out.name = record.name;
315
390
  return out;
316
391
  } catch {
317
392
  return { message: message ?? SOMETHING_WENT_WRONG };
@@ -320,19 +395,32 @@ export function eventErrorOf(error: unknown, message?: string): EventError {
320
395
 
321
396
  const SOMETHING_WENT_WRONG = "Something went wrong.";
322
397
 
398
+ /** Data, not an error: an object of no class, as an `EventError` is, or one parsed from JSON. */
399
+ export function isPlainData(value: object): boolean {
400
+ const proto: unknown = Object.getPrototypeOf(value);
401
+ return proto === Object.prototype || proto === null;
402
+ }
403
+
323
404
  /**
324
405
  * A message for users: a model error by its kind and status, a storage error by its code, the
325
406
  * library's own errors (refusals, a stop) as they are written, and anything that is not an
326
407
  * `Error` as "Something went wrong."
327
408
  */
328
409
  function userMessageOf(error: unknown): string {
329
- if (error instanceof DocumentStoreError) return error.message;
410
+ // The library's own errors with a status (503, 404) are not model errors: their words are safe.
411
+ if (DocumentStoreError.is(error) || DocumentsNotFoundError.is(error)) return (error as Error).message;
330
412
  if (typeof error !== "object" || error === null) return SOMETHING_WENT_WRONG;
331
413
  const record = error as { kind?: unknown; status?: unknown; code?: unknown; syscall?: unknown; message?: unknown };
332
- // A model error: the provider's words stay on the error.
333
- if (typeof record.kind === "string" || typeof record.status === "number") return modelFailureReason(error);
334
- // A system error (ENOENT, EACCES…): its message names paths of the server.
335
- if (typeof record.code === "string" && typeof record.syscall === "string") return `The file could not be read from storage (${record.code}).`;
414
+ // A model error, as eventErrorOf gives it a kind: the provider's words stay on the error.
415
+ if (typeof record.kind === "string" || (isModelStatus(record.status) && !isPlainData(record))) return modelFailureReason(error);
416
+ // Any other status (thrown plain data, a status no model answers with) is not a model's, and the
417
+ // words that came with it may be anyone's: errorInfoOf tells it so too.
418
+ if (typeof record.status === "number") return SOMETHING_WENT_WRONG;
419
+ // A system error (ENOENT, EACCES…): its message names paths of the server. Its code is told only
420
+ // when it reads as one: a driver may put a host in it.
421
+ if (typeof record.code === "string" && typeof record.syscall === "string") {
422
+ return `The file could not be read from storage${isErrorCode(record.code) ? ` (${record.code})` : ""}.`;
423
+ }
336
424
  if (!(error instanceof Error) && !(typeof DOMException !== "undefined" && error instanceof DOMException)) return SOMETHING_WENT_WRONG;
337
425
  return typeof record.message === "string" && record.message ? record.message : SOMETHING_WENT_WRONG;
338
426
  }
package/src/evidence.ts CHANGED
@@ -94,8 +94,13 @@ export function evidenceOf(call: ToolCall, result: ToolResult): Evidence | undef
94
94
  if (total < 1) return entry;
95
95
  return withRanges(total > 30 ? [[1, 30], [Math.max(1, total - 19), total]] : [[1, total]], []);
96
96
  }
97
- case TOOL_NAMES.analyze:
98
- return { ...entry, whole: true, ...(typeof call.args.task === "string" ? { query: call.args.task } : {}) };
97
+ case TOOL_NAMES.analyze: {
98
+ // A read that lists items (since 0.10.0) also showed the lines of the items in its result,
99
+ // each checked against its quote: those can be cited.
100
+ const items = (Array.isArray(result.items) ? result.items : []) as Array<{ line?: unknown }>;
101
+ const lines = items.flatMap((item): NumberRange[] => (typeof item.line === "number" && Number.isInteger(item.line) && item.line > 0 ? [[item.line, item.line]] : []));
102
+ return { ...withRanges(lines, []), whole: true, ...(typeof call.args.task === "string" ? { query: call.args.task } : {}) };
103
+ }
99
104
  case TOOL_NAMES.aggregate: {
100
105
  // The rows read are all of the table; what can be cited is the header and each group's first rows.
101
106
  const groups = (Array.isArray(result.groups) ? result.groups : []) as Array<{ lines?: unknown }>;
@@ -117,6 +122,8 @@ const KEPT_ANSWER_CHARACTERS = 6_000;
117
122
  const MOST_RANGES = 60;
118
123
  /** The groups kept of a search with `group_by`, the largest (or, by time, the first) ones. */
119
124
  const KEPT_GROUPS = 30;
125
+ /** The items kept of a whole-file read that lists them: their counts are kept whole. */
126
+ const KEPT_ITEMS = 20;
120
127
 
121
128
  const rangeText = ([from, to]: NumberRange) => (to > from ? `${from}-${to}` : String(from));
122
129
 
@@ -124,12 +131,23 @@ const rangeText = ([from, to]: NumberRange) => (to > from ? `${from}-${to}` : St
124
131
  * A short stand-in for a tool result that is dropped from the request to make room: it keeps
125
132
  * which document it was about and which lines or pages it showed, so the model can read them
126
133
  * again, and says that it is a stand-in. Undefined when there is nothing to gain: the result is an
127
- * error, is small already, or is such a stand-in. `hadFiles` is true for a result whose files
128
- * (pages) are dropped with it, however small its JSON is.
134
+ * error, is small already, is such a stand-in, or is no larger than its stand-in would be (a search
135
+ * counted by group, or an `aggregate_table` result, of a few short groups: the stand-in keeps the
136
+ * groups and adds a note; since 0.9.0). `hadFiles` is true for a result whose files (pages) are
137
+ * dropped with it, however small its JSON is: its stand-in is always given.
129
138
  */
130
139
  export function stubResult(call: ToolCall, result: ToolResult, hadFiles = false): ToolResult | undefined {
131
140
  if (typeof result.error === "string" || result.dropped === true) return undefined;
132
- if (!hadFiles && JSON.stringify(result).length < SMALL_RESULT_CHARACTERS) return undefined;
141
+ if (hadFiles) return standIn(call, result);
142
+ const size = JSON.stringify(result).length;
143
+ if (size < SMALL_RESULT_CHARACTERS) return undefined;
144
+ const stub = standIn(call, result);
145
+ // A stand-in as large as the result would take more room than it makes.
146
+ return JSON.stringify(stub).length < size ? stub : undefined;
147
+ }
148
+
149
+ /** The stand-in of `stubResult`, whatever its size. */
150
+ function standIn(call: ToolCall, result: ToolResult): ToolResult {
133
151
  const evidence = evidenceOf(call, result);
134
152
  const base: ToolResult = { ...(typeof result.document === "string" ? { document: result.document } : {}), dropped: true };
135
153
  const lines = evidence?.lines?.slice(0, MOST_RANGES).map(rangeText);
@@ -165,6 +183,18 @@ export function stubResult(call: ToolCall, result: ToolResult, hadFiles = false)
165
183
  note: "This result was shown to you earlier and was shortened to make room: the largest groups are kept. Run aggregate_table again for the others.",
166
184
  };
167
185
  case TOOL_NAMES.analyze: {
186
+ // A read that lists items (since 0.10.0): its counts stay, and its first items.
187
+ if (typeof result.total_items === "number") {
188
+ return {
189
+ ...base,
190
+ ...(typeof result.parts_read === "number" ? { parts_read: result.parts_read } : {}),
191
+ total_items: result.total_items,
192
+ ...(result.counts_by_label && typeof result.counts_by_label === "object" ? { counts_by_label: result.counts_by_label } : {}),
193
+ ...(typeof result.unverified_items === "number" ? { unverified_items: result.unverified_items } : {}),
194
+ ...(Array.isArray(result.items) ? { items: result.items.slice(0, KEPT_ITEMS) } : {}),
195
+ note: "This is the start of the list of the whole-file read, with its counts. The rest of the list was dropped from the conversation to make room.",
196
+ };
197
+ }
168
198
  const answer = typeof result.answer === "string" ? result.answer : "";
169
199
  return {
170
200
  ...base,