llm-large-files 0.5.0 → 0.8.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 (285) hide show
  1. package/CHANGELOG.md +1719 -466
  2. package/README.md +190 -60
  3. package/dist/analyze.d.ts +8 -1
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +198 -54
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +14 -3
  8. package/dist/anthropic/adapter.d.ts.map +1 -1
  9. package/dist/anthropic/adapter.js +194 -40
  10. package/dist/anthropic/adapter.js.map +1 -1
  11. package/dist/ask.d.ts +63 -7
  12. package/dist/ask.d.ts.map +1 -1
  13. package/dist/ask.js +1131 -214
  14. package/dist/ask.js.map +1 -1
  15. package/dist/decode.d.ts +19 -0
  16. package/dist/decode.d.ts.map +1 -0
  17. package/dist/decode.js +97 -0
  18. package/dist/decode.js.map +1 -0
  19. package/dist/encoding.d.ts +17 -0
  20. package/dist/encoding.d.ts.map +1 -0
  21. package/dist/encoding.js +852 -0
  22. package/dist/encoding.js.map +1 -0
  23. package/dist/errors.d.ts +59 -0
  24. package/dist/errors.d.ts.map +1 -1
  25. package/dist/errors.js +80 -0
  26. package/dist/errors.js.map +1 -1
  27. package/dist/events.d.ts +339 -0
  28. package/dist/events.d.ts.map +1 -0
  29. package/dist/events.js +163 -0
  30. package/dist/events.js.map +1 -0
  31. package/dist/evidence.d.ts +2 -0
  32. package/dist/evidence.d.ts.map +1 -1
  33. package/dist/evidence.js +9 -2
  34. package/dist/evidence.js.map +1 -1
  35. package/dist/extract.d.ts +26 -7
  36. package/dist/extract.d.ts.map +1 -1
  37. package/dist/extract.js +180 -314
  38. package/dist/extract.js.map +1 -1
  39. package/dist/gemini/adapter.d.ts +17 -8
  40. package/dist/gemini/adapter.d.ts.map +1 -1
  41. package/dist/gemini/adapter.js +117 -66
  42. package/dist/gemini/adapter.js.map +1 -1
  43. package/dist/gemini/chat.d.ts +23 -3
  44. package/dist/gemini/chat.d.ts.map +1 -1
  45. package/dist/gemini/chat.js +6 -2
  46. package/dist/gemini/chat.js.map +1 -1
  47. package/dist/gemini/endpoints.d.ts +5 -1
  48. package/dist/gemini/endpoints.d.ts.map +1 -1
  49. package/dist/gemini/endpoints.js +11 -2
  50. package/dist/gemini/endpoints.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +9 -4
  52. package/dist/gemini/errors.d.ts.map +1 -1
  53. package/dist/gemini/errors.js +32 -0
  54. package/dist/gemini/errors.js.map +1 -1
  55. package/dist/gemini/generate.d.ts +10 -2
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +33 -10
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +3 -3
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +2 -2
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -1
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -1
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/groups.d.ts +54 -0
  68. package/dist/groups.d.ts.map +1 -0
  69. package/dist/groups.js +136 -0
  70. package/dist/groups.js.map +1 -0
  71. package/dist/html.d.ts +11 -0
  72. package/dist/html.d.ts.map +1 -0
  73. package/dist/html.js +1112 -0
  74. package/dist/html.js.map +1 -0
  75. package/dist/http.d.ts +116 -0
  76. package/dist/http.d.ts.map +1 -1
  77. package/dist/http.js +347 -1
  78. package/dist/http.js.map +1 -1
  79. package/dist/index.d.ts +13 -7
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +7 -5
  82. package/dist/index.js.map +1 -1
  83. package/dist/library.d.ts +67 -5
  84. package/dist/library.d.ts.map +1 -1
  85. package/dist/library.js +449 -93
  86. package/dist/library.js.map +1 -1
  87. package/dist/limiter.d.ts +2 -1
  88. package/dist/limiter.d.ts.map +1 -1
  89. package/dist/limiter.js +3 -2
  90. package/dist/limiter.js.map +1 -1
  91. package/dist/map-reduce.d.ts +28 -1
  92. package/dist/map-reduce.d.ts.map +1 -1
  93. package/dist/map-reduce.js +240 -52
  94. package/dist/map-reduce.js.map +1 -1
  95. package/dist/model.d.ts +84 -2
  96. package/dist/model.d.ts.map +1 -1
  97. package/dist/model.js +190 -2
  98. package/dist/model.js.map +1 -1
  99. package/dist/node/handlers.d.ts +20 -4
  100. package/dist/node/handlers.d.ts.map +1 -1
  101. package/dist/node/handlers.js +184 -28
  102. package/dist/node/handlers.js.map +1 -1
  103. package/dist/node/index.d.ts +4 -0
  104. package/dist/node/index.d.ts.map +1 -1
  105. package/dist/node/index.js +2 -0
  106. package/dist/node/index.js.map +1 -1
  107. package/dist/node/ingest-child.d.ts +38 -0
  108. package/dist/node/ingest-child.d.ts.map +1 -0
  109. package/dist/node/ingest-child.js +42 -0
  110. package/dist/node/ingest-child.js.map +1 -0
  111. package/dist/node/isolated.d.ts +88 -0
  112. package/dist/node/isolated.d.ts.map +1 -0
  113. package/dist/node/isolated.js +381 -0
  114. package/dist/node/isolated.js.map +1 -0
  115. package/dist/node/sse.d.ts +59 -0
  116. package/dist/node/sse.d.ts.map +1 -0
  117. package/dist/node/sse.js +174 -0
  118. package/dist/node/sse.js.map +1 -0
  119. package/dist/office.d.ts +105 -0
  120. package/dist/office.d.ts.map +1 -0
  121. package/dist/office.js +1092 -0
  122. package/dist/office.js.map +1 -0
  123. package/dist/openai/adapter.d.ts +29 -5
  124. package/dist/openai/adapter.d.ts.map +1 -1
  125. package/dist/openai/adapter.js +325 -37
  126. package/dist/openai/adapter.js.map +1 -1
  127. package/dist/output-limit.d.ts +14 -2
  128. package/dist/output-limit.d.ts.map +1 -1
  129. package/dist/output-limit.js +39 -10
  130. package/dist/output-limit.js.map +1 -1
  131. package/dist/pause.d.ts +24 -0
  132. package/dist/pause.d.ts.map +1 -0
  133. package/dist/pause.js +38 -0
  134. package/dist/pause.js.map +1 -0
  135. package/dist/pdf-pages.d.ts +32 -2
  136. package/dist/pdf-pages.d.ts.map +1 -1
  137. package/dist/pdf-pages.js +277 -20
  138. package/dist/pdf-pages.js.map +1 -1
  139. package/dist/pdf-pictures.d.ts +30 -3
  140. package/dist/pdf-pictures.d.ts.map +1 -1
  141. package/dist/pdf-pictures.js +50 -8
  142. package/dist/pdf-pictures.js.map +1 -1
  143. package/dist/pdf-work.d.ts +40 -0
  144. package/dist/pdf-work.d.ts.map +1 -0
  145. package/dist/pdf-work.js +734 -0
  146. package/dist/pdf-work.js.map +1 -0
  147. package/dist/peers.d.ts +8 -0
  148. package/dist/peers.d.ts.map +1 -0
  149. package/dist/peers.js +32 -0
  150. package/dist/peers.js.map +1 -0
  151. package/dist/plan.d.ts +22 -4
  152. package/dist/plan.d.ts.map +1 -1
  153. package/dist/plan.js +61 -12
  154. package/dist/plan.js.map +1 -1
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +4 -2
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +23 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +33 -3
  161. package/dist/retry.js.map +1 -1
  162. package/dist/search.d.ts +107 -24
  163. package/dist/search.d.ts.map +1 -1
  164. package/dist/search.js +803 -149
  165. package/dist/search.js.map +1 -1
  166. package/dist/sse.d.ts +35 -2
  167. package/dist/sse.d.ts.map +1 -1
  168. package/dist/sse.js +145 -31
  169. package/dist/sse.js.map +1 -1
  170. package/dist/stores.d.ts.map +1 -1
  171. package/dist/stores.js +5 -2
  172. package/dist/stores.js.map +1 -1
  173. package/dist/text-index.d.ts +9 -1
  174. package/dist/text-index.d.ts.map +1 -1
  175. package/dist/text-index.js +28 -9
  176. package/dist/text-index.js.map +1 -1
  177. package/dist/text.d.ts +87 -3
  178. package/dist/text.d.ts.map +1 -1
  179. package/dist/text.js +526 -24
  180. package/dist/text.js.map +1 -1
  181. package/dist/tools.d.ts +61 -1
  182. package/dist/tools.d.ts.map +1 -1
  183. package/dist/tools.js +461 -46
  184. package/dist/tools.js.map +1 -1
  185. package/dist/types.d.ts +103 -4
  186. package/dist/types.d.ts.map +1 -1
  187. package/dist/word-styles.d.ts +102 -0
  188. package/dist/word-styles.d.ts.map +1 -0
  189. package/dist/word-styles.js +419 -0
  190. package/dist/word-styles.js.map +1 -0
  191. package/dist/xlsx.d.ts +23 -0
  192. package/dist/xlsx.d.ts.map +1 -0
  193. package/dist/xlsx.js +511 -0
  194. package/dist/xlsx.js.map +1 -0
  195. package/dist/xml-stream.d.ts +55 -0
  196. package/dist/xml-stream.d.ts.map +1 -0
  197. package/dist/xml-stream.js +235 -0
  198. package/dist/xml-stream.js.map +1 -0
  199. package/dist/zip-directory.d.ts +43 -0
  200. package/dist/zip-directory.d.ts.map +1 -0
  201. package/dist/zip-directory.js +130 -0
  202. package/dist/zip-directory.js.map +1 -0
  203. package/docs/README.md +288 -0
  204. package/docs/api.md +37 -381
  205. package/docs/configuration.md +28 -558
  206. package/docs/getting-started.md +407 -223
  207. package/docs/guides/anthropic.md +590 -0
  208. package/docs/guides/conversations.md +629 -0
  209. package/docs/guides/costs-and-limits.md +728 -0
  210. package/docs/guides/deployment.md +720 -0
  211. package/docs/guides/errors-and-reliability.md +748 -0
  212. package/docs/guides/explorer-model.md +399 -0
  213. package/docs/guides/openai-compatible.md +602 -0
  214. package/docs/guides/own-adapter-and-loop.md +1169 -0
  215. package/docs/guides/pdfs.md +1024 -0
  216. package/docs/guides/storage.md +731 -0
  217. package/docs/guides/testing.md +1203 -0
  218. package/docs/guides/vertex-and-gemini.md +717 -0
  219. package/docs/guides/web-app.md +1590 -0
  220. package/docs/how-it-works.md +1035 -164
  221. package/docs/measurements.md +881 -0
  222. package/docs/publishing.md +274 -46
  223. package/docs/reference/anthropic.md +427 -0
  224. package/docs/reference/ask.md +910 -0
  225. package/docs/reference/errors-and-retries.md +760 -0
  226. package/docs/reference/events.md +1001 -0
  227. package/docs/reference/gemini.md +827 -0
  228. package/docs/reference/library.md +1598 -0
  229. package/docs/reference/node.md +706 -0
  230. package/docs/reference/openai.md +385 -0
  231. package/docs/reference/tools.md +1031 -0
  232. package/docs/security.md +940 -101
  233. package/docs/troubleshooting.md +1410 -0
  234. package/package.json +7 -3
  235. package/src/analyze.ts +204 -49
  236. package/src/anthropic/adapter.ts +200 -40
  237. package/src/ask.ts +1151 -210
  238. package/src/decode.ts +89 -0
  239. package/src/encoding.ts +850 -0
  240. package/src/errors.ts +125 -0
  241. package/src/events.ts +451 -0
  242. package/src/evidence.ts +11 -2
  243. package/src/extract.ts +191 -308
  244. package/src/gemini/adapter.ts +127 -70
  245. package/src/gemini/chat.ts +28 -4
  246. package/src/gemini/endpoints.ts +12 -2
  247. package/src/gemini/errors.ts +34 -1
  248. package/src/gemini/generate.ts +42 -13
  249. package/src/gemini/index.ts +3 -3
  250. package/src/gemini/sse.ts +1 -1
  251. package/src/groups.ts +162 -0
  252. package/src/html.ts +1071 -0
  253. package/src/http.ts +376 -1
  254. package/src/index.ts +29 -6
  255. package/src/library.ts +498 -93
  256. package/src/limiter.ts +6 -1
  257. package/src/map-reduce.ts +252 -51
  258. package/src/model.ts +244 -4
  259. package/src/node/handlers.ts +196 -31
  260. package/src/node/index.ts +4 -0
  261. package/src/node/ingest-child.ts +61 -0
  262. package/src/node/isolated.ts +464 -0
  263. package/src/node/sse.ts +198 -0
  264. package/src/office.ts +1047 -0
  265. package/src/openai/adapter.ts +319 -38
  266. package/src/output-limit.ts +44 -8
  267. package/src/pause.ts +41 -0
  268. package/src/pdf-pages.ts +270 -20
  269. package/src/pdf-pictures.ts +56 -9
  270. package/src/pdf-work.ts +722 -0
  271. package/src/peers.ts +29 -0
  272. package/src/plan.ts +70 -12
  273. package/src/ranged.ts +4 -2
  274. package/src/retry.ts +49 -5
  275. package/src/search.ts +800 -155
  276. package/src/sse.ts +153 -28
  277. package/src/stores.ts +5 -2
  278. package/src/text-index.ts +30 -9
  279. package/src/text.ts +524 -23
  280. package/src/tools.ts +445 -46
  281. package/src/types.ts +108 -5
  282. package/src/word-styles.ts +420 -0
  283. package/src/xlsx.ts +478 -0
  284. package/src/xml-stream.ts +224 -0
  285. package/src/zip-directory.ts +136 -0
