llm-large-files 0.5.0 → 0.7.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 (221) hide show
  1. package/CHANGELOG.md +1402 -467
  2. package/README.md +188 -60
  3. package/dist/analyze.d.ts +5 -0
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +96 -47
  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 +190 -39
  10. package/dist/anthropic/adapter.js.map +1 -1
  11. package/dist/ask.d.ts +60 -4
  12. package/dist/ask.d.ts.map +1 -1
  13. package/dist/ask.js +1068 -206
  14. package/dist/ask.js.map +1 -1
  15. package/dist/encoding.d.ts +17 -0
  16. package/dist/encoding.d.ts.map +1 -0
  17. package/dist/encoding.js +852 -0
  18. package/dist/encoding.js.map +1 -0
  19. package/dist/errors.d.ts +4 -0
  20. package/dist/errors.d.ts.map +1 -1
  21. package/dist/errors.js +15 -0
  22. package/dist/errors.js.map +1 -1
  23. package/dist/events.d.ts +333 -0
  24. package/dist/events.d.ts.map +1 -0
  25. package/dist/events.js +159 -0
  26. package/dist/events.js.map +1 -0
  27. package/dist/evidence.d.ts +2 -0
  28. package/dist/evidence.d.ts.map +1 -1
  29. package/dist/evidence.js +3 -2
  30. package/dist/evidence.js.map +1 -1
  31. package/dist/extract.d.ts +35 -3
  32. package/dist/extract.d.ts.map +1 -1
  33. package/dist/extract.js +626 -58
  34. package/dist/extract.js.map +1 -1
  35. package/dist/gemini/adapter.d.ts +17 -8
  36. package/dist/gemini/adapter.d.ts.map +1 -1
  37. package/dist/gemini/adapter.js +108 -61
  38. package/dist/gemini/adapter.js.map +1 -1
  39. package/dist/gemini/chat.d.ts +23 -3
  40. package/dist/gemini/chat.d.ts.map +1 -1
  41. package/dist/gemini/chat.js +6 -2
  42. package/dist/gemini/chat.js.map +1 -1
  43. package/dist/gemini/errors.d.ts +9 -4
  44. package/dist/gemini/errors.d.ts.map +1 -1
  45. package/dist/gemini/errors.js +32 -0
  46. package/dist/gemini/errors.js.map +1 -1
  47. package/dist/gemini/generate.d.ts +10 -2
  48. package/dist/gemini/generate.d.ts.map +1 -1
  49. package/dist/gemini/generate.js +13 -7
  50. package/dist/gemini/generate.js.map +1 -1
  51. package/dist/gemini/index.d.ts +3 -3
  52. package/dist/gemini/index.d.ts.map +1 -1
  53. package/dist/gemini/index.js +2 -2
  54. package/dist/gemini/index.js.map +1 -1
  55. package/dist/gemini/sse.d.ts +1 -1
  56. package/dist/gemini/sse.d.ts.map +1 -1
  57. package/dist/gemini/sse.js +1 -1
  58. package/dist/gemini/sse.js.map +1 -1
  59. package/dist/http.d.ts +116 -0
  60. package/dist/http.d.ts.map +1 -1
  61. package/dist/http.js +347 -1
  62. package/dist/http.js.map +1 -1
  63. package/dist/index.d.ts +11 -6
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +6 -4
  66. package/dist/index.js.map +1 -1
  67. package/dist/library.d.ts +67 -5
  68. package/dist/library.d.ts.map +1 -1
  69. package/dist/library.js +405 -85
  70. package/dist/library.js.map +1 -1
  71. package/dist/map-reduce.d.ts +28 -1
  72. package/dist/map-reduce.d.ts.map +1 -1
  73. package/dist/map-reduce.js +240 -52
  74. package/dist/map-reduce.js.map +1 -1
  75. package/dist/model.d.ts +84 -2
  76. package/dist/model.d.ts.map +1 -1
  77. package/dist/model.js +182 -1
  78. package/dist/model.js.map +1 -1
  79. package/dist/node/handlers.d.ts +20 -4
  80. package/dist/node/handlers.d.ts.map +1 -1
  81. package/dist/node/handlers.js +122 -20
  82. package/dist/node/handlers.js.map +1 -1
  83. package/dist/node/index.d.ts +2 -0
  84. package/dist/node/index.d.ts.map +1 -1
  85. package/dist/node/index.js +1 -0
  86. package/dist/node/index.js.map +1 -1
  87. package/dist/node/sse.d.ts +59 -0
  88. package/dist/node/sse.d.ts.map +1 -0
  89. package/dist/node/sse.js +174 -0
  90. package/dist/node/sse.js.map +1 -0
  91. package/dist/openai/adapter.d.ts +29 -5
  92. package/dist/openai/adapter.d.ts.map +1 -1
  93. package/dist/openai/adapter.js +311 -37
  94. package/dist/openai/adapter.js.map +1 -1
  95. package/dist/output-limit.d.ts +14 -2
  96. package/dist/output-limit.d.ts.map +1 -1
  97. package/dist/output-limit.js +39 -10
  98. package/dist/output-limit.js.map +1 -1
  99. package/dist/pause.d.ts +24 -0
  100. package/dist/pause.d.ts.map +1 -0
  101. package/dist/pause.js +38 -0
  102. package/dist/pause.js.map +1 -0
  103. package/dist/pdf-pages.d.ts +32 -2
  104. package/dist/pdf-pages.d.ts.map +1 -1
  105. package/dist/pdf-pages.js +275 -14
  106. package/dist/pdf-pages.js.map +1 -1
  107. package/dist/pdf-pictures.d.ts +30 -3
  108. package/dist/pdf-pictures.d.ts.map +1 -1
  109. package/dist/pdf-pictures.js +50 -8
  110. package/dist/pdf-pictures.js.map +1 -1
  111. package/dist/pdf-work.d.ts +40 -0
  112. package/dist/pdf-work.d.ts.map +1 -0
  113. package/dist/pdf-work.js +734 -0
  114. package/dist/pdf-work.js.map +1 -0
  115. package/dist/plan.d.ts +22 -4
  116. package/dist/plan.d.ts.map +1 -1
  117. package/dist/plan.js +61 -12
  118. package/dist/plan.js.map +1 -1
  119. package/dist/retry.d.ts +23 -1
  120. package/dist/retry.d.ts.map +1 -1
  121. package/dist/retry.js +33 -3
  122. package/dist/retry.js.map +1 -1
  123. package/dist/search.d.ts +8 -2
  124. package/dist/search.d.ts.map +1 -1
  125. package/dist/search.js +60 -10
  126. package/dist/search.js.map +1 -1
  127. package/dist/sse.d.ts +35 -2
  128. package/dist/sse.d.ts.map +1 -1
  129. package/dist/sse.js +145 -31
  130. package/dist/sse.js.map +1 -1
  131. package/dist/stores.d.ts.map +1 -1
  132. package/dist/stores.js +5 -2
  133. package/dist/stores.js.map +1 -1
  134. package/dist/text-index.d.ts +6 -0
  135. package/dist/text-index.d.ts.map +1 -1
  136. package/dist/text-index.js +25 -8
  137. package/dist/text-index.js.map +1 -1
  138. package/dist/text.d.ts +62 -2
  139. package/dist/text.d.ts.map +1 -1
  140. package/dist/text.js +314 -14
  141. package/dist/text.js.map +1 -1
  142. package/dist/tools.d.ts +61 -1
  143. package/dist/tools.d.ts.map +1 -1
  144. package/dist/tools.js +269 -42
  145. package/dist/tools.js.map +1 -1
  146. package/dist/types.d.ts +102 -3
  147. package/dist/types.d.ts.map +1 -1
  148. package/dist/zip-directory.d.ts +43 -0
  149. package/dist/zip-directory.d.ts.map +1 -0
  150. package/dist/zip-directory.js +130 -0
  151. package/dist/zip-directory.js.map +1 -0
  152. package/docs/README.md +288 -0
  153. package/docs/api.md +37 -381
  154. package/docs/configuration.md +28 -558
  155. package/docs/getting-started.md +407 -223
  156. package/docs/guides/anthropic.md +590 -0
  157. package/docs/guides/conversations.md +629 -0
  158. package/docs/guides/costs-and-limits.md +726 -0
  159. package/docs/guides/deployment.md +654 -0
  160. package/docs/guides/errors-and-reliability.md +735 -0
  161. package/docs/guides/explorer-model.md +399 -0
  162. package/docs/guides/openai-compatible.md +602 -0
  163. package/docs/guides/own-adapter-and-loop.md +1169 -0
  164. package/docs/guides/pdfs.md +971 -0
  165. package/docs/guides/storage.md +731 -0
  166. package/docs/guides/testing.md +1199 -0
  167. package/docs/guides/vertex-and-gemini.md +717 -0
  168. package/docs/guides/web-app.md +1589 -0
  169. package/docs/how-it-works.md +1012 -164
  170. package/docs/measurements.md +881 -0
  171. package/docs/publishing.md +274 -46
  172. package/docs/reference/anthropic.md +427 -0
  173. package/docs/reference/ask.md +892 -0
  174. package/docs/reference/errors-and-retries.md +758 -0
  175. package/docs/reference/events.md +993 -0
  176. package/docs/reference/gemini.md +823 -0
  177. package/docs/reference/library.md +1467 -0
  178. package/docs/reference/node.md +528 -0
  179. package/docs/reference/openai.md +385 -0
  180. package/docs/reference/tools.md +883 -0
  181. package/docs/security.md +897 -103
  182. package/docs/troubleshooting.md +1390 -0
  183. package/package.json +2 -2
  184. package/src/analyze.ts +93 -42
  185. package/src/anthropic/adapter.ts +196 -39
  186. package/src/ask.ts +1087 -202
  187. package/src/encoding.ts +850 -0
  188. package/src/errors.ts +17 -0
  189. package/src/events.ts +442 -0
  190. package/src/evidence.ts +5 -2
  191. package/src/extract.ts +602 -62
  192. package/src/gemini/adapter.ts +118 -65
  193. package/src/gemini/chat.ts +28 -4
  194. package/src/gemini/errors.ts +34 -1
  195. package/src/gemini/generate.ts +23 -10
  196. package/src/gemini/index.ts +3 -3
  197. package/src/gemini/sse.ts +1 -1
  198. package/src/http.ts +376 -1
  199. package/src/index.ts +27 -5
  200. package/src/library.ts +459 -85
  201. package/src/map-reduce.ts +252 -51
  202. package/src/model.ts +236 -3
  203. package/src/node/handlers.ts +137 -22
  204. package/src/node/index.ts +2 -0
  205. package/src/node/sse.ts +198 -0
  206. package/src/openai/adapter.ts +306 -38
  207. package/src/output-limit.ts +44 -8
  208. package/src/pause.ts +41 -0
  209. package/src/pdf-pages.ts +268 -15
  210. package/src/pdf-pictures.ts +56 -9
  211. package/src/pdf-work.ts +722 -0
  212. package/src/plan.ts +68 -12
  213. package/src/retry.ts +49 -5
  214. package/src/search.ts +63 -10
  215. package/src/sse.ts +153 -28
  216. package/src/stores.ts +5 -2
  217. package/src/text-index.ts +26 -7
  218. package/src/text.ts +323 -13
  219. package/src/tools.ts +261 -42
  220. package/src/types.ts +107 -4
  221. package/src/zip-directory.ts +136 -0
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,10 @@ 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.",
144
200
  "- read_document reads a line range. Read around search hits before you rely on them.",
