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/model.ts CHANGED
@@ -43,6 +43,17 @@ export type ChatTurn = { role: "user" | "assistant" | "model"; text: string };
43
43
  */
44
44
  export type ToolTurn = { role: "tools"; calls: Array<ToolCall & { result: ToolResult }> };
45
45
 
46
+ /**
47
+ * A result of a stored tool round, as it is sent again in a later question: without
48
+ * `tool_turns_left`, which counted the tool turns its own question had left, not those of the
49
+ * later one. The same result when it has none.
50
+ */
51
+ export function laterResult(result: ToolResult): ToolResult {
52
+ if (result === null || typeof result !== "object" || !("tool_turns_left" in result)) return result;
53
+ const { tool_turns_left: _left, ...rest } = result;
54
+ return rest;
55
+ }
56
+
46
57
  /** What `askWithFiles` takes as conversation: plain turns, stored tool rounds, and turns with native parts. */
47
58
  export type ChatMessage = ChatTurn | ToolTurn | ModelTextMessage;
48
59
 
@@ -78,7 +89,15 @@ export type ModelReply = {
78
89
  calls: ToolCall[];
79
90
  /** This turn in the provider's own form, to send back unchanged with the tool results. */
80
91
  raw?: unknown;
92
+ /** Why the reply ended, in the provider's own word ("STOP", "length", "end_turn"). */
81
93
  finishReason?: string;
94
+ /**
95
+ * How the reply ended, in terms every adapter maps its own to: "complete"; "cut" at the output
96
+ * limit; "filtered" by the provider's safety filters; "malformed_call", a tool call the model
97
+ * tried to make that could not be read (Gemini's MALFORMED_FUNCTION_CALL). Unset when the
98
+ * adapter does not know the reason.
99
+ */
100
+ finish?: "complete" | "cut" | "filtered" | "malformed_call";
82
101
  /** Why the provider refused the prompt, when it did. Nothing more is asked after it. */
83
102
  blockReason?: string;
84
103
  usage?: Partial<ModelUsage>;
@@ -128,6 +147,13 @@ export type ModelCapabilities = {
128
147
  * question is answered with what it has.
129
148
  */
130
149
  appendOnly?: boolean;
150
+ /**
151
+ * True for a model whose provider may clear old tool results from the conversation on its side,
152
+ * before the model reads it (Claude's context editing with `clear_tool_uses`, or compaction). A
153
+ * call made again is then run again, instead of being answered with a pointer to an earlier
154
+ * result that the model may no longer have.
155
+ */
156
+ clearsToolResults?: boolean;
131
157
  };
132
158
 
133
159
  /** A model provider, as the tool loop sees it. */
@@ -135,7 +161,12 @@ export interface ModelAdapter {
135
161
  /** Names the model in usage totals and messages: "gemini-3.8-flash". */
136
162
  readonly id: string;
137
163
  readonly capabilities: ModelCapabilities;
138
- /** How many tokens a text is for this model. Defaults to the library's estimate. */
164
+ /**
165
+ * @deprecated Never called. The loop counts every request in the library's estimate
166
+ * (`estimateTokens`), as the documents were counted when they were uploaded, and turns that into
167
+ * this model's tokens with `capabilities.tokenScale`: set `tokenScale` instead. Kept so that
168
+ * adapters that declare it still compile; it may be removed in a later version.
169
+ */
139
170
  estimateTokens?(text: string): number;
140
171
  /**
141
172
  * One chat request. Throw a `ModelRequestError` for an HTTP error or a connection that failed:
@@ -151,21 +182,223 @@ export interface ModelAdapter {
151
182
  generateText?: GenerateText;
152
183
  }
153
184
 
185
+ /**
186
+ * What went wrong with a model request, as far as the error says:
187
+ * - "context_overflow": the request was larger than the model takes (its context window, or the
188
+ * size of the body). A smaller request can work.
189
+ * - "quota": a quota that does not come back soon (a daily cap, no credit left). Sending again
190
+ * does not help.
191
+ * - "rate_limit": too many requests or tokens for now (HTTP 429). Sending again later helps.
192
+ * - "timeout": nothing came from the model for longer than the adapter waits (`firstByteTimeoutMs`,
193
+ * `idleTimeoutMs`; status 0), or the provider or a gateway said the request timed out (HTTP 408).
194
+ * - "unreachable": no answer at all: the connection failed.
195
+ * - "server": the provider failed on its side (HTTP 5xx).
196
+ * - "auth": the key or token was refused (HTTP 401, 403).
197
+ * - "invalid": the provider refused the request as it was (another HTTP 4xx).
198
+ */
199
+ export type ModelErrorKind = "context_overflow" | "quota" | "rate_limit" | "timeout" | "unreachable" | "server" | "auth" | "invalid";
200
+
201
+ /** How an error was told apart, with the numbers of an overflow when the message gives them. */
202
+ export type ModelErrorClass = {
203
+ kind: ModelErrorKind;
204
+ /** The most input tokens the model takes, as the provider counts them. */
205
+ limitTokens?: number;
206
+ /**
207
+ * The tokens of the refused request that the provider counted against the window: its input,
208
+ * and for some providers (OpenRouter, vLLM) the output it would have taken too.
209
+ */
210
+ requestedTokens?: number;
211
+ };
212
+
213
+ /** Wording of a request larger than the model takes, across providers. */
214
+ const OVERFLOW_WORDING = [
215
+ /context[_ ]length[_ ]exceeded/i,
216
+ /maximum context length/i,
217
+ /prompt is too long/i,
218
+ /input token count\b.{0,40}\bexceeds/i,
219
+ // Vertex AI: "Unable to submit request because the input token count is N but model only supports up to M."
220
+ /input token count is [\d,]+ but/i,
221
+ /model only supports up to/i,
222
+ /exceeds? the maximum number of tokens/i,
223
+ /maximum context (?:size|window)/i,
224
+ /too large for (?:the )?model with [\d,]+ maximum context/i,
225
+ /exceeds? (?:the )?(?:available |model'?s? )?context (?:size|window|length)/i,
226
+ /request payload size exceeds/i,
227
+ /reduce the length of the messages/i,
228
+ /input tokens? exceeds?/i,
229
+ /request_too_large/i,
230
+ // Claude 3.7 to 4.1: "input length and `max_tokens` exceed context limit: 188240 + 21333 > 200000".
231
+ /exceed context limit/i,
232
+ // Text Generation Inference (Hugging Face, Together): "Input validation error: `inputs` tokens +
233
+ // `max_new_tokens` must be <= 32769. Given: 40000 `inputs` tokens and 1024 `max_new_tokens`".
234
+ /`?inputs`? tokens \+ `?max_new_tokens`? must be <=/i,
235
+ /`?inputs`? must have less than [\d,]+ tokens/i,
236
+ // LM Studio: "Trying to keep the first 9000 tokens when context the overflows. However, the model
237
+ // is loaded with context length of only 4096 tokens, which is not enough."
238
+ /loaded with context length of only/i,
239
+ /tokens to keep from the initial prompt is greater than the context length/i,
240
+ // Amazon Bedrock: "Input is too long for requested model."
241
+ /input is too long for (?:the )?(?:requested )?model/i,
242
+ ];
243
+ /**
244
+ * A request larger than the tokens a whole minute (or day) allows. OpenAI: "Request too large for
245
+ * gpt-4o in organization org-… on tokens per min (TPM): Limit 30000, Requested 45237.", as HTTP 429.
246
+ * Groq says "tokens per minute", as HTTP 413. No wait lets it pass: only a smaller request can.
247
+ */
248
+ const RATE_TOO_SMALL = /request too large for .{0,200}\bon tokens per (min(?:ute)?|day)\b/i;
249
+ /** Wording of throttling, which can share words with an overflow ("too many tokens, please wait"). */
250
+ const THROTTLE_WORDING = /rate.?limit|too many requests|please (?:wait|try again later)|per (?:minute|second|day)\b|\b[TR]PM\b|throttl/i;
251
+
252
+ const LIMIT_WORDING = [
253
+ /maximum context length is ([\d,]+)/i,
254
+ // The Gemini API puts the number in parentheses; Vertex AI (November 2026) does not:
255
+ // "The input token count exceeds the maximum number of tokens allowed 1048576."
256
+ /maximum number of tokens allowed \(?([\d,]+)/i,
257
+ /> ?([\d,]+) maximum/i,
258
+ /with ([\d,]+) maximum context/i,
259
+ /configured limit of ([\d,]+) tokens/i,
260
+ /supports up to ([\d,]+)/i,
261
+ /context limit: [\d,]+ \+ [\d,]+ > ([\d,]+)/i,
262
+ /must be <= ?([\d,]+)/i,
263
+ /must have less than ([\d,]+) tokens/i,
264
+ /context length of only ([\d,]+) tokens/i,
265
+ /\bLimit:? ([\d,]+), Requested\b/i,
266
+ ];
267
+ const REQUESTED_WORDING = [
268
+ /input token count \(([\d,]+)\)/i,
269
+ /input token count is ([\d,]+)/i,
270
+ /context limit: ([\d,]+) \+/i,
271
+ /\(([\d,]+) in the messages/i,
272
+ /resulted in ([\d,]+) tokens/i,
273
+ /too long: ([\d,]+) tokens/i,
274
+ /prompt contains ([\d,]+) tokens/i,
275
+ /requested (?:about )?([\d,]+) tokens/i,
276
+ // vLLM since its errors changed: "However, your request has 40000 input tokens."
277
+ /your request has ([\d,]+) input tokens/i,
278
+ /\bGiven: ([\d,]+)/i,
279
+ /\bRequested:? ([\d,]+)/i,
280
+ ];
281
+ /**
282
+ * Wording of a quota that does not come back soon: no credit left (DeepSeek's "Insufficient
283
+ * Balance", OpenRouter's "Insufficient credits", Claude's "Your credit balance is too low"), or a
284
+ * spending cap that was reached (Claude's "You have reached your API usage limits").
285
+ */
286
+ const QUOTA_WORDING = /credit balance is too low|insufficient (?:balance|credits?|funds)|reached your (?:specified )?API usage limits/i;
287
+ /** A quota per day named in the message alone: Vertex AI's "Quota exceeded for …requests_per_day_per_project…". */
288
+ const DAILY_QUOTA_WORDING = /quota.{0,200}(?:per[_ -]?day|PerDay)/i;
289
+
290
+ function firstNumber(message: string, patterns: RegExp[]): number | undefined {
291
+ for (const pattern of patterns) {
292
+ const found = pattern.exec(message)?.[1];
293
+ if (!found) continue;
294
+ const value = Number(found.replace(/,/g, ""));
295
+ if (Number.isFinite(value) && value > 0) return value;
296
+ }
297
+ return undefined;
298
+ }
299
+
300
+ /** True when a Gemini error says a quota per day ran out: `google.rpc.QuotaFailure` with a "PerDay" quota. */
301
+ function dailyQuota(details: unknown): boolean {
302
+ if (!Array.isArray(details)) return false;
303
+ return details.some((detail) => {
304
+ const violations = (detail as { violations?: unknown } | null)?.violations;
305
+ return Array.isArray(violations) && violations.some((violation) => {
306
+ const id = (violation as { quotaId?: unknown; quotaMetric?: unknown } | null);
307
+ return /per.?day/i.test(`${String(id?.quotaId ?? "")} ${String(id?.quotaMetric ?? "")}`);
308
+ });
309
+ });
310
+ }
311
+
312
+ /** A request larger than the model takes, with the numbers its message gives. */
313
+ function overflowOf(message: string): ModelErrorClass {
314
+ const limitTokens = firstNumber(message, LIMIT_WORDING);
315
+ const requestedTokens = firstNumber(message, REQUESTED_WORDING);
316
+ return { kind: "context_overflow", ...(limitTokens ? { limitTokens } : {}), ...(requestedTokens ? { requestedTokens } : {}) };
317
+ }
318
+
319
+ /** True when a Gemini error names an API key that is not valid (it comes as HTTP 400). */
320
+ const keyRefused = (details: unknown): boolean => Array.isArray(details) && details.some((detail) => (detail as { reason?: unknown } | null)?.reason === "API_KEY_INVALID");
321
+
322
+ /**
323
+ * Tells what kind of failure an HTTP status and an error message are (see `ModelErrorKind`).
324
+ * `code` is the provider's own word, when it gives one (OpenAI's `error.code`, Claude's
325
+ * `error.type`, Gemini's `error.status`); `details` is a Gemini error's `details`. A quota is told
326
+ * from those, from HTTP 402 (payment required), and from words that only a quota uses (no credit
327
+ * left, a spending cap, a quota per day): Gemini says "You exceeded your current quota" of a limit
328
+ * per minute too, which a wait mends.
329
+ */
330
+ export function classifyModelError(status: number, message: string, signals: { code?: string | undefined; details?: unknown } = {}): ModelErrorClass {
331
+ const { code, details } = signals;
332
+ if (status === 0) return { kind: "unreachable" };
333
+ if (code === "insufficient_quota" || status === 402 || (status === 429 && (dailyQuota(details) || DAILY_QUOTA_WORDING.test(message)))) return { kind: "quota" };
334
+ if (status < 500 && QUOTA_WORDING.test(message)) return { kind: "quota" };
335
+ // Larger than the provider lets through in a minute: a context overflow, though it comes as 429,
336
+ // and though its words are those of a rate limit.
337
+ if ((status === 429 || status === 413) && RATE_TOO_SMALL.test(message)) return overflowOf(message);
338
+ const throttled = THROTTLE_WORDING.test(message);
339
+ const overflow = !throttled && status !== 429 && status < 500 && (
340
+ status === 413 || code === "context_length_exceeded" || code === "request_too_large" || OVERFLOW_WORDING.some((pattern) => pattern.test(message))
341
+ );
342
+ if (overflow) return overflowOf(message);
343
+ if (status === 429) return { kind: "rate_limit" };
344
+ if (status === 408) return { kind: "timeout" };
345
+ if (status >= 500) return { kind: "server" };
346
+ if (status === 401 || status === 403 || keyRefused(details)) return { kind: "auth" };
347
+ return { kind: "invalid" };
348
+ }
349
+
154
350
  /**
155
351
  * A model request that failed: the provider answered with an HTTP error, or could not be reached
156
- * (`status` 0). `retryAfterMs` is the wait the provider asked for, when it named one.
352
+ * (`status` 0). `retryAfterMs` is the wait the provider asked for, when it named one. `kind` says
353
+ * what went wrong (see `ModelErrorKind`); for a request larger than the model takes,
354
+ * `limitTokens` and `requestedTokens` are the provider's numbers, when its message gives them.
157
355
  */
158
356
  export class ModelRequestError extends Error {
159
357
  readonly status: number;
160
358
  readonly retryAfterMs?: number;
161
- constructor(message: string, status: number, options: { retryAfterMs?: number; cause?: unknown } = {}) {
359
+ readonly kind: ModelErrorKind;
360
+ readonly limitTokens?: number;
361
+ readonly requestedTokens?: number;
362
+ constructor(message: string, status: number, options: {
363
+ retryAfterMs?: number;
364
+ cause?: unknown;
365
+ /** The kind, when the adapter knows it (a timeout). Otherwise it is told from the status and the message. */
366
+ kind?: ModelErrorKind;
367
+ /** The provider's own word for the error, used to tell its kind. */
368
+ code?: string | undefined;
369
+ /** The `details` of a Gemini error, used to tell its kind. */
370
+ details?: unknown;
371
+ } = {}) {
162
372
  super(message, options.cause === undefined ? undefined : { cause: options.cause });
163
373
  this.name = "ModelRequestError";
164
374
  this.status = status;
165
375
  if (options.retryAfterMs !== undefined) this.retryAfterMs = options.retryAfterMs;
376
+ const found = classifyModelError(status, message, { code: options.code, details: options.details });
377
+ this.kind = options.kind ?? found.kind;
378
+ if (this.kind === "context_overflow") {
379
+ if (found.limitTokens) this.limitTokens = found.limitTokens;
380
+ if (found.requestedTokens) this.requestedTokens = found.requestedTokens;
381
+ }
166
382
  }
167
383
  }
168
384
 
385
+ /** The kind of a model error, when it has one: a `ModelRequestError`'s, or that of an error with the same field. */
386
+ export function errorKindOf(error: unknown): ModelErrorKind | undefined {
387
+ const kind = (error as { kind?: unknown } | null)?.kind;
388
+ return typeof kind === "string" ? kind as ModelErrorKind : undefined;
389
+ }
390
+
391
+ /**
392
+ * For a request refused as larger than the tokens a minute (or a day) of the provider allows, not
393
+ * than the model's window: that period. Undefined for any other error.
394
+ */
395
+ export function rateAllowanceOf(error: unknown): "minute" | "day" | undefined {
396
+ if (errorKindOf(error) !== "context_overflow" || !(error instanceof Error)) return undefined;
397
+ const period = RATE_TOO_SMALL.exec(error.message)?.[1];
398
+ if (period === undefined) return undefined;
399
+ return period.toLowerCase() === "day" ? "day" : "minute";
400
+ }
401
+
169
402
  /** Some document IDs were never uploaded, have expired, or belong to another owner. */
170
403
  export class DocumentsNotFoundError extends Error {
171
404
  constructor(readonly ids: string[]) {
@@ -188,7 +421,14 @@ export class UsageMeter {
188
421
  readonly totals: UsageTotals = { requests: 0, ...EMPTY_USAGE, byModel: {} };
189
422
 
190
423
  add(model: string, usage: Partial<ModelUsage> | undefined): void {
191
- const of = (this.totals.byModel[model] ??= { requests: 0, ...EMPTY_USAGE });
424
+ const { byModel } = this.totals;
425
+ // An own entry only: an id such as "__proto__" or "constructor" found what every object
426
+ // inherits, and "__proto__" then counted the usage into Object.prototype.
427
+ let of = Object.hasOwn(byModel, model) ? byModel[model] : undefined;
428
+ if (!of) {
429
+ of = { requests: 0, ...EMPTY_USAGE };
430
+ Object.defineProperty(byModel, model, { value: of, enumerable: true, writable: true, configurable: true });
431
+ }
192
432
  for (const sum of [this.totals, of]) {
193
433
  sum.requests++;
194
434
  for (const key of Object.keys(EMPTY_USAGE) as Array<keyof ModelUsage>) {
@@ -1,11 +1,19 @@
1
1
  import type { IncomingMessage, ServerResponse } from "node:http";
2
- import { toDocumentSummary, type LargeFiles } from "../library.js";
2
+ import { IngestError, isStoreWriteFailure } from "../errors.js";
3
+ import { eventStream, newRunId, type EventError, type IngestEvent } from "../events.js";
4
+ import { checkOwner, toDocumentSummary, type IngestInput, type LargeFiles } from "../library.js";
3
5
  import { formatBytes } from "../plan.js";
6
+ import type { DocumentMeta } from "../types.js";
7
+ import { writeSseEvents } from "./sse.js";
4
8
 
5
9
  export type DocumentHandlerOptions = {
6
10
  /**
7
11
  * The signed-in user for this request. When set, uploads are owned by that user and other
8
- * users cannot read or delete them. Return undefined to allow anonymous access.
12
+ * users cannot read or delete them. Return undefined to allow anonymous access. An empty owner
13
+ * ("", spaces only, or null from JavaScript) is the server's mistake: the upload is answered with a 500
14
+ * `{"error":"Upload failed (empty owner)."}`, before its body is read. So is an owner from
15
+ * JavaScript that is neither a string nor a finite number (`req.user` in place of `req.user.id`,
16
+ * say): `{"error":"Upload failed (owner is not a string)."}`.
9
17
  *
10
18
  * To refuse a request, throw an error with a `status` (or `statusCode`) between 400 and 599, as
11
19
  * the `http-errors` package makes: the handler answers with that status and the error's message.
@@ -17,10 +25,21 @@ export type DocumentHandlerOptions = {
17
25
 
18
26
  /**
19
27
  * The handlers answer every request themselves, errors included, and never reject: they can be
20
- * called without a `catch`, from `node:http` or from Express 4.
28
+ * called without a `catch`, from `node:http`, from Express 4 (which does not catch a rejected
29
+ * promise) or from Express 5.
21
30
  */
22
31
  export type DocumentHandlers = {
23
- /** POST: the body is the raw file. Name it with an `X-File-Name` header (URI-encoded) or `?name=`. */
32
+ /**
33
+ * POST: the body is the raw file. Name it with an `X-File-Name` header (URI-encoded) or `?name=`.
34
+ * A file that cannot be read is answered with a 422 and the reason. A store that fails while it
35
+ * writes is answered with a 500 that does not repeat its message, unless its error has a status.
36
+ *
37
+ * When the request's `Accept` header names `text/event-stream` (not with `q=0`, nor only through a
38
+ * wildcard), a file that passes the checks of the name, the owner and the size (which still
39
+ * answer with an HTTP error) is answered with a 200 and Server-Sent Events: the ingest's events (`ingest.start`, `ingest.progress`…), ending
40
+ * with `ingest.finish`, whose data is the summary a 201 would hold, or `ingest.error`, whose data
41
+ * is `{ error: { message, status } }` with the message and status a JSON answer would have.
42
+ */
24
43
  upload(request: IncomingMessage, response: ServerResponse): Promise<void>;
25
44
  /** GET: the document's summary, or 404. */
26
45
  get(request: IncomingMessage, response: ServerResponse, id: string): Promise<void>;
@@ -53,25 +72,113 @@ function systemErrorCode(error: unknown): string | undefined {
53
72
  }
54
73
 
55
74
  /**
56
- * Answers a failed request. An error with a status keeps its status and message. Anything else is
57
- * the server's trouble: a 500 that says what failed and, for a system error, its code.
75
+ * The answer to a failed request. An error with a status keeps its status and message. Anything
76
+ * else is the server's trouble: a 500 that says what failed and, for a system error, its code.
58
77
  */
59
- function fail(response: ServerResponse, error: unknown, failed: string, tooLarge: string): void {
78
+ function answerOf(error: unknown, failed: string, tooLarge: string): { status: number; message: string } {
60
79
  const status = statusOf(error);
61
80
  if (status !== undefined) {
62
- const message = status === 413 ? tooLarge : error instanceof Error && error.message ? error.message : `${failed}.`;
63
- send(response, status, { error: message });
64
- return;
81
+ return { status, message: status === 413 ? tooLarge : error instanceof Error && error.message ? error.message : `${failed}.` };
65
82
  }
66
83
  const code = systemErrorCode(error);
67
- send(response, 500, { error: code ? `${failed} (${code}).` : `${failed}.` });
84
+ return { status: 500, message: code ? `${failed} (${code}).` : `${failed}.` };
85
+ }
86
+
87
+ /** Answers a failed request with JSON (see `answerOf`). A refusal that says when to try again (a busy reader) sets `Retry-After`. */
88
+ function fail(response: ServerResponse, error: unknown, failed: string, tooLarge: string, unread?: IncomingMessage): void {
89
+ const { status, message } = answerOf(error, failed, tooLarge);
90
+ const retryAfterMs = (error as { retryAfterMs?: unknown } | null)?.retryAfterMs;
91
+ if (status === 503 && typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs) && !response.headersSent) {
92
+ response.setHeader("Retry-After", String(Math.max(1, Math.ceil(retryAfterMs / 1_000))));
93
+ }
94
+ send(response, status, { error: message }, unread);
95
+ }
96
+
97
+ /**
98
+ * An error of `ingest` as the upload answers it. A file that cannot be read is the client's 422,
99
+ * with the reason. An error with a status keeps it, and a system error is the server's 500 with its
100
+ * code. A store that failed in another way is the server's 500 too, without its message: that is
101
+ * the store's own, and may name a database host. So is a value that is not an Error, whoever threw it.
102
+ */
103
+ function ingestFailure(error: unknown): unknown {
104
+ if (statusOf(error) !== undefined || systemErrorCode(error) !== undefined) return error;
105
+ if (isStoreWriteFailure(error) || !(error instanceof Error)) return error;
106
+ return new HttpError(422, error.message);
107
+ }
108
+
109
+ /**
110
+ * Whether the client asked for the upload's progress as Server-Sent Events: its `Accept` header
111
+ * names `text/event-stream` itself, without `q=0`. A wildcard (`text/*`, or any type at all) keeps
112
+ * the JSON answer.
113
+ */
114
+ function wantsEvents(request: IncomingMessage): boolean {
115
+ const accept = request.headers.accept;
116
+ return (Array.isArray(accept) ? accept.join(",") : accept ?? "").split(",").some((range) => {
117
+ const [type, ...parameters] = range.split(";").map((part) => part.trim().toLowerCase());
118
+ if (type !== "text/event-stream") return false;
119
+ const q = parameters.map((parameter) => parameter.split("=").map((part) => part.trim())).find(([name]) => name === "q");
120
+ return q === undefined || Number(q[1]) > 0;
121
+ });
122
+ }
123
+
124
+ /**
125
+ * Ingests the upload and answers with its events as Server-Sent Events. The last one is always
126
+ * `ingest.finish` or `ingest.error`, even with a `LargeFiles` of your own whose `ingest` sends no events.
127
+ */
128
+ async function streamIngest(files: LargeFiles, input: IngestInput, response: ServerResponse, tooLarge: string): Promise<void> {
129
+ const runId = newRunId("ing");
130
+ const stream = eventStream<IngestEvent, DocumentMeta>(
131
+ (onEvent, signal) => files.ingest({ ...input, runId, onEvent, signal }),
132
+ { signal: input.signal },
133
+ );
134
+ // The error as a JSON answer would give it: the event's own may hold a store's message.
135
+ const answer = async (fallback: EventError): Promise<EventError> => {
136
+ try {
137
+ await stream.result;
138
+ return { message: fallback.message, ...(fallback.status !== undefined ? { status: fallback.status } : {}) };
139
+ } catch (error) {
140
+ const failure = ingestFailure(error);
141
+ // A file that could not be read also says why, for a page that tells it in its own words.
142
+ return { ...answerOf(failure, "Upload failed", tooLarge), ...(failure instanceof IngestError ? { code: failure.code } : {}) };
143
+ }
144
+ };
145
+ async function* events(): AsyncGenerator<IngestEvent> {
146
+ let seq = 0;
147
+ for await (const event of stream) {
148
+ seq = event.seq;
149
+ if (event.type === "ingest.error") {
150
+ yield { ...event, error: await answer(event.error) };
151
+ return;
152
+ }
153
+ yield event;
154
+ if (event.type === "ingest.finish") return;
155
+ }
156
+ // The ingest ended without a last event: a `LargeFiles` of your own whose ingest sends none.
157
+ const base = { seq: seq + 1, runId, time: Date.now() };
158
+ try {
159
+ yield { ...base, type: "ingest.finish", document: toDocumentSummary(await stream.result) };
160
+ } catch {
161
+ yield { ...base, type: "ingest.error", error: await answer({ message: "Upload failed." }) };
162
+ }
163
+ }
164
+ // Each message is the event itself, as for a question: `ingest.finish` holds the summary a 201
165
+ // answer would (`document`), `ingest.error` the message and status a JSON answer would (`error`).
166
+ await writeSseEvents(response, events());
68
167
  }
69
168
 
70
- function send(response: ServerResponse, status: number, value: unknown): void {
169
+ /**
170
+ * Answers with `value` as JSON. With `unread`, a request whose body was not read to its end (an
171
+ * upload refused as too large, or before it was read): the answer is written now, so that a client
172
+ * still sending reads it, and ended once the rest of the body is drained (see `drain`).
173
+ */
174
+ function send(response: ServerResponse, status: number, value: unknown, unread?: IncomingMessage): void {
71
175
  if (response.headersSent) return;
72
176
  response.statusCode = status;
73
177
  response.setHeader("Content-Type", "application/json; charset=utf-8");
74
- response.end(JSON.stringify(value));
178
+ const body = JSON.stringify(value);
179
+ if (!unread || unread.complete || unread.destroyed) return void response.end(body);
180
+ response.write(body);
181
+ drain(unread, response);
75
182
  }
76
183
 
77
184
  function header(request: IncomingMessage, name: string): string {
@@ -99,23 +206,58 @@ async function readBody(request: IncomingMessage, limit: number): Promise<Uint8A
99
206
  if (Number.isFinite(declared) && declared > limit) throw new HttpError(413, "");
100
207
  const chunks: Buffer[] = [];
101
208
  let size = 0;
102
- for await (const chunk of request) {
209
+ // Leaving the loop early must not destroy the request: the rest of the body is drained after
210
+ // the answer (see `drain`), which a destroyed request would not do.
211
+ for await (const chunk of request.iterator({ destroyOnReturn: false })) {
103
212
  const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);
104
213
  size += buffer.byteLength;
105
- if (size > limit) {
106
- // Stop buffering; drain the rest so the client can read the response.
107
- request.resume();
108
- throw new HttpError(413, "");
109
- }
214
+ if (size > limit) throw new HttpError(413, "");
110
215
  chunks.push(buffer);
111
216
  }
112
217
  const body = Buffer.concat(chunks);
113
218
  return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
114
219
  }
115
220
 
221
+ /**
222
+ * The most bytes of an upload's body that are read and dropped after it was answered before the
223
+ * body was read to its end (too large, no name). Past it the connection is closed.
224
+ */
225
+ const DRAIN_BYTES = 8 * 1024 * 1024;
226
+
227
+ /**
228
+ * Reads and drops the rest of a body that was answered before it was read to its end, up to
229
+ * `DRAIN_BYTES`, then ends the answer, which was written but not ended. The client, still
230
+ * sending, reads the answer and can use the connection again. Two things Node does shape this:
231
+ * it stops reading a request once its answer has ended, and its client stops sending once it has
232
+ * a whole answer (so the answer has no Content-Length, and ends only after the drain). Closing the
233
+ * connection at once instead makes some systems (Windows) reset it, and the client then never
234
+ * reads the answer. A body larger than `DRAIN_BYTES` is cut off: the answer ends, and the
235
+ * connection is closed.
236
+ */
237
+ function drain(request: IncomingMessage, response: ServerResponse): void {
238
+ let drained = 0;
239
+ const end = () => {
240
+ request.off("data", count);
241
+ if (!response.writableEnded) response.end();
242
+ };
243
+ const count = (chunk: Buffer | string) => {
244
+ drained += chunk.length;
245
+ if (drained <= DRAIN_BYTES) return;
246
+ end();
247
+ if (response.writableFinished) request.destroy();
248
+ else response.once("finish", () => request.destroy());
249
+ };
250
+ request.on("data", count);
251
+ request.once("end", end);
252
+ request.once("close", end);
253
+ request.on("error", () => {});
254
+ request.resume();
255
+ }
256
+
116
257
  /**
117
258
  * Upload, get, and delete handlers for any Node HTTP server (node:http, Express, Fastify via
118
- * `request.raw`/`reply.raw`, Next.js API routes on the Node runtime). Responses are JSON.
259
+ * `request.raw`/`reply.raw`, Next.js API routes on the Node runtime). Responses are JSON, except an upload that asks for
260
+ * `text/event-stream`: it is answered with its ingest events.
119
261
  */
120
262
  export function createDocumentHandlers(files: LargeFiles, options: DocumentHandlerOptions = {}): DocumentHandlers {
121
263
  const tooLarge = `The file is larger than the ${formatBytes(files.maxUploadBytes)} upload limit.`;
@@ -127,27 +269,50 @@ export function createDocumentHandlers(files: LargeFiles, options: DocumentHandl
127
269
  const url = new URL(request.url ?? "/", "http://localhost");
128
270
  const name = header(request, "x-file-name").trim() || url.searchParams.get("name")?.trim() || "";
129
271
  if (!name) throw new HttpError(400, "Name the file with an X-File-Name header or a ?name= query parameter.");
130
- // Who is asking comes first: a refused upload is not read into memory.
272
+ // Who is asking comes first: a refused upload is not read into memory. An owner that
273
+ // `ingest` would refuse ("", or an object such as `req.user` from JavaScript) is the server's
274
+ // mistake, answered with a 500 before the body is read. Its message says which, so that the
275
+ // operator knows where to look; it says nothing else.
131
276
  const currentOwner = await owner(request);
277
+ try {
278
+ checkOwner(currentOwner);
279
+ } catch {
280
+ const empty = typeof currentOwner === "string" || currentOwner === null;
281
+ throw new HttpError(500, empty ? "Upload failed (empty owner)." : "Upload failed (owner is not a string).");
282
+ }
132
283
  const bytes = await readBody(request, files.maxUploadBytes);
133
284
  const contentType = header(request, "content-type");
134
285
  const mimeType = header(request, "x-file-type") || (contentType && !contentType.startsWith("application/octet-stream") ? contentType : "");
286
+ // A client that goes away before the answer stops the reading of its file: nobody would
287
+ // get the document, and the server has other work.
288
+ const gone = new AbortController();
289
+ const onClose = () => {
290
+ if (!response.writableFinished) gone.abort(new Error("The upload was cancelled: the client closed the connection."));
291
+ };
292
+ response.once("close", onClose);
293
+ const input: IngestInput = {
294
+ name,
295
+ bytes,
296
+ ...(mimeType ? { mimeType } : {}),
297
+ ...(currentOwner !== undefined ? { owner: currentOwner } : {}),
298
+ signal: gone.signal,
299
+ };
135
300
  let meta;
136
301
  try {
137
- meta = await files.ingest({
138
- name,
139
- bytes,
140
- ...(mimeType ? { mimeType } : {}),
141
- ...(currentOwner !== undefined ? { owner: currentOwner } : {}),
142
- });
302
+ if (wantsEvents(request)) return await streamIngest(files, input, response, tooLarge);
303
+ meta = await files.ingest(input);
143
304
  } catch (error) {
144
- // A file that cannot be read is the client's 422. A store that fails is the server's 500.
145
- if (statusOf(error) !== undefined || systemErrorCode(error) !== undefined) throw error;
146
- throw new HttpError(422, error instanceof Error ? error.message : String(error));
305
+ throw ingestFailure(error);
306
+ } finally {
307
+ response.off("close", onClose);
147
308
  }
148
309
  send(response, 201, toDocumentSummary(meta));
149
310
  } catch (error) {
150
- fail(response, error, "Upload failed", tooLarge);
311
+ // Answered before the body was read to its end (too large, no name): the rest is drained.
312
+ fail(response, error, "Upload failed", tooLarge, request);
313
+ // An event stream that failed after its headers were sent cannot answer with a status. (An
314
+ // answer to a body still being drained is ended by `drain`.)
315
+ if (response.headersSent && !response.writableEnded && request.complete) response.end();
151
316
  }
152
317
  },
153
318
 
package/src/node/index.ts CHANGED
@@ -1,2 +1,6 @@
1
1
  export { createDocumentHandlers } from "./handlers.js";
2
2
  export type { DocumentHandlerOptions, DocumentHandlers } from "./handlers.js";
3
+ export { sseMessageOf, writeSseEvents } from "./sse.js";
4
+ export type { SseMessage, SseWriteOptions } from "./sse.js";
5
+ export { createIsolatedExtractors } from "./isolated.js";
6
+ export type { IsolatedExtractorOptions, IsolatedExtractors } from "./isolated.js";