package/src/errors.ts CHANGED
@@ -30,6 +30,23 @@ export class DocumentStoreError extends Error {
30
30
  }
31
31
  }
32
32
 
33
+ /**
34
+ * The errors a store threw while `ingest` wrote a document. `ingest` passes them on as they are,
35
+ * and the upload handler tells them apart from a file that could not be read: their message is
36
+ * the store's own (a database driver's names its host), not words for a user.
37
+ */
38
+ const storeWriteFailures = new WeakSet<object>();
39
+
40
+ /** Takes note that a store threw this error while it wrote a document. */
41
+ export function noteStoreWriteFailure(error: unknown): void {
42
+ if (typeof error === "object" && error !== null) storeWriteFailures.add(error);
43
+ }
44
+
45
+ /** Whether a store threw this error while it wrote a document (see `noteStoreWriteFailure`). */
46
+ export function isStoreWriteFailure(error: unknown): boolean {
47
+ return typeof error === "object" && error !== null && storeWriteFailures.has(error);
48
+ }
49
+
33
50
  /**
34
51
  * What to tell a model, or a user, about an error: its message, unless it is a system error, whose
35
52
  * message names a path or a host of the server. Of that one only the code is passed on.
@@ -40,3 +57,111 @@ export function safeErrorMessage(error: unknown): string {
40
57
  if (code && syscall) return `The file could not be read from storage (${code}). Try the call again.`;
41
58
  return error instanceof Error ? error.message : String(error);
42
59
  }
60
+
61
+ /**
62
+ * Why `ingest` refused a file, for an application that tells its users in its own words (another
63
+ * language, its own tone) rather than with the message:
64
+ * - "empty": the file has no bytes.
65
+ * - "too_large": larger than `maxUploadBytes`.
66
+ * - "too_much_text": more text than `maxTextBytes`, or far more than its size can hold.
67
+ * - "too_many_pages": a PDF with more pages than `maxPdfPages`.
68
+ * - "not_text": a binary file of a kind the library does not read.
69
+ * - "compressed": a gzip or ZIP archive to extract first.
70
+ * - "legacy_office": a Word, Excel or PowerPoint file of before 2007 (.doc, .xls, .ppt), or an
71
+ * Office file protected by a password: both are stored the same way, and neither can be read.
72
+ * - "encrypted": a PDF protected by a password.
73
+ * - "no_text": nothing to read: a PDF without a text layer (a scan), a deck without slides, a
74
+ * workbook without sheets, a file of white space.
75
+ * - "hostile": a file built the way files that exhaust a server are: a zip bomb, pages that draw far
76
+ * more than they hold, a structure no program writes.
77
+ * - "timeout": reading it took longer than `ingestTimeoutMs`, or the kill timer of an isolated reader.
78
+ * - "out_of_memory": an isolated reader ran out of the memory it is given (`createIsolatedExtractors`).
79
+ * - "busy": every isolated reader is busy and the queue is full: try again in a moment
80
+ * (`IngestError.retryAfterMs`). The upload handler answers 503 with `Retry-After`.
81
+ * - "missing_dependency": the optional dependency for the format is not installed, could not be
82
+ * loaded, or (`unpdf`) is of a version that cannot read PDFs on this Node.
83
+ * - "unreadable": the file is damaged, or not of the type its name says.
84
+ */
85
+ export type IngestErrorCode =
86
+ | "empty"
87
+ | "too_large"
88
+ | "too_much_text"
89
+ | "too_many_pages"
90
+ | "not_text"
91
+ | "compressed"
92
+ | "legacy_office"
93
+ | "encrypted"
94
+ | "no_text"
95
+ | "hostile"
96
+ | "timeout"
97
+ | "out_of_memory"
98
+ | "busy"
99
+ | "missing_dependency"
100
+ | "unreadable";
101
+
102
+ /**
103
+ * `ingest` could not read a file. The message says why, in words for the person who uploaded it,
104
+ * as it always did; `code` says it for the application. New in 0.8.0: before it, the same refusals
105
+ * were plain `Error`s, with the same messages. The error of an extractor, a parser or an isolated
106
+ * reader is `cause`.
107
+ */
108
+ export class IngestError extends Error {
109
+ readonly code: IngestErrorCode;
110
+ /** For "busy": how long to wait before trying again, in milliseconds. */
111
+ 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". */
113
+ readonly status: number;
114
+
115
+ constructor(code: IngestErrorCode, message: string, options: { cause?: unknown; retryAfterMs?: number } = {}) {
116
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
117
+ this.name = "IngestError";
118
+ this.code = code;
119
+ this.status = code === "busy" ? 503 : code === "too_large" ? 413 : 422;
120
+ if (options.retryAfterMs !== undefined) (this as { retryAfterMs?: number }).retryAfterMs = options.retryAfterMs;
121
+ }
122
+ }
123
+
124
+ /** The refusals of the library, by the words of their messages: the extractors give plain `Error`s. */
125
+ const REFUSALS: Array<[RegExp, IngestErrorCode]> = [
126
+ // First, and to the end of the message: the busy refusal of a file starts with its name, which
127
+ // may hold the words of any other refusal.
128
+ [/^The server is (?:reading other files right now|shutting down)\. Try again in a moment\.$| could not be read now: a reader could not be started(?: \([^()]*\))?\. Try again in a moment\.$/, "busy"],
129
+ [/ is empty\.$/, "empty"],
130
+ [/larger than the .* upload limit/, "too_large"],
131
+ // An unpdf that cannot run on this Node is told as its own message (checkUnpdf in extract.ts).
132
+ [/needs the optional dependency|is installed but could not be loaded|^The unpdf installed (?:cannot read PDF files|would stop the whole server)/, "missing_dependency"],
133
+ [/needed more memory than/, "out_of_memory"],
134
+ [/took too long to read|took longer than/, "timeout"],
135
+ [/may be built to exhaust the server|may be a zip bomb|cannot be checked before it is read|lists the same page more than once|far longer than any Office file writes/, "hostile"],
136
+ [/of text, more than is kept|more text than is (?:kept|read) from one file|million characters of text|draws more than .* of text|unpacks to more than/, "too_much_text"],
137
+ [/ pages, more than the .* read from one file/, "too_many_pages"],
138
+ [/gzip-compressed|is a ZIP archive/, "compressed"],
139
+ [/Word, Excel or PowerPoint file of before 2007|protected by a password and stored/, "legacy_office"],
140
+ [/PasswordException|No password given|Incorrect Password|is protected by a password/i, "encrypted"],
141
+ [/looks binary, not text/, "not_text"],
142
+ [/no text layer|did not contain any text|does not contain any slides|any sheets with cells/, "no_text"],
143
+ ];
144
+
145
+ /**
146
+ * The code of a refusal of the library, from its message; "unreadable" for any other error of
147
+ * reading a file. A "busy" message does not say how long to wait: give the `IngestError` a
148
+ * `retryAfterMs` of your own (the isolated readers use 5,000).
149
+ */
150
+ export function ingestErrorCodeOf(message: string): IngestErrorCode {
151
+ for (const [pattern, code] of REFUSALS) if (pattern.test(message)) return code;
152
+ return "unreadable";
153
+ }
154
+
155
+ /**
156
+ * `error` as an `IngestError`: one already is kept, a plain `Error` gets the code of its message.
157
+ * Anything else is passed on as it is: a value that is not an `Error`, an error with an HTTP status
158
+ * of its own, and a system error, whose message names paths of the server (an extractor of your
159
+ * own that reads a file).
160
+ */
161
+ export function toIngestError(error: unknown): unknown {
162
+ if (error instanceof IngestError || !(error instanceof Error)) return error;
163
+ const { code, syscall } = systemError(error);
164
+ const { status, statusCode } = error as { status?: unknown; statusCode?: unknown };
165
+ if ((code && syscall) || typeof status === "number" || typeof statusCode === "number") return error;
166
+ return new IngestError(ingestErrorCodeOf(error.message), error.message, { cause: error });
167
+ }
package/src/events.ts ADDED
@@ -0,0 +1,451 @@
1
+ // What a question or an ingest does while it runs, as typed data in order. The callbacks of
2
+ // earlier versions (onText, onActivity, onStep) still get the same strings, at the same moments.
3
+ import type { AskResult } from "./ask.js";
4
+ import { DocumentStoreError, IngestError, type IngestErrorCode } from "./errors.js";
5
+ import type { Evidence } from "./evidence.js";
6
+ import { modelFailureReason } from "./map-reduce.js";
7
+ import type { ModelErrorKind, ModelReply, ModelUsage, ToolTurn } from "./model.js";
8
+ import type { DocumentFormat, DocumentMeta, DocumentSummary, ToolResult } from "./types.js";
9
+
10
+ /** What every event carries. */
11
+ export type EventBase = {
12
+ /** 1 for the first event of a run, then one more for each event after it: no gaps, no repeats. */
13
+ seq: number;
14
+ /** The run the event belongs to: the `runId` you gave, or one made for it ("run_…" for a question, "ing_…" for an ingest). */
15
+ runId: string;
16
+ /** When it was emitted, in milliseconds since 1970 (`Date.now()`). */
17
+ time: number;
18
+ };
19
+
20
+ /** A document as an event names it. */
21
+ export type DocumentRef = {
22
+ id: string;
23
+ name: string;
24
+ format: DocumentFormat;
25
+ estimatedTokens: number;
26
+ pages?: number;
27
+ };
28
+
29
+ /** An error as an event carries it: plain data, safe to send to a browser. */
30
+ export type EventError = {
31
+ /**
32
+ * A message your users may see. A model error is told by its kind and status ("The model was
33
+ * busy (HTTP 429)."), never in the provider's own words, which can name projects, hosts or
34
+ * keys: those stay on the error that is thrown, for your logs. A storage error is told by its
35
+ * code only.
36
+ */
37
+ message: string;
38
+ /** For a model error: what kind it is (`errorKindOf`). */
39
+ kind?: ModelErrorKind;
40
+ /** For an HTTP error: its status. 0 when no answer came. */
41
+ status?: number;
42
+ /** The error's class name: "ModelRequestError", "AbortError", "DocumentsNotFoundError"… */
43
+ name?: string;
44
+ /**
45
+ * 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.
47
+ */
48
+ code?: IngestErrorCode;
49
+ };
50
+
51
+ /**
52
+ * Which model a request goes to, and for what:
53
+ * - "tools": the one model of a question without an explorer, in a turn where it may call tools;
54
+ * - "explorer": the explorer model, which only calls tools;
55
+ * - "answer": the model that writes the answer (with or without an explorer);
56
+ * - "reader": a request of a whole-file read (`analyze_whole_document`), made for one tool call.
57
+ */
58
+ export type RequestRole = "tools" | "explorer" | "answer" | "reader";
59
+
60
+ /**
61
+ * Why a request is made:
62
+ * - "turn": a turn of the tool loop;
63
+ * - "nudge": the same turn asked again after an empty or malformed reply;
64
+ * - "closing": the request for the answer after the tools;
65
+ * - "answer_again": the answer asked for again after it came back without text;
66
+ * - "direct": the one request of a question that needs no tools;
67
+ * - "part", "merge", "final": a whole-file read reading one part, combining notes, writing its answer.
68
+ */
69
+ export type RequestPurpose = "turn" | "nudge" | "closing" | "answer_again" | "direct" | "part" | "merge" | "final";
70
+
71
+ /**
72
+ * How a tool call ended:
73
+ * - "ok": it ran and returned a result;
74
+ * - "error": it ran, or was checked, and returned `{ error }` (bad arguments, a document it cannot
75
+ * read, a regex that took too long…), or it was ended because its turn failed (the question was
76
+ * stopped, or a listener threw): then the model was sent nothing;
77
+ * - "refused": it was not run, for a limit of the question (cost, room, reads of a whole file);
78
+ * - "already_shown": it repeated a call whose result is still in the conversation, and was answered
79
+ * with a pointer to it;
80
+ * - "not_run": the turn had more calls than `limits.callsPerTurn`.
81
+ */
82
+ export type ToolOutcome = "ok" | "error" | "refused" | "already_shown" | "not_run";
83
+
84
+ /**
85
+ * Something the run did that is not a request or a tool call:
86
+ * - "searching_instead": documents too large to send whole are searched instead;
87
+ * - "writing_answer": the tools are done and the answer is asked for;
88
+ * - "replanned": the question started again with less in the prompt (a smaller window than thought);
89
+ * - "room_made": the request was too large for the model, was made smaller and sent again;
90
+ * - "nudged": an empty or malformed reply was asked for again;
91
+ * - "results_shortened": older tool results were shortened to make room;
92
+ * - "answer_again": the answer came back without text and was asked for again;
93
+ * - "calls_not_run": a turn had more calls than `limits.callsPerTurn`;
94
+ * - "budget_reached": `limits.inputTokens` or `limits.requests` was reached, so no more tools run;
95
+ * - "no_room": there is no room left in the conversation for another tool result;
96
+ * - "blocked": the provider refused the prompt (`AskResult.blockReason`).
97
+ */
98
+ export type NoticeCode =
99
+ | "searching_instead"
100
+ | "writing_answer"
101
+ | "replanned"
102
+ | "room_made"
103
+ | "nudged"
104
+ | "results_shortened"
105
+ | "answer_again"
106
+ | "calls_not_run"
107
+ | "budget_reached"
108
+ | "no_room"
109
+ | "blocked";
110
+
111
+ /**
112
+ * Where a notice went in the callbacks of earlier versions: "activity" to `onActivity`, "step" to
113
+ * `onStep` (and `AskResult.steps`), "none" to neither (new in 0.7.0).
114
+ */
115
+ export type NoticeDisplay = "activity" | "step" | "none";
116
+
117
+ /**
118
+ * The result of a question as `run.finish` and `run.error` carry it: an `AskResult` without
119
+ * `toolTurns`, which hold the text of the documents the tools returned, and with its plan naming
120
+ * the documents only (`DocumentRef`). With
121
+ * `AskOptions.eventResults: true` they are there too. The result `askWithFiles` returns (and
122
+ * `askStream`'s `result`, and `partialResultOf`) always has them: keep them from there.
123
+ */
124
+ export type EventResult = Omit<AskResult, "toolTurns" | "plan"> & {
125
+ toolTurns?: ToolTurn[];
126
+ /**
127
+ * 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.
130
+ */
131
+ plan: { inline: Array<DocumentRef | DocumentMeta>; searchable: Array<DocumentRef | DocumentMeta> };
132
+ };
133
+
134
+ /** The events of a question (`askWithFiles`, `askStream`), in the order they happen. */
135
+ export type AskEvent =
136
+ /** Always first. */
137
+ | (EventBase & {
138
+ type: "run.start";
139
+ /** The adapter ids: the model that answers, and the explorer when there is one. */
140
+ models: { answer: string; explorer?: string };
141
+ documentIds: string[];
142
+ })
143
+ /**
144
+ * Which documents go into the prompt whole and which are searched. After `run.start`, before any
145
+ * request. Again after a "replanned" notice.
146
+ */
147
+ | (EventBase & { type: "plan"; inline: DocumentRef[]; searchable: DocumentRef[] })
148
+ /** A model request starts. Its retries are `retry` events with the same `requestId`. */
149
+ | (EventBase & {
150
+ type: "request.start";
151
+ /** Unique in the run: "req_1", "req_2"… */
152
+ requestId: string;
153
+ role: RequestRole;
154
+ purpose: RequestPurpose;
155
+ /** The adapter id of the model the request goes to. */
156
+ model: string;
157
+ /** For a request of the chat (not "reader"): its number in the question, from 1, as `AskResult.turns` counts. */
158
+ turn?: number;
159
+ /** For a "reader" request: the tool call of the whole-file read it belongs to. */
160
+ callId?: string;
161
+ /** For a "reader" request: which part ("part 3 of 12"), or which round of combining notes. */
162
+ detail?: string;
163
+ /** For a request of the chat: the library's estimate of its input tokens, before it is sent. */
164
+ estimatedInputTokens?: number;
165
+ })
166
+ /** A model request ended, after any retries. */
167
+ | (EventBase & {
168
+ type: "request.end";
169
+ requestId: string;
170
+ /** From `request.start` to now, retries and their waits included. */
171
+ ms: number;
172
+ outcome: "ok" | "error";
173
+ /** What the provider said this request used (all its HTTP sends, for a "reader" request). */
174
+ usage?: Partial<ModelUsage>;
175
+ /** How the reply ended, in the library's words. */
176
+ finish?: ModelReply["finish"];
177
+ /** How the reply ended, in the provider's words. */
178
+ finishReason?: string;
179
+ /** How many tool calls the reply asked for. */
180
+ toolCalls?: number;
181
+ /** With outcome "error": why. A request that failed may still be followed by others (an overflow made smaller, a part read in halves). */
182
+ error?: EventError;
183
+ })
184
+ /**
185
+ * A model request failed and is sent again after `delayMs`. For a request of the chat, earlier
186
+ * versions told `onActivity` the same in `message`; the retries of a "reader" request (a
187
+ * whole-file read) are told only here.
188
+ */
189
+ | (EventBase & {
190
+ type: "retry";
191
+ requestId: string;
192
+ /** 1 for the first retry. */
193
+ attempt: number;
194
+ delayMs: number;
195
+ error: EventError;
196
+ message: string;
197
+ })
198
+ /** Answer text as it arrives: what `onText` gets. Joined, the deltas of a run are `AskResult.text`. */
199
+ | (EventBase & { type: "text"; requestId: string; delta: string })
200
+ /**
201
+ * A tool call starts to run, or is settled without running (refused, already shown, not run).
202
+ * Calls of one turn run a few at a time, so their starts and ends interleave.
203
+ */
204
+ | (EventBase & {
205
+ type: "tool.start";
206
+ /** Unique in the run: "call_1", "call_2"… The provider's own id, when it sent one, is `providerCallId`. */
207
+ callId: string;
208
+ providerCallId?: string;
209
+ /** The tool's name: "search_document", "read_document"… */
210
+ tool: string;
211
+ /** The arguments as the model sent them. */
212
+ args: Record<string, unknown>;
213
+ /** One line of plain text: "Search app.log (exact) for “timeout”". */
214
+ label: string;
215
+ /** The document the call names, when it names one. */
216
+ documentId?: string;
217
+ /** The turn of the tool loop the call came in, from 1. */
218
+ round: number;
219
+ })
220
+ /** Progress of a tool call that takes long: a whole-file read. Between its `tool.start` and `tool.end`. */
221
+ | (EventBase & {
222
+ type: "tool.progress";
223
+ callId: string;
224
+ /** "map": parts read (its requests have purpose "part"); "reduce": notes combined or the answer written ("merge", "final"). */
225
+ stage: "map" | "reduce";
226
+ done: number;
227
+ total: number;
228
+ /** "Reading app.log: part 3 of 12". */
229
+ message: string;
230
+ })
231
+ /** A tool call ended. Ends come in call order within a turn. */
232
+ | (EventBase & {
233
+ type: "tool.end";
234
+ callId: string;
235
+ outcome: ToolOutcome;
236
+ /** From `tool.start` to now. */
237
+ ms: number;
238
+ /**
239
+ * The finished step, as `onStep` gets it. Absent for "not_run" (one "calls_not_run" notice
240
+ * says it for all of them), and for a call ended because its turn failed (see `outcome`).
241
+ */
242
+ step?: string;
243
+ /** What the call showed the model, as in `AskResult.evidence` (with this `callId`). */
244
+ evidence?: Evidence;
245
+ /** The characters of the JSON result the model was sent. */
246
+ resultCharacters?: number;
247
+ /**
248
+ * When the result the model was sent is an error (outcomes "error", "refused", "not_run"):
249
+ * its message. For a call ended because its turn failed: why, as in `EventError.message`.
250
+ */
251
+ error?: string;
252
+ /** The result itself. Only with `AskOptions.eventResults: true`: it holds document text. */
253
+ result?: ToolResult;
254
+ })
255
+ | (EventBase & { type: "notice"; code: NoticeCode; message: string; display: NoticeDisplay })
256
+ /** Always last when the question returns. Nothing comes after it. */
257
+ | (EventBase & { type: "run.finish"; result: EventResult })
258
+ /**
259
+ * Always last when the question throws (an abort included). Nothing comes after it. `partial` is
260
+ * what `partialResultOf(error)` gives: what the question found before it failed.
261
+ */
262
+ | (EventBase & { type: "run.error"; error: EventError; partial?: EventResult });
263
+
264
+ /** The stages of an ingest that report progress. Not every file goes through each. */
265
+ export type IngestStage = "decode" | "extract" | "check" | "pictures" | "prepare" | "index" | "store";
266
+
267
+ /** The events of an ingest (`IngestInput.onEvent`), in the order they happen. */
268
+ export type IngestEvent =
269
+ /** Always first. `format` is what the name and type say; a text file can still become a log. */
270
+ | (EventBase & { type: "ingest.start"; name: string; format: DocumentFormat; bytes: number })
271
+ /**
272
+ * How far a stage is. `total` is absent when it is not known. Sent at most about every 12 ms, and
273
+ * once more when a stage ends; a stage with no progress to report may send none.
274
+ */
275
+ | (EventBase & {
276
+ type: "ingest.progress";
277
+ stage: IngestStage;
278
+ done: number;
279
+ total?: number;
280
+ unit: "pages" | "parts" | "bytes" | "characters";
281
+ })
282
+ /** Always last when the ingest stores the document. */
283
+ | (EventBase & { type: "ingest.finish"; document: DocumentSummary })
284
+ /** Always last when the ingest throws (a refusal or an abort included). */
285
+ | (EventBase & { type: "ingest.error"; error: EventError });
286
+
287
+ /** Any event of this library. */
288
+ export type LibraryEvent = AskEvent | IngestEvent;
289
+
290
+ /** An event without the fields the emitter stamps on it. */
291
+ export type UnstampedEvent<E> = E extends unknown ? Omit<E, keyof EventBase> : never;
292
+
293
+ const TERMINAL = new Set(["run.finish", "run.error", "ingest.finish", "ingest.error"]);
294
+
295
+ /** A run id: the prefix, "_" and 16 hex digits ("run_3f9a…"). */
296
+ export function newRunId(prefix = "run"): string {
297
+ const random = globalThis.crypto?.randomUUID?.().replace(/-/g, "").slice(0, 16)
298
+ ?? Array.from({ length: 16 }, () => Math.floor(Math.random() * 16).toString(16)).join("");
299
+ return `${prefix}_${random}`;
300
+ }
301
+
302
+ /** An error as plain event data. */
303
+ export function eventErrorOf(error: unknown, message?: string): EventError {
304
+ // It never throws: an error whose fields throw when read (a getter, a proxy) is told plainly.
305
+ 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 } : {}) };
310
+ }
311
+ const out: EventError = { message: message ?? userMessageOf(error) };
312
+ if (typeof record.kind === "string") out.kind = record.kind as ModelErrorKind;
313
+ if (typeof record.status === "number") out.status = record.status;
314
+ if (typeof record.name === "string" && record.name) out.name = record.name;
315
+ return out;
316
+ } catch {
317
+ return { message: message ?? SOMETHING_WENT_WRONG };
318
+ }
319
+ }
320
+
321
+ const SOMETHING_WENT_WRONG = "Something went wrong.";
322
+
323
+ /**
324
+ * A message for users: a model error by its kind and status, a storage error by its code, the
325
+ * library's own errors (refusals, a stop) as they are written, and anything that is not an
326
+ * `Error` as "Something went wrong."
327
+ */
328
+ function userMessageOf(error: unknown): string {
329
+ if (error instanceof DocumentStoreError) return error.message;
330
+ if (typeof error !== "object" || error === null) return SOMETHING_WENT_WRONG;
331
+ 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}).`;
336
+ if (!(error instanceof Error) && !(typeof DOMException !== "undefined" && error instanceof DOMException)) return SOMETHING_WENT_WRONG;
337
+ return typeof record.message === "string" && record.message ? record.message : SOMETHING_WENT_WRONG;
338
+ }
339
+
340
+ /**
341
+ * Stamps events with `seq`, `runId` and `time`, and hands them to one listener. After a terminal
342
+ * event (`run.finish`, `run.error`, `ingest.finish`, `ingest.error`) it drops everything: work
343
+ * that goes on after a question stopped (a part read still running) is never reported.
344
+ */
345
+ export class EventEmitter<E extends { type: string }> {
346
+ private seq = 0;
347
+ private closed = false;
348
+
349
+ constructor(
350
+ readonly runId: string,
351
+ private readonly listener: ((event: E) => void) | undefined,
352
+ ) {}
353
+
354
+ /** False when nobody listens or the run has ended: callers may skip building an event. */
355
+ get active(): boolean {
356
+ return this.listener !== undefined && !this.closed;
357
+ }
358
+
359
+ /** True once a terminal event was emitted. */
360
+ get ended(): boolean {
361
+ return this.closed;
362
+ }
363
+
364
+ emit(event: UnstampedEvent<E>): void {
365
+ if (this.closed) return;
366
+ if (TERMINAL.has(event.type)) this.closed = true;
367
+ if (!this.listener) return;
368
+ this.listener({ ...event, seq: ++this.seq, runId: this.runId, time: Date.now() } as unknown as E);
369
+ }
370
+ }
371
+
372
+ /** The events of a run as an async iterable, and how the run ended. */
373
+ export type EventStream<E, T> = AsyncIterable<E> & {
374
+ /** What the run returned. Rejects with its error; awaiting it is optional (it never goes unhandled). */
375
+ result: Promise<T>;
376
+ /** Stops the run: its signal aborts, and the stream ends after the run's last event. */
377
+ abort(reason?: unknown): void;
378
+ };
379
+
380
+ /**
381
+ * Runs `run` at once and gives its events as an async iterable. Events wait in memory until they
382
+ * are read. Leaving the loop early (`break`, `return`, a throw) aborts the run. The iterable ends
383
+ * after the run's last event; it does not throw when the run fails: read the `run.error` event, or
384
+ * await `result`. It can be iterated once.
385
+ */
386
+ export function eventStream<E, T>(
387
+ run: (onEvent: (event: E) => void, signal: AbortSignal) => Promise<T>,
388
+ options: { signal?: AbortSignal | undefined } = {},
389
+ ): EventStream<E, T> {
390
+ const controller = new AbortController();
391
+ const outer = options.signal;
392
+ const onOuterAbort = () => controller.abort(outer?.reason);
393
+ if (outer?.aborted) controller.abort(outer.reason);
394
+ else outer?.addEventListener("abort", onOuterAbort, { once: true });
395
+
396
+ const queue: E[] = [];
397
+ // Calls of next() waiting for an event, oldest first: each gets the next event in turn.
398
+ const waiters: Array<(result: IteratorResult<E>) => void> = [];
399
+ let finished = false;
400
+ // Set by return(): the reader left, so nothing more is queued or handed out.
401
+ let closed = false;
402
+ const settleWaiters = () => {
403
+ for (const resolve of waiters.splice(0)) resolve({ value: undefined, done: true });
404
+ };
405
+ const onEvent = (event: E) => {
406
+ if (closed) return;
407
+ const waiter = waiters.shift();
408
+ if (waiter) waiter({ value: event, done: false });
409
+ else queue.push(event);
410
+ };
411
+
412
+ let started: Promise<T>;
413
+ try {
414
+ started = run(onEvent, controller.signal);
415
+ } catch (error) {
416
+ started = Promise.reject(error);
417
+ }
418
+ const result = started.finally(() => {
419
+ finished = true;
420
+ outer?.removeEventListener("abort", onOuterAbort);
421
+ // Every event came before the run settled: whoever still waits gets the end.
422
+ settleWaiters();
423
+ });
424
+ result.catch(() => undefined);
425
+
426
+ let iterated = false;
427
+ return {
428
+ result,
429
+ abort(reason?: unknown) {
430
+ controller.abort(reason ?? new DOMException("The run was stopped.", "AbortError"));
431
+ },
432
+ [Symbol.asyncIterator](): AsyncIterator<E> {
433
+ if (iterated) throw new TypeError("These events can be read once.");
434
+ iterated = true;
435
+ return {
436
+ next(): Promise<IteratorResult<E>> {
437
+ if (queue.length > 0) return Promise.resolve({ value: queue.shift()!, done: false });
438
+ if (finished || closed) return Promise.resolve({ value: undefined, done: true });
439
+ return new Promise((resolve) => waiters.push(resolve));
440
+ },
441
+ async return(): Promise<IteratorResult<E>> {
442
+ if (!finished && !closed) controller.abort(new DOMException("The events stopped being read.", "AbortError"));
443
+ closed = true;
444
+ queue.length = 0;
445
+ settleWaiters();
446
+ return { value: undefined, done: true };
447
+ },
448
+ };
449
+ },
450
+ };
451
+ }
package/src/evidence.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // What the tools showed a model, as data: the trail an application can keep with an answer, and
2
2
  // the short stand-in a tool result leaves behind when the request runs out of room.
3
3
  import type { ToolCall } from "./model.js";
4
+ import { sliceWhole } from "./text.js";
4
5
  import { TOOL_NAMES } from "./tools.js";
5
6
  import type { ToolResult } from "./types.js";
6
7
 
@@ -26,6 +27,8 @@ export type Evidence = {
26
27
  totalMatchingLines?: number;
27
28
  /** True for a whole-file read: other model calls read every line, and the model saw their answer. */
28
29
  whole?: boolean;
30
+ /** The tool call it came from, as its events name it ("call_3"). Set by `askWithFiles`. New in 0.7.0. */
31
+ callId?: string;
29
32
  };
30
33
 
31
34
  /** "12-14", "12" or 12 as a range. */
@@ -105,6 +108,8 @@ const SMALL_RESULT_CHARACTERS = 700;
105
108
  /** What is kept of the answer of a whole-file read, which cannot be asked for again. */
106
109
  const KEPT_ANSWER_CHARACTERS = 6_000;
107
110
  const MOST_RANGES = 60;
111
+ /** The groups kept of a search with `group_by`, the largest (or, by time, the first) ones. */
112
+ const KEPT_GROUPS = 30;
108
113
 
109
114
  const rangeText = ([from, to]: NumberRange) => (to > from ? `${from}-${to}` : String(from));
110
115
 
@@ -133,9 +138,13 @@ export function stubResult(call: ToolCall, result: ToolResult, hadFiles = false)
133
138
  return {
134
139
  ...base,
135
140
  ...(typeof result.mode === "string" ? { mode: result.mode } : {}),
136
- ...(typeof call.args.query === "string" ? { query: call.args.query.slice(0, 200) } : {}),
141
+ ...(typeof call.args.query === "string" ? { query: sliceWhole(call.args.query, 200) } : {}),
137
142
  ...(typeof result.total_matching_lines === "number" ? { total_matching_lines: result.total_matching_lines } : {}),
138
143
  ...(lines && lines.length > 0 ? { lines_shown: lines } : {}),
144
+ // Counts by group show no lines to read again: the largest groups are kept as they are.
145
+ ...(typeof result.group_by === "string" ? { group_by: result.group_by } : {}),
146
+ ...(typeof result.total_groups === "number" ? { total_groups: result.total_groups } : {}),
147
+ ...(Array.isArray(result.groups) ? { groups: result.groups.slice(0, KEPT_GROUPS) } : {}),
139
148
  note: "The results of this search were shown to you earlier and were dropped from the conversation to make room. Read the lines listed here with read_document, or search again, if you need them.",
140
149
  };
141
150
  case TOOL_NAMES.analyze: {
@@ -143,7 +152,7 @@ export function stubResult(call: ToolCall, result: ToolResult, hadFiles = false)
143
152
  return {
144
153
  ...base,
145
154
  ...(typeof result.parts_read === "number" ? { parts_read: result.parts_read } : {}),
146
- answer: answer.length > KEPT_ANSWER_CHARACTERS ? `${answer.slice(0, KEPT_ANSWER_CHARACTERS)}…` : answer,
155
+ answer: answer.length > KEPT_ANSWER_CHARACTERS ? `${sliceWhole(answer, KEPT_ANSWER_CHARACTERS)}…` : answer,
147
156
  note: "This is the start of the answer of the whole-file read. The rest was dropped from the conversation to make room.",
148
157
  };
149
158
  }