145
201
  "- 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."] : []),
202
+ ...(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
203
  "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
204
  "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
205
  );
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;
package/src/search.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { createContext, Script, type Context } from "node:vm";
2
+ import { pause } from "./pause.js";
2
3
  import { PASSAGE_CHARACTERS, PASSAGE_MAX_LINES, positionOf } from "./text-index.js";
3
- import { foldCase, LineIndex } from "./text.js";
4
+ import { foldCase, LineIndex, sliceWhole } from "./text.js";
4
5
  import type { DocumentMeta, StoredDocument } from "./types.js";
5
6
 
6
7
  const MAX_OCCURRENCES_PER_TERM = 200_000;
@@ -70,8 +71,7 @@ export interface DocumentSource {
70
71
  */
71
72
  export type ScanFeed = (chunk: TextChunk) => boolean | void | "again";
72
73
 
73
- /** Lets other work on the server run (an answer streaming to another user) before going on. */
74
- export const pause = () => new Promise<void>((resolve) => setImmediate(resolve));
74
+ export { pause };
75
75
 
76
76
  /** Feeds a document's text, a piece at a time, to `feed` until it returns true or the text ends. */
77
77
  export async function scanSource(source: DocumentSource, feed: ScanFeed, signal?: AbortSignal): Promise<void> {
@@ -227,7 +227,13 @@ export type GrepResult = {
227
227
  totalMatchingLines: number;
228
228
  /** True when the scan stopped early (too many matches or the regex time limit). */
229
229
  stoppedEarly: boolean;
230
+ /** The first `maxResults` matching lines. */
230
231
  matches: LineMatch[];
232
+ /**
233
+ * The last matching line of the document, when it is not among `matches`. Undefined when the
234
+ * scan stopped early: the last line it found need not be the last of the document.
235
+ */
236
+ last?: LineMatch;
231
237
  };
232
238
 
233
239
  export type GrepOptions = {
@@ -243,8 +249,12 @@ export type GrepOptions = {
243
249
 
244
250
  function clip(line: string, column: number): string {
245
251
  if (line.length <= SHOWN_LINE_CHARACTERS) return line;
246
- const start = Math.max(0, Math.min(column - SHOWN_LINE_CHARACTERS / 2, line.length - SHOWN_LINE_CHARACTERS));
247
- return `${start > 0 ? "…" : ""}${line.slice(start, start + SHOWN_LINE_CHARACTERS)}${start + SHOWN_LINE_CHARACTERS < line.length ? "…" : ""}`;
252
+ let start = Math.max(0, Math.min(column - SHOWN_LINE_CHARACTERS / 2, line.length - SHOWN_LINE_CHARACTERS));
253
+ // Never inside a character outside the basic plane (an emoji): half of one is refused by Claude's API.
254
+ const code = line.charCodeAt(start);
255
+ if (start > 0 && code >= 0xdc00 && code <= 0xdfff) start++;
256
+ const end = start + SHOWN_LINE_CHARACTERS;
257
+ return `${start > 0 ? "…" : ""}${sliceWhole(line, end).slice(start)}${end < line.length ? "…" : ""}`;
248
258
  }
249
259
 
250
260
  const RUN_SCAN = new Script("scan()");
@@ -331,6 +341,14 @@ function remember(recent: Array<readonly [number, string]>, chunk: TextChunk, ke
331
341
  */
332
342
  class LineSearch {
333
343
  private readonly hits: Array<{ line: number; column: number; text: string }> = [];
344
+ /** The latest matching line past the first `maxResults`: the last one of the document, once the scan is over. */
345
+ private last?: { line: number; column: number; text: string };
346
+ /** The lines around `last`, by number, kept from the pieces as they are read: they need not be read again. */
347
+ private readonly aroundLast = new Map<number, string>();
348
+ /** The line of the match whose lines `aroundLast` holds. */
349
+ private aroundLine = 0;
350
+ /** True once the lines around `last` are among the lines to show. */
351
+ private lastShown = false;
334
352
  private total = 0;
335
353
  stoppedEarly = false;
336
354
  /** True once nothing more is to be found or counted: the rest of the text need not be read. */
@@ -397,12 +415,38 @@ class LineSearch {
397
415
  if (found !== undefined) this.fill(line, found);
398
416
  }
399
417
  }
418
+ if (this.last && this.context > 0) this.keepAroundLast(chunk);
400
419
  this.recent = remember(this.recent, chunk, this.keep);
401
420
  return true;
402
421
  }
403
422
 
404
- /** Lines to show that were not in the pieces read (the scan stopped early). Read them and `fill` them. */
423
+ /** Keeps the lines around `last` that are in this piece or in the lines read just before it. */
424
+ private keepAroundLast(chunk: TextChunk): void {
425
+ const { line } = this.last!;
426
+ if (this.aroundLine !== line) {
427
+ this.aroundLast.clear();
428
+ this.aroundLine = line;
429
+ }
430
+ const end = chunk.firstLine + chunk.lines.lineCount - 1;
431
+ for (let other = Math.max(1, line - this.context); other <= Math.min(this.lineCount, line + this.context); other++) {
432
+ if (other === line || this.aroundLast.has(other)) continue;
433
+ const found = other >= chunk.firstLine && other <= end
434
+ ? chunk.lines.line(other - chunk.firstLine + 1)
435
+ : this.recent.find(([number]) => number === other)?.[1];
436
+ if (found !== undefined) this.aroundLast.set(other, found);
437
+ }
438
+ }
439
+
440
+ /**
441
+ * Lines to show that were not in the pieces read: those of a scan that stopped early, and those
442
+ * around the last match, which is known only once the scan is over. Read them and `fill` them.
443
+ */
405
444
  missing(): number[] {
445
+ if (this.last && !this.lastShown && !this.stoppedEarly) {
446
+ this.lastShown = true;
447
+ this.showAround(this.last.line);
448
+ if (this.aroundLine === this.last.line) for (const [line, text] of this.aroundLast) this.fill(line, text);
449
+ }
406
450
  if (this.unfilled === 0) return [];
407
451
  return [...this.shown].filter(([, text]) => text === undefined).map(([line]) => line).sort((left, right) => left - right);
408
452
  }
@@ -415,7 +459,7 @@ class LineSearch {
415
459
 
416
460
  result(): GrepResult {
417
461
  const lineText = (line: number) => this.shown.get(line) ?? "";
418
- const matches = this.hits.map(({ line, column, text }): LineMatch => {
462
+ const show = ({ line, column, text }: { line: number; column: number; text: string }): LineMatch => {
419
463
  const match: LineMatch = { line, text: clip(text, column) };
420
464
  if (this.context > 0) {
421
465
  match.before = [];
@@ -424,14 +468,23 @@ class LineSearch {
424
468
  for (let other = line + 1; other <= Math.min(this.lineCount, line + this.context); other++) match.after.push(`${other}| ${clip(lineText(other), 0)}`);
425
469
  }
426
470
  return match;
427
- });
428
- return { totalMatchingLines: this.total, stoppedEarly: this.stoppedEarly, matches };
471
+ };
472
+ const last = this.last && !this.stoppedEarly ? { last: show(this.last) } : {};
473
+ return { totalMatchingLines: this.total, stoppedEarly: this.stoppedEarly, matches: this.hits.map(show), ...last };
429
474
  }
430
475
 
431
476
  private record(line: number, column: number, text: string): void {
432
477
  this.total++;
433
- if (this.hits.length >= this.settings.maxResults) return;
478
+ if (this.hits.length >= this.settings.maxResults) {
479
+ this.last = { line, column, text };
480
+ return;
481
+ }
434
482
  this.hits.push({ line, column, text });
483
+ this.showAround(line);
484
+ }
485
+
486
+ /** Puts the lines around a match among the lines to show. */
487
+ private showAround(line: number): void {
435
488
  for (let other = Math.max(1, line - this.context); other <= Math.min(this.lineCount, line + this.context); other++) {
436
489
  if (other !== line && !this.shown.has(other)) {
437
490
  this.shown.set(other, undefined);
package/src/sse.ts CHANGED
@@ -1,34 +1,159 @@
1
- /** Parses a `text/event-stream` body into JSON objects, one per `data:` event. */
2
- export async function* parseSseJson<T>(stream: ReadableStream<Uint8Array>): AsyncGenerator<T> {
3
- const reader = stream.getReader();
1
+ import { bodyPieces } from "./http.js";
2
+
3
+ /** What a stream reader can be told of as the stream goes: see `parseSseJson`. */
4
+ export type SseHooks = {
5
+ /** Bytes arrived: an event, part of one, or a keep-alive comment. */
6
+ onData?: () => void;
7
+ /** The stream said it is done (`data: [DONE]`), as OpenAI-compatible servers do at the end. */
8
+ onDone?: () => void;
9
+ /** When it aborts, the next piece is not waited for: the stream ends with its reason. */
10
+ signal?: AbortSignal | undefined;
11
+ /**
12
+ * The most characters one event may hold: what its data lines hold after `data:` and the spaces
13
+ * after it, and the line feeds that join them. A line of another field (a comment, `event:`)
14
+ * counts in full with the event, as it is held until its end. A longer event ends the stream with
15
+ * an error named `SseEventTooLongError`, rather than fill the memory of the server, however the
16
+ * stream is cut into pieces. Defaults to 64,000,000. `Infinity` sets no limit; a value that is not
17
+ * a positive number counts as not set.
18
+ */
19
+ maxEventLength?: number;
20
+ };
21
+
22
+ /** The most characters one event holds, by default: see `SseHooks.maxEventLength`. */
23
+ const DEFAULT_MAX_EVENT_LENGTH = 64_000_000;
24
+ /** The data lines of an event are joined this many at a time as they come (see `parseSseJson`). */
25
+ const JOIN_LINES = 1_024;
26
+
27
+ /** An event of a stream held more characters than `SseHooks.maxEventLength`, and was not read. */
28
+ export class SseEventTooLongError extends Error {
29
+ constructor(readonly limit: number) {
30
+ super(`An event of the stream held more than ${limit.toLocaleString("en-US")} characters.`);
31
+ this.name = "SseEventTooLongError";
32
+ }
33
+ }
34
+
35
+ /**
36
+ * The message of a reply whose stream had an event too long to read. It is not sent again: the same
37
+ * event would most likely come back. `who` is "Gemini's", "Claude's"…
38
+ */
39
+ export function eventTooLongMessage(who: string, error: SseEventTooLongError): string {
40
+ return `${who} reply could not be read: an event of its stream held more than ${error.limit.toLocaleString("en-US")} characters.`;
41
+ }
42
+
43
+ /**
44
+ * Parses a `text/event-stream` body into JSON objects, one per `data:` event. The body is a web
45
+ * stream (the global `fetch`), or a Node stream (node-fetch and the like). Lines end with LF, CRLF
46
+ * or CR alone, as the format allows. Each piece of the body is read once, however long the event
47
+ * it belongs to: a line that has not ended waits for the next piece.
48
+ */
49
+ export async function* parseSseJson<T>(stream: ReadableStream<Uint8Array> | AsyncIterable<Uint8Array | string>, hooks: SseHooks = {}): AsyncGenerator<T> {
4
50
  const decoder = new TextDecoder();
5
- let buffer = "";
6
- const parse = (block: string): T | undefined => {
7
- const data = block
8
- .split("\n")
9
- .filter((line) => line.startsWith("data:"))
10
- .map((line) => line.slice(5).trimStart())
11
- .join("\n");
12
- return data && data !== "[DONE]" ? JSON.parse(data) as T : undefined;
51
+ const most = typeof hooks.maxEventLength === "number" && hooks.maxEventLength > 0 ? hooks.maxEventLength : DEFAULT_MAX_EVENT_LENGTH;
52
+ /** The data lines of the event being read, since the last ones were joined into `joined`. */
53
+ let data: string[] = [];
54
+ /**
55
+ * Earlier data lines of the event, joined `JOIN_LINES` at a time: an event of millions of empty
56
+ * data lines would otherwise hold a slot for each, far more memory than the characters counted.
57
+ */
58
+ let joined: string[] = [];
59
+ /** The characters of the event those lines make. */
60
+ let held = 0;
61
+ /** The start of a line whose end has not arrived. */
62
+ let partial = "";
63
+ /**
64
+ * Whether that line is a data line, and if so whether its value has begun after `data:` and the
65
+ * spaces after it. Undefined while what has come of it may still be the start of `data:`.
66
+ */
67
+ let partialKind: "field" | "value" | "other" | undefined;
68
+ /** The characters of the event that line holds, as `held` counts them. */
69
+ let partialHeld = 0;
70
+ /** The last piece ended with CR: a LF that starts the next one belongs to that line end. */
71
+ let afterCr = false;
72
+ const lineEnd = /\r\n?|\n/g;
73
+ /** The event of the data lines read so far, which a blank line ends. */
74
+ const event = (): T | undefined => {
75
+ if (data.length > 0) joined.push(data.join("\n"));
76
+ const text = joined.join("\n");
77
+ data = [];
78
+ joined = [];
79
+ held = 0;
80
+ if (text === "[DONE]") hooks.onDone?.();
81
+ return text && text !== "[DONE]" ? JSON.parse(text) as T : undefined;
82
+ };
83
+ const take = (line: string): T | undefined => {
84
+ if (!line) return event();
85
+ if (line.startsWith("data:")) {
86
+ const value = line.slice(5).trimStart();
87
+ // The line feed that joins it to the line before counts too: empty data lines add up.
88
+ held += value.length + (data.length > 0 || joined.length > 0 ? 1 : 0);
89
+ if (held > most) throw new SseEventTooLongError(most);
90
+ data.push(value);
91
+ if (data.length >= JOIN_LINES) {
92
+ joined.push(data.join("\n"));
93
+ data = [];
94
+ }
95
+ } else if (held + line.length > most) {
96
+ // Another line is not kept, but it was held until its end: it counts as it did then.
97
+ throw new SseEventTooLongError(most);
98
+ }
99
+ return undefined;
13
100
  };
14
- try {
15
- while (true) {
16
- const { done, value } = await reader.read();
17
- buffer += decoder.decode(value, { stream: !done });
18
- buffer = buffer.replace(/\r\n/g, "\n");
19
- let boundary = buffer.indexOf("\n\n");
20
- while (boundary >= 0) {
21
- const event = parse(buffer.slice(0, boundary));
22
- buffer = buffer.slice(boundary + 2);
23
- if (event !== undefined) yield event;
24
- boundary = buffer.indexOf("\n\n");
101
+ /**
102
+ * Adds the rest of a piece to the line whose end has not arrived, and counts it as `take` will
103
+ * count the whole line. Only the rest is looked at, not what came of the line before.
104
+ */
105
+ const hold = (rest: string): void => {
106
+ let at = 0;
107
+ if (partialKind === undefined) {
108
+ const start = partial + rest.slice(0, 5 - partial.length);
109
+ at = start.length - partial.length;
110
+ if (start === "data:") {
111
+ partialKind = "field";
112
+ partialHeld = data.length > 0 || joined.length > 0 ? 1 : 0;
113
+ } else if (!"data:".startsWith(start)) {
114
+ partialKind = "other";
115
+ partialHeld = partial.length;
116
+ at = 0;
25
117
  }
26
- if (done) break;
27
118
  }
28
- const last = buffer.trim() ? parse(buffer.trim()) : undefined;
29
- if (last !== undefined) yield last;
30
- } finally {
31
- await reader.cancel().catch(() => undefined);
32
- reader.releaseLock();
119
+ if (partialKind === "field") {
120
+ const value = rest.slice(at).search(/\S/);
121
+ if (value >= 0) partialKind = "value";
122
+ at = value >= 0 ? at + value : rest.length;
123
+ }
124
+ // What counts starts at `at`: at the end of the rest while the line may still be a data line,
125
+ // or while the value of one has not begun.
126
+ partialHeld += rest.length - at;
127
+ partial += rest;
128
+ if (held + partialHeld > most) throw new SseEventTooLongError(most);
129
+ };
130
+ // The events that end in this text, one at a time: a line that does not end in it waits for more.
131
+ function* lines(text: string): Generator<T> {
132
+ if (!text) return;
133
+ let from = afterCr && text.startsWith("\n") ? 1 : 0;
134
+ afterCr = false;
135
+ lineEnd.lastIndex = from;
136
+ for (let found = lineEnd.exec(text); found; found = lineEnd.exec(text)) {
137
+ const line = partial + text.slice(from, found.index);
138
+ partial = "";
139
+ partialKind = undefined;
140
+ partialHeld = 0;
141
+ from = lineEnd.lastIndex;
142
+ if (found[0] === "\r" && from === text.length) afterCr = true;
143
+ const parsed = take(line);
144
+ if (parsed !== undefined) yield parsed;
145
+ lineEnd.lastIndex = from;
146
+ }
147
+ hold(text.slice(from));
148
+ }
149
+ for await (const value of bodyPieces(stream, hooks.signal)) {
150
+ if (value.length > 0) hooks.onData?.();
151
+ yield* lines(decoder.decode(value, { stream: true }));
33
152
  }
153
+ yield* lines(decoder.decode());
154
+ // A last line, and a last event, that the stream ended without a line end or a blank line after.
155
+ if (partial.trim()) take(partial.trim());
156
+ partial = "";
157
+ const last = event();
158
+ if (last !== undefined) yield last;
34
159
  }
package/src/stores.ts CHANGED
@@ -19,8 +19,11 @@ export class MemoryDocumentStore implements DocumentStore {
19
19
  this.now = options.now ?? (() => new Date());
20
20
  }
21
21
 
22
+ // The metadata is copied on the way in and on the way out, as a store that writes it somewhere
23
+ // does: an app that changes the metadata it was handed (deletes its owner before sending it to a
24
+ // browser) must not change the document's owner or expiry.
22
25
  async put(document: StoredDocument): Promise<void> {
23
- this.documents.set(document.meta.id, document);
26
+ this.documents.set(document.meta.id, { meta: structuredClone(document.meta), text: document.text });
24
27
  }
25
28
 
26
29
  async get(id: string): Promise<StoredDocument | undefined> {
@@ -29,7 +32,7 @@ export class MemoryDocumentStore implements DocumentStore {
29
32
  await this.delete(id);
30
33
  return undefined;
31
34
  }
32
- return document;
35
+ return document && { meta: structuredClone(document.meta), text: document.text };
33
36
  }
34
37
 
35
38
  async getMeta(id: string): Promise<DocumentMeta | undefined> {
package/src/text-index.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  * It is built from the bytes of the text, in one pass, at ingest (and written next to the text
7
7
  * with `putIndex`), or the first time an older document without one is used.
8
8
  */
9
+ import type { TimeSlicer } from "./pause.js";
9
10
  import type { DocumentMeta } from "./types.js";
10
11
 
11
12
  /** A passage, for keyword search, is a run of lines of about this many characters... */
@@ -126,18 +127,36 @@ export class TextIndexBuilder {
126
127
  /** The index of a text held as a string, built from its UTF-8 bytes a slice at a time. */
127
128
  export function buildTextIndex(text: string): TextIndex {
128
129
  const builder = new TextIndexBuilder();
129
- const slice = 1 << 20;
130
+ for (let at = 0; at < text.length;) at = pushSlice(builder, text, at);
131
+ return builder.finish();
132
+ }
133
+
134
+ /**
135
+ * `buildTextIndex`, the same index, with pauses for other requests while a large text is indexed.
136
+ * `onProgress` is told the characters indexed so far, after each slice.
137
+ */
138
+ export async function buildTextIndexInSlices(text: string, slicer: TimeSlicer, onProgress?: (done: number, total: number) => void): Promise<TextIndex> {
139
+ const builder = new TextIndexBuilder();
130
140
  for (let at = 0; at < text.length;) {
131
- let end = Math.min(text.length, at + slice);
132
- // Never cut between the two halves of a surrogate pair: each half alone encodes as U+FFFD.
133
- const last = text.charCodeAt(end - 1);
134
- if (end < text.length && last >= 0xd800 && last <= 0xdbff) end++;
135
- builder.push(Buffer.from(text.slice(at, end), "utf8"));
136
- at = end;
141
+ at = pushSlice(builder, text, at);
142
+ onProgress?.(at, text.length);
143
+ await slicer.maybePause();
137
144
  }
138
145
  return builder.finish();
139
146
  }
140
147
 
148
+ /** Pushes the next slice of `text`, from `at`, as UTF-8; returns where the slice ended. */
149
+ function pushSlice(builder: TextIndexBuilder, text: string, at: number): number {
150
+ let end = Math.min(text.length, at + (1 << 18));
151
+ // Never cut between the two halves of a surrogate pair: each half alone encodes as U+FFFD. Only
152
+ // a real pair is kept whole: a first half followed by anything else is one U+FFFD either way.
153
+ const last = text.charCodeAt(end - 1);
154
+ const next = text.charCodeAt(end);
155
+ if (end < text.length && last >= 0xd800 && last <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) end++;
156
+ builder.push(Buffer.from(text.slice(at, end), "utf8"));
157
+ return end;
158
+ }
159
+
141
160
  // The file: a 40-byte header, then the lists of 32-bit numbers (line starts in bytes, line starts
142
161
  // in characters, passage starts, page starts), all little-endian.
143
162
  // 0 "LLFI" 4 version 8 lineCount 12 passages 16 pages 20 unused