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/peers.ts ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Loads an optional dependency. When it is not installed, the error says so in `missing`, words for
3
+ * a user ("Reading PDF files needs the optional dependency \"unpdf\"."). When it is installed but
4
+ * fails to load (a version this Node cannot run, a broken install), the error says that, with the
5
+ * reason, and keeps the failure as its cause: it was reported as missing before 0.8.0.
6
+ */
7
+ export async function importPeer<T>(name: string, load: () => Promise<T>, missing: string): Promise<T> {
8
+ try {
9
+ return await load();
10
+ } catch (error) {
11
+ if (notFound(error, name)) throw new Error(missing, { cause: error });
12
+ const reason = error instanceof Error ? error.message : String(error);
13
+ throw new Error(`The optional dependency "${name}" is installed but could not be loaded (${reason.split("\n")[0]}). Reinstall it, or install a version this Node can run.`, { cause: error });
14
+ }
15
+ }
16
+
17
+ /**
18
+ * Whether an import failed because the package is not installed: Node's code, or the words of Node
19
+ * and of bundlers that give none, about this package and not one it needs. A loader that wraps the
20
+ * failure (a test runner's mock) keeps it as a cause, looked at too.
21
+ */
22
+ function notFound(error: unknown, name: string): boolean {
23
+ for (let current = error, depth = 0; current && depth < 4; current = (current as { cause?: unknown }).cause, depth++) {
24
+ const { code, message } = current as { code?: unknown; message?: unknown };
25
+ if (typeof message === "string" && message.includes(name)
26
+ && (code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND" || /Cannot find (?:package|module)/.test(message))) return true;
27
+ }
28
+ return false;
29
+ }
package/src/plan.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { plural, sliceWhole, wellFormed } from "./text.js";
1
2
  import type { Budget, DocumentMeta, DocumentPlan, OutlineEntry } from "./types.js";
2
3
 
3
4
  /** Bytes kept free for document cards, the tool declarations, and JSON framing. */
@@ -84,28 +85,80 @@ export function outlineLines(outline: OutlineEntry[]): string[] {
84
85
  return outline.map((entry) => `L${entry.line} ${" ".repeat(entry.level - top)}${entry.title}`);
85
86
  }
86
87
 
88
+ /**
89
+ * What the model is told of a text file that was not valid UTF-8, or nothing: in which encoding
90
+ * it was read, so that it can say so when letters look wrong, or why it shows U+FFFD.
91
+ */
92
+ function readingNote(meta: DocumentMeta, short: boolean): string | undefined {
93
+ const count = meta.replacedCharacters ?? 0;
94
+ const characters = `${count.toLocaleString("en-US")} ${count === 1 ? "character" : "characters"}`;
95
+ const were = count === 1 ? "was" : "were";
96
+ const show = count === 1 ? "shows" : "show";
97
+ if (meta.encoding) {
98
+ if (short) return `read as ${meta.encoding}${count ? `, ${characters} not valid in it, shown as �` : ""}`;
99
+ const read = `This file is not in UTF-8. Its text was read as ${meta.encoding}: if its letters look wrong, ask the user to save it as UTF-8.`;
100
+ // Bytes further on that the encoding does not have.
101
+ return count ? `${read} ${characters} of it ${were} not valid in ${meta.encoding}, and ${show} as �.` : read;
102
+ }
103
+ if (!count) return undefined;
104
+ return short ? `${characters} not valid UTF-8, shown as �` : `${characters} of this file ${were} not valid UTF-8, and ${show} as �.`;
105
+ }
106
+
107
+ /**
108
+ * Eight hex digits made from a document ID. The ID is made at random when the file is stored, so
109
+ * the file's own text cannot know them, and they are the same in every request: a provider's
110
+ * prompt cache still reuses the file.
111
+ */
112
+ export function frameMark(id: string): string {
113
+ // FNV-1a, 32 bits.
114
+ let hash = 0x811c9dc5;
115
+ for (let index = 0; index < id.length; index++) hash = Math.imul(hash ^ id.charCodeAt(index), 0x01000193);
116
+ return (hash >>> 0).toString(16).padStart(8, "0");
117
+ }
118
+
119
+ /**
120
+ * A file sent whole, between two frame lines. Both carry a mark the file's text cannot hold, and
121
+ * the first one says that only the line with the mark ends the file: a line of the file such as
122
+ * "--- End attached file: report.txt ---", in whatever letters, cannot end it early and start a
123
+ * fake one. The uploader chooses the name with the text, so the mark comes before the name, the
124
+ * name is quoted, and the last line holds the mark alone: a name cannot name a mark of its own.
125
+ */
87
126
  export function renderInline(meta: DocumentMeta, text: string): string {
88
- return `--- Attached file: ${meta.name} (${meta.format}, ${meta.lines.toLocaleString("en-US")} lines) ---\n${text}\n--- End attached file: ${meta.name} ---`;
127
+ const mark = frameMark(meta.id);
128
+ const note = readingNote(meta, true);
129
+ return `--- Attached file [mark ${mark}]: ${JSON.stringify(meta.name)} (${meta.format}, ${meta.lines.toLocaleString("en-US")} ${plural(meta.lines, "line")}${note ? `, ${note}` : ""}; it ends only at the line with mark ${mark}) ---\n${text}\n--- End attached file [mark ${mark}] ---`;
89
130
  }
90
131
 
91
132
  /** How many lines of a file its card shows. */
92
133
  export const CARD_LINES = CARD_HEAD_LINES;
93
134
 
135
+ /**
136
+ * What a card says of a whole-document read: that it can have one ("offered"), that the file is
137
+ * too large for one ("too_large"), or nothing, when the tools have none ("not_offered").
138
+ */
139
+ export type WholeRead = "offered" | "too_large" | "not_offered";
140
+
141
+ /** The line of a card that says how to read the file. */
142
+ const HOW_TO_READ: Record<WholeRead, string> = {
143
+ offered: "This file is NOT in your context. Use the document tools to search it, read line ranges, or analyze all of it.",
144
+ too_large: "This file is NOT in your context. Use the document tools to search it and to read line ranges. It is too large to be analyzed whole.",
145
+ not_offered: "This file is NOT in your context. Use the document tools to search it and to read line ranges.",
146
+ };
147
+
94
148
  /**
95
149
  * A compact stand-in for a document that is too large for the prompt. `head` is its first
96
150
  * `CARD_LINES` lines, numbered. `viewable` adds a line saying that its pages can be looked at
97
- * with `view_pages`. `readableWhole` is false for a file that a whole-document read would refuse:
98
- * the card then does not offer one.
151
+ * with `view_pages`. `wholeRead` says whether the card offers a whole-document read.
99
152
  */
100
- export function renderCard(meta: DocumentMeta, head: string, viewable = false, readableWhole = true): string {
153
+ export function renderCard(meta: DocumentMeta, head: string, viewable = false, wholeRead: WholeRead = "offered"): string {
154
+ const note = readingNote(meta, false);
101
155
  const out = [
102
156
  `--- Large attached file: ${meta.name} ---`,
103
157
  `document_id: ${meta.id}`,
104
- `${meta.format} · ${formatBytes(meta.bytes)} · ${meta.lines.toLocaleString("en-US")} lines${meta.pages ? ` · ${meta.pages} pages` : ""} · about ${formatCount(meta.estimatedTokens)} tokens`,
105
- readableWhole
106
- ? "This file is NOT in your context. Use the document tools to search it, read line ranges, or analyze all of it."
107
- : "This file is NOT in your context. Use the document tools to search it and to read line ranges. It is too large to be analyzed whole.",
158
+ `${meta.format} · ${formatBytes(meta.bytes)} · ${meta.lines.toLocaleString("en-US")} ${plural(meta.lines, "line")}${meta.pages ? ` · ${meta.pages} ${plural(meta.pages, "page")}` : ""} · about ${formatCount(meta.estimatedTokens)} tokens`,
159
+ HOW_TO_READ[wholeRead],
108
160
  ...(viewable ? ["Its text cannot show pictures. To see a picture, a chart or the layout of a page, look at the page with view_pages."] : []),
161
+ ...(note ? [note] : []),
109
162
  ];
110
163
  const profile = meta.logProfile;
111
164
  if (profile) {
@@ -114,14 +167,15 @@ export function renderCard(meta: DocumentMeta, head: string, viewable = false, r
114
167
  if (profile.firstTimestamp) out.push(`Time range: ${profile.firstTimestamp} → ${profile.lastTimestamp ?? profile.firstTimestamp}`);
115
168
  if (profile.topIssues.length) {
116
169
  out.push("Most frequent problems (count, first line):");
117
- for (const issue of profile.topIssues.slice(0, 8)) out.push(` [${issue.level} ×${issue.count}, L${issue.firstLine}] ${issue.template}`);
170
+ // 0.5.0 stored some templates cut inside an emoji: half of a character is not sent.
171
+ for (const issue of profile.topIssues.slice(0, 8)) out.push(` [${issue.level} ×${issue.count}, L${issue.firstLine}] ${wellFormed(issue.template)}`);
118
172
  }
119
173
  }
120
174
  if (meta.outline.length) {
121
175
  out.push(`Outline (${Math.min(meta.outline.length, CARD_OUTLINE_ENTRIES)} of ${meta.outline.length} headings):`);
122
176
  out.push(...outlineLines(meta.outline.slice(0, CARD_OUTLINE_ENTRIES)).map((line) => ` ${line}`));
123
177
  }
124
- out.push(`First lines:`, head.split("\n").map((line) => ` ${line.slice(0, 300)}`).join("\n"));
178
+ out.push(`First lines:`, head.split("\n").map((line) => ` ${sliceWhole(line, 300)}`).join("\n"));
125
179
  out.push(`--- End large attached file: ${meta.name} ---`);
126
180
  return out.join("\n");
127
181
  }
@@ -130,7 +184,8 @@ export function renderCard(meta: DocumentMeta, head: string, viewable = false, r
130
184
  * The tool guide for the system prompt. `searchable` are the files the model reads through the
131
185
  * text tools. `viewable` are the PDFs whose pages it can look at with `view_pages`: some of them
132
186
  * may be searchable, and some may have their whole text in the prompt. `wholeReads` is false when
133
- * every searchable file is too large for `analyze_whole_document`: the guide then leaves it out.
187
+ * the tools have no `analyze_whole_document`, or every searchable file is too large for it: the
188
+ * guide then leaves it out.
134
189
  */
135
190
  export function documentToolsInstruction(searchable: DocumentMeta[], viewable: DocumentMeta[] = [], wholeReads = true): string {
136
191
  // File names come from uploads. Quoting keeps a name that reads like an instruction a name.
@@ -141,9 +196,12 @@ export function documentToolsInstruction(searchable: DocumentMeta[], viewable: D
141
196
  `Some attached files are too large for your context: ${searchable.map((meta) => named(meta)).join("; ")}.`,
142
197
  "You see only a summary card for each. Read them through the tools:",
143
198
  "- search_document finds lines (exact or regex) or the most relevant passages (keywords).",
199
+ "- To count or list what can be matched as text (a word, an ID, an error code, a log level, a pattern), use search_document in exact or regex mode: its total_matching_lines is exact.",
200
+ "- To count per group (per hour or day, per error code or ID with a regex group, per message shape), pass group_by: one call gives every count. For more matches than a result shows, search again from its next_from_line, or with order \"last\" for the last ones.",
201
+ "- Search for the bare form of a word: a search matches inside longer words, so \"timeout\" also finds \"timeouts\", and a Hebrew word without its prefix letters (חוזה, not בחוזה) finds every form of it.",
144
202
  "- read_document reads a line range. Read around search hits before you rely on them.",
145
203
  "- get_document_overview returns the outline, log profile, and the start and end of a file.",
146
- ...(wholeReads ? ["- analyze_whole_document reads the entire file in parts. Use it only when the task needs all of it (a full summary, every occurrence, a timeline). It is slow and costly."] : []),
204
+ ...(wholeReads ? ["- analyze_whole_document reads the entire file in parts. Use it only when the task needs all of the file and cannot be done by matching text: a full summary, a timeline, or items that must be judged by meaning. It is slow and costly, and it can miss items of a long list."] : []),
147
205
  "You have a limited number of tool turns. Call several tools in the same turn when the searches do not depend on each other, and answer as soon as you have enough evidence.",
148
206
  "Base your answer on text you actually read. Cite line numbers like (app.log L1203). If the tools did not find something, say so rather than guessing.",
149
207
  );
package/src/ranged.ts CHANGED
@@ -44,7 +44,9 @@ export const pieceKey = (id: string, at: number) => `${id}#${at}`;
44
44
  const BUILD_READ_BYTES = 4 * 1024 * 1024;
45
45
  /** A pass shared by several scans lets other work run after this much time on the main thread. */
46
46
  const YIELD_AFTER_MS = 15;
47
- const decoder = new TextDecoder("utf-8");
47
+ // `ignoreBOM`: every decode is a stream of its own, and would drop a U+FEFF that starts it. A range
48
+ // starts at a line, so a line that began with one lost it, and its piece no longer matched the index.
49
+ const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
48
50
 
49
51
  const gone = (id: string) => new Error(`${id} is no longer available on the server. Ask the user to attach the file again.`);
50
52
 
@@ -347,7 +349,7 @@ export async function openRangedDocument(
347
349
  if (!index) return undefined;
348
350
  // An index that disagrees with the metadata describes a text that is not what was ingested.
349
351
  // It is used, since it is what the store holds, but not saved.
350
- if (store.putIndex && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters) {
352
+ if (store.putIndex && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters && (meta.textBytes === undefined || index.textBytes === meta.textBytes)) {
351
353
  await store.putIndex(meta.id, serializeTextIndex(index)).catch(() => undefined);
352
354
  }
353
355
  }
package/src/retry.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  // One rule for sending a model request again, used by the chat loop and by whole-file part reads.
2
2
 
3
- /** How a model request that failed is sent again. */
3
+ /**
4
+ * How a model request that failed is sent again. A field that is not a finite number (NaN,
5
+ * Infinity) counts as not set: its default applies.
6
+ */
4
7
  export type RetryOptions = {
5
8
  /** How many times a failed request is sent again. Defaults to 3. 0 turns it off. */
6
9
  retries?: number;
@@ -80,13 +83,45 @@ export function retryAfterMs(headers: Headers | undefined, body?: unknown, now:
80
83
  return undefined;
81
84
  }
82
85
 
83
- export type RetryNotice = { error: unknown; attempt: number; delayMs: number };
86
+ /** Errors whose provider said not to send the request again: see `noteNoRetry`. */
87
+ const notToRetry = new WeakSet<object>();
88
+
89
+ /**
90
+ * Takes note that the provider said not to send this request again (Claude's
91
+ * `x-should-retry: false`): `withRetry` does not, whatever its status.
92
+ */
93
+ export function noteNoRetry(error: object): void {
94
+ notToRetry.add(error);
95
+ }
96
+
97
+ /** A value of the options, or its default when the value is not a finite number. */
98
+ const finiteOr = (value: number | undefined, fallback: number): number => (typeof value === "number" && Number.isFinite(value) ? value : fallback);
99
+
100
+ /** What `withRetry` tells `onRetry` before it sends a request again. */
101
+ export type RetryNotice = {
102
+ /** The error of the attempt that failed. */
103
+ error: unknown;
104
+ /**
105
+ * The number of the retry to come, 1 for the first. It counts every retry made so far, the one
106
+ * of an error without a status (`unknownErrors: "once"`, which is not told) included.
107
+ */
108
+ attempt: number;
109
+ /** How long it waits, in milliseconds, before it sends the request again. */
110
+ delayMs: number;
111
+ };
84
112
 
85
113
  /**
86
114
  * Runs a model request, and runs it again when it failed in a way that another try can mend.
87
115
  * - An error with a retryable status (see `isRetryableStatus`) is retried after a wait that doubles
88
116
  * each time, with jitter, or after the wait the provider asked for.
89
117
  * - An error with another status is not retried.
118
+ * - An error of kind "quota" (a daily cap, no credit left) is not retried: a wait does not mend it.
119
+ * Nor is one of kind "context_overflow", whatever its status: only a smaller request can pass
120
+ * (OpenAI's request larger than a minute's allowance of tokens comes as HTTP 429). Nor is one
121
+ * whose provider said not to try again (Claude's `x-should-retry: false`).
122
+ * - An error of kind "timeout" with status 0 (nothing came from the model for the adapter's whole
123
+ * wait) is retried once: another such wait is long, and a model that went silent twice will most
124
+ * likely do so again. A timeout the provider reports (HTTP 408) is retried like any other.
90
125
  * - An error without a status is retried once, at once, when `unknownErrors` is "once"; otherwise not.
91
126
  * Nothing is retried after the signal aborted, or once `canRetry` says no.
92
127
  */
@@ -98,17 +133,26 @@ export async function withRetry<T>(run: () => Promise<T>, options: {
98
133
  onRetry?: (notice: RetryNotice) => void;
99
134
  unknownErrors?: "once" | "never";
100
135
  } = {}): Promise<T> {
101
- const retries = Math.max(0, Math.trunc(options.retry?.retries ?? DEFAULT_RETRIES));
102
- const base = Math.max(0, options.retry?.baseDelayMs ?? DEFAULT_BASE_DELAY_MS);
103
- const longest = Math.max(0, options.retry?.maxDelayMs ?? DEFAULT_MAX_DELAY_MS);
136
+ // NaN would never compare true (`attempt >= NaN`), and a request would be sent again without end.
137
+ const retries = Math.max(0, Math.trunc(finiteOr(options.retry?.retries, DEFAULT_RETRIES)));
138
+ const base = Math.max(0, finiteOr(options.retry?.baseDelayMs, DEFAULT_BASE_DELAY_MS));
139
+ const longest = Math.max(0, finiteOr(options.retry?.maxDelayMs, DEFAULT_MAX_DELAY_MS));
104
140
  const wait = options.retry?.sleep ?? sleep;
105
141
  const random = options.retry?.random ?? Math.random;
106
142
  let unknownRetried = false;
143
+ let timeoutRetried = false;
107
144
  for (let attempt = 0; ; attempt++) {
108
145
  try {
109
146
  return await run();
110
147
  } catch (error) {
111
148
  if (options.signal?.aborted || options.canRetry?.() === false) throw error;
149
+ const kind = (error as { kind?: unknown } | null)?.kind;
150
+ if (kind === "quota" || kind === "context_overflow") throw error;
151
+ if (typeof error === "object" && error !== null && notToRetry.has(error)) throw error;
152
+ if (kind === "timeout" && statusOf(error) === 0) {
153
+ if (timeoutRetried || retries === 0) throw error;
154
+ timeoutRetried = true;
155
+ }
112
156
  const status = statusOf(error);
113
157
  if (status === undefined) {
114
158
  if (options.unknownErrors !== "once" || unknownRetried || retries === 0) throw error;