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
@@ -1,17 +1,24 @@
1
1
  // Any Chat Completions endpoint as a model of `askWithFiles`: OpenAI, Azure OpenAI, DeepSeek,
2
2
  // LiteLLM, vLLM, Ollama, OpenRouter, Gemini's OpenAI layer. No SDK: the caller gives the URL.
3
- import { base64, parseArguments, readArguments, resolveHeaderSource, resolveSecret, unreachableReason, type HeaderSource, type SecretSource } from "../http.js";
4
- import { ModelRequestError, type ChatMessage, type ModelAdapter, type ModelMessage, type ModelReply, type ModelRequest, type ModelTextMessage, type ModelToolRound, type SendHooks, type ToolCall, type ToolTurn } from "../model.js";
3
+ import { randomUUID } from "node:crypto";
4
+ import { base64, idleWatch, noteCutReply, notJsonMessage, parseArguments, readArguments, readJson, replyEnd, resolveHeaderSource, resolveSecret, streamedReply, unreachableReason, type HeaderSource, type IdleWatch, type SecretSource } from "../http.js";
5
+ import { laterResult, ModelRequestError, type ChatMessage, type ModelAdapter, type ModelMessage, type ModelReply, type ModelRequest, type ModelTextMessage, type ModelToolRound, type SendHooks, type ToolCall, type ToolTurn } from "../model.js";
5
6
  import { completeWithinLimit, type LimitedReply } from "../output-limit.js";
6
7
  import { retryAfterMs } from "../retry.js";
7
- import { parseSseJson } from "../sse.js";
8
+ import { eventTooLongMessage, parseSseJson, SseEventTooLongError } from "../sse.js";
8
9
  import type { GenerateText, GenerateUsage, ToolDeclaration, ToolResult } from "../types.js";
9
10
 
10
11
  /** The endpoint answered with an HTTP error, or could not be reached (`status` 0). */
11
12
  export class OpenAiRequestError extends ModelRequestError {
12
- constructor(message: string, status: number, options: { retryAfterMs?: number; cause?: unknown } = {}) {
13
+ /** The request field the error is about, when the server named it (`error.param`): "max_tokens". */
14
+ readonly param?: string;
15
+ /** The server's own word for the error (`error.code`): "unsupported_parameter". */
16
+ readonly code?: string;
17
+ constructor(message: string, status: number, options: ConstructorParameters<typeof ModelRequestError>[2] & { param?: string } = {}) {
13
18
  super(message, status, options);
14
19
  this.name = "OpenAiRequestError";
20
+ if (options.param) this.param = options.param;
21
+ if (options.code) this.code = options.code;
15
22
  }
16
23
  }
17
24
 
@@ -38,8 +45,10 @@ export type OpenAiCompatibleOptions = {
38
45
  analysisBody?: ((maxOutputTokens: number) => Record<string, unknown>) | undefined;
39
46
  /**
40
47
  * The name of the output limit in a part read. `max_completion_tokens` for api.openai.com and
41
- * Azure OpenAI, whose newer models refuse the other; `max_tokens` anywhere else, where it is the
42
- * one every server knows.
48
+ * Azure OpenAI (`*.openai.azure.com`, and the `/openai/` paths of `*.cognitiveservices.azure.com`
49
+ * and `*.services.ai.azure.com`), whose newer models refuse the other; `max_tokens` anywhere
50
+ * else, where it is the one every server knows. Left out, a server that refuses the one sent
51
+ * (HTTP 400 naming it) is sent the other, which is then kept for this adapter.
43
52
  */
44
53
  maxTokensField?: "max_tokens" | "max_completion_tokens" | undefined;
45
54
  /** "system" (the default), or "developer" for an endpoint that wants the newer name. */
@@ -68,6 +77,19 @@ export type OpenAiCompatibleOptions = {
68
77
  tokenScale?: number | undefined;
69
78
  /** Milliseconds a part read may take. Defaults to 180,000. */
70
79
  timeoutMs?: number | undefined;
80
+ /**
81
+ * The longest wait, in milliseconds, for the first piece of a chat reply. Headers do not count:
82
+ * a model that thinks sends nothing until it has thought, and a reply that is not streamed comes
83
+ * whole at the end. A request that gets nothing for that long is aborted and sent again, once.
84
+ * Defaults to 600,000. 0 waits without end.
85
+ */
86
+ firstByteTimeoutMs?: number | undefined;
87
+ /**
88
+ * The longest wait, in milliseconds, between two pieces of a chat reply once it has started to
89
+ * arrive (keep-alives count). A request that gets nothing for that long is aborted and sent
90
+ * again, once, unless text of it was shown. Defaults to 300,000. 0 waits without end.
91
+ */
92
+ idleTimeoutMs?: number | undefined;
71
93
  /** Names the model in usage totals. Defaults to `model`. */
72
94
  id?: string | undefined;
73
95
  fetch?: typeof fetch | undefined;
@@ -93,13 +115,107 @@ function usageOf(usage: Json | undefined): GenerateUsage {
93
115
  };
94
116
  }
95
117
 
96
- /** The error of a response that is not OK. Gemini's layer wraps its error in an array. */
118
+ /** The status of an error event in a stream that began with 200: from its code, or from its type. */
119
+ const STATUS_OF_ERROR: Record<string, number> = {
120
+ server_error: 500, api_error: 500, internal_error: 500, internal_server_error: 500, service_unavailable: 503,
121
+ rate_limit_exceeded: 429, rate_limit_error: 429, tokens_exceeded: 429, timeout: 408, invalid_request_error: 400,
122
+ context_length_exceeded: 400, insufficient_quota: 429,
123
+ };
124
+
125
+ /**
126
+ * The HTTP status of an error that arrived inside a stream. The response itself was 200, which says
127
+ * nothing of the error: OpenAI's own is `{ type: "server_error", code: null }`. A failure the server
128
+ * did not name is its own, 500, and is sent again like one (when no text of it was shown).
129
+ */
130
+ export function streamErrorStatus(failed: unknown): number {
131
+ if (failed && typeof failed === "object") {
132
+ const { code, type } = failed as { code?: unknown; type?: unknown };
133
+ const numeric = typeof code === "number" ? code : typeof code === "string" && /^\d{3}$/.test(code) ? Number(code) : Number.NaN;
134
+ if (numeric >= 400 && numeric <= 599) return numeric;
135
+ for (const word of [type, code]) if (typeof word === "string" && STATUS_OF_ERROR[word] !== undefined) return STATUS_OF_ERROR[word]!;
136
+ }
137
+ return 500;
138
+ }
139
+
140
+ /**
141
+ * Whether a server refused the name of the output limit (`max_tokens` or `max_completion_tokens`),
142
+ * rather than its number: "Unsupported parameter: 'max_tokens' ... Use 'max_completion_tokens'
143
+ * instead", "Unrecognized request argument supplied: max_completion_tokens". Not "max_tokens is
144
+ * too large", which can name the other field too.
145
+ */
146
+ function refusesField(error: unknown, field: string): boolean {
147
+ if (!(error instanceof OpenAiRequestError) || error.status !== 400) return false;
148
+ // A server that names the field it refuses says it plainly.
149
+ if (error.param !== undefined) return error.param === field && (error.code === "unsupported_parameter" || REFUSED.test(error.message));
150
+ const message = error.message;
151
+ if (/too large|too many|maximum|at most|exceed|must be (less|at most|<)/i.test(message) || !REFUSED.test(message)) return false;
152
+ // "Unsupported parameter: 'max_tokens' ... Use 'max_completion_tokens' instead" names both: the
153
+ // one it refuses comes first. Azure's "Could not finish the message because max_tokens or model
154
+ // output limit was reached" refuses nothing.
155
+ const named = /max_completion_tokens|max_tokens/.exec(message)?.[0];
156
+ return named === field;
157
+ }
158
+
159
+ /** Words of a server that refuses a field of the request, rather than its value. */
160
+ const REFUSED = /unsupported|unrecognized|not supported|unknown (parameter|field|argument)|not permitted|not allowed|extra (inputs|fields)/i;
161
+
162
+ /**
163
+ * Adds a piece of OpenRouter's streamed `reasoning_details` to those of the turn. Pieces of one
164
+ * detail share its `index` and type: their text is joined, and their other fields (a signature, an
165
+ * ID, the encrypted data) are kept. The details stay in the order they came, and are not changed
166
+ * otherwise: they go back to the model as they were written.
167
+ */
168
+ function addReasoningDetail(details: Json[], detail: unknown): void {
169
+ if (!detail || typeof detail !== "object") return;
170
+ const piece = detail as Json;
171
+ const same = typeof piece.index === "number" ? details.find((known) => known.index === piece.index && known.type === piece.type) : undefined;
172
+ if (!same) {
173
+ details.push({ ...piece });
174
+ return;
175
+ }
176
+ for (const [key, value] of Object.entries(piece)) {
177
+ if (value === null || value === undefined) continue;
178
+ if ((key === "text" || key === "summary") && typeof value === "string" && typeof same[key] === "string") same[key] += value;
179
+ else same[key] = value;
180
+ }
181
+ }
182
+
183
+ /**
184
+ * The error of a response that is not OK. Gemini's layer wraps its error in an array. Most servers
185
+ * put it in `error`; vLLM before its OpenAI-shaped errors, SGLang and FastChat put `message`, and
186
+ * servers built on FastAPI `detail`, at the top of the body.
187
+ */
97
188
  async function failure(response: Response): Promise<OpenAiRequestError> {
98
189
  const data = await response.json().catch(() => null) as Json | Json[] | null;
99
190
  const body = Array.isArray(data) ? data[0] : data;
100
- const message = typeof body?.error === "string" ? body.error : body?.error?.message;
191
+ const nested = body?.error && typeof body.error === "object" ? body.error as Json : undefined;
192
+ const message = [typeof body?.error === "string" ? body.error : nested?.message, body?.message, detailText(body?.detail)]
193
+ .find((text): text is string => typeof text === "string" && text.length > 0);
101
194
  const wait = retryAfterMs(response.headers, body);
102
- return new OpenAiRequestError(typeof message === "string" && message ? message : `The model returned HTTP ${response.status}.`, response.status, wait === undefined ? {} : { retryAfterMs: wait });
195
+ const own = nested ?? (body && typeof body === "object" ? body : undefined);
196
+ const param = typeof own?.param === "string" ? own.param as string : undefined;
197
+ const code = typeof own?.code === "string" ? own.code as string : undefined;
198
+ return new OpenAiRequestError(message ?? `The model returned HTTP ${response.status}.`, response.status, {
199
+ ...(wait === undefined ? {} : { retryAfterMs: wait }),
200
+ ...(param ? { param } : {}),
201
+ ...(code ? { code } : {}),
202
+ });
203
+ }
204
+
205
+ /** FastAPI's `detail`: a message, or a list of problems, each with its own `msg`. */
206
+ function detailText(detail: unknown): string | undefined {
207
+ if (typeof detail === "string") return detail;
208
+ if (!Array.isArray(detail)) return undefined;
209
+ return detail.map((problem) => (typeof (problem as Json | null)?.msg === "string" ? (problem as Json).msg as string : "")).filter(Boolean).join("; ") || undefined;
210
+ }
211
+
212
+ /** An error event inside a stream that began with 200, with the server's own word for it. */
213
+ function streamFailure(failed: unknown): OpenAiRequestError {
214
+ const named = failed && typeof failed === "object" ? failed as Json : {};
215
+ return new OpenAiRequestError(typeof failed === "string" ? failed : String(named.message ?? "The model reported an error."), streamErrorStatus(failed), {
216
+ ...(typeof named.code === "string" && named.code ? { code: named.code } : {}),
217
+ ...(typeof named.param === "string" && named.param ? { param: named.param } : {}),
218
+ });
103
219
  }
104
220
 
105
221
  const textOf = (message: ModelTextMessage): string => message.parts.map((part) => part.text ?? "").filter(Boolean).join("\n\n");
@@ -110,6 +226,30 @@ function textMessage(message: ModelTextMessage): OpenAiMessage {
110
226
  return { role: message.role, content: message.parts.map((part) => (part.native !== undefined ? part.native : { type: "text", text: part.text })) };
111
227
  }
112
228
 
229
+ /**
230
+ * Turns of the user that follow each other, made one. The loop can send the question and the
231
+ * request for an answer after it with no turn between them, and some servers (DeepSeek's reasoner,
232
+ * the chat templates of Mistral and Gemma models) refuse two user turns in a row.
233
+ */
234
+ function joinUserTurns(messages: OpenAiMessage[]): OpenAiMessage[] {
235
+ const parts = (content: unknown): unknown[] => (typeof content === "string" ? (content ? [{ type: "text", text: content }] : []) : Array.isArray(content) ? content : []);
236
+ const out: OpenAiMessage[] = [];
237
+ for (const message of messages) {
238
+ const last = out.at(-1);
239
+ if (last?.role !== "user" || message.role !== "user") {
240
+ out.push(message);
241
+ continue;
242
+ }
243
+ out[out.length - 1] = {
244
+ role: "user",
245
+ content: typeof last.content === "string" && typeof message.content === "string"
246
+ ? [last.content, message.content].filter(Boolean).join("\n\n")
247
+ : [...parts(last.content), ...parts(message.content)],
248
+ };
249
+ }
250
+ return out;
251
+ }
252
+
113
253
  /** The messages of one tool round. `number` makes the IDs of calls that came without one. */
114
254
  function roundMessages(round: ModelToolRound, number: number, pdfInput: boolean): OpenAiMessage[] {
115
255
  const idOf = (call: ToolCall, index: number) => call.id ?? `call_${number}_${index + 1}`;
@@ -172,7 +312,9 @@ export function fromOpenAiMessages(history: OpenAiMessage[]): { system: string;
172
312
  */
173
313
  export function openAiToolTurns(turns: ToolTurn[]): OpenAiMessage[] {
174
314
  return turns.flatMap((turn, index) => {
175
- const answers = turn.calls.map(({ result, ...call }) => ({ call, result }));
315
+ // A call that came without an ID is given one that no round of another question has: these
316
+ // messages are kept, and sent again next to those of later questions.
317
+ const answers = turn.calls.map(({ result, ...call }) => ({ call: call.id ? call : { ...call, id: `call_${randomUUID().replaceAll("-", "").slice(0, 24)}` }, result: laterResult(result) }));
176
318
  return roundMessages({ role: "tools", calls: answers.map((answer) => answer.call), answers }, index + 1, false);
177
319
  });
178
320
  }
@@ -181,14 +323,18 @@ export function openAiToolTurns(turns: ToolTurn[]): OpenAiMessage[] {
181
323
  export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter {
182
324
  const fetchImpl = options.fetch ?? fetch;
183
325
  const url = options.url ?? `${(options.baseUrl ?? "https://api.openai.com/v1").replace(/\/+$/, "")}/chat/completions`;
184
- const official = /(^|\.)openai\.com$|\.openai\.azure\.com$/.test((() => {
326
+ const { hostname, pathname } = (() => {
185
327
  try {
186
- return new URL(url).hostname;
328
+ return new URL(url);
187
329
  } catch {
188
- return "";
330
+ return { hostname: "", pathname: "" };
189
331
  }
190
- })());
191
- const maxTokensField = options.maxTokensField ?? (official ? "max_completion_tokens" : "max_tokens");
332
+ })();
333
+ // Azure OpenAI answers on three kinds of host. On the two it shares with other models, only its `/openai/` paths are OpenAI's.
334
+ const official = /(^|\.)openai\.com$|\.openai\.azure\.com$/.test(hostname)
335
+ || (/\.(cognitiveservices\.azure\.com|services\.ai\.azure\.com)$/.test(hostname) && pathname.includes("/openai/"));
336
+ /** The name of the output limit in a part read: changed once when the server refuses it and no name was given. */
337
+ let maxTokensField = options.maxTokensField ?? (official ? "max_completion_tokens" : "max_tokens");
192
338
  const systemRole = options.systemRole ?? "system";
193
339
  const pdfInput = options.pdfInput === true;
194
340
 
@@ -200,7 +346,7 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
200
346
  const built = new WeakMap<ModelToolRound, { number: number; messages: OpenAiMessage[] }>();
201
347
  const toMessages = (messages: ModelMessage[]): OpenAiMessage[] => {
202
348
  let rounds = 0;
203
- return messages.flatMap((message) => {
349
+ return joinUserTurns(messages.flatMap((message) => {
204
350
  if (message.role !== "tools") return [textMessage(message)];
205
351
  const number = ++rounds;
206
352
  let known = built.get(message);
@@ -209,7 +355,7 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
209
355
  built.set(message, known);
210
356
  }
211
357
  return known.messages;
212
- });
358
+ }));
213
359
  };
214
360
  const bodyOf = (request: ModelRequest, stream: boolean): Json => {
215
361
  const mustAnswer = request.toolChoice === "none";
@@ -223,13 +369,13 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
223
369
  };
224
370
  };
225
371
 
226
- const post = async (body: Json, signal: AbortSignal | undefined, stopped: () => boolean): Promise<Response> => {
372
+ const post = async (body: Json, signal: AbortSignal | undefined, stopped: () => boolean, lost: (error: unknown) => OpenAiRequestError = unreachable, headers?: Record<string, string>): Promise<Response> => {
227
373
  let response: Response;
228
374
  try {
229
- response = await fetchImpl(url, { method: "POST", headers: await headersNow(), body: JSON.stringify(body), ...(signal ? { signal } : {}) });
375
+ response = await fetchImpl(url, { method: "POST", headers: headers ?? await headersNow(), body: JSON.stringify(body), ...(signal ? { signal } : {}) });
230
376
  } catch (error) {
231
377
  if (stopped()) throw error;
232
- throw new OpenAiRequestError(`The model could not be reached${unreachableReason(error)}.`, 0, { cause: error });
378
+ throw lost(error);
233
379
  }
234
380
  if (!response.ok) throw await failure(response);
235
381
  return response;
@@ -238,19 +384,36 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
238
384
  const generateText: GenerateText = ({ system, prompt, maxOutputTokens, signal, onTruncated, onUsage }) => {
239
385
  const send = async (limit: number): Promise<LimitedReply> => {
240
386
  const timeout = AbortSignal.timeout(options.timeoutMs ?? 180_000);
241
- const response = await post({
387
+ const stopped = () => Boolean(signal?.aborted) || timeout.aborted;
388
+ const body = (field: string): Json => ({
242
389
  model: options.model,
243
390
  messages: [{ role: systemRole, content: system }, { role: "user", content: prompt }],
244
- [maxTokensField]: limit,
391
+ [field]: limit,
245
392
  ...options.analysisBody?.(limit),
246
- }, signal ? AbortSignal.any([signal, timeout]) : timeout, () => Boolean(signal?.aborted) || timeout.aborted);
247
- const data = await response.json() as Json;
393
+ });
394
+ let response: Response;
395
+ // The name this request is sent with: part reads run together, and another may learn the other name meanwhile.
396
+ const sent = maxTokensField;
397
+ try {
398
+ response = await post(body(sent), signal ? AbortSignal.any([signal, timeout]) : timeout, stopped);
399
+ } catch (error) {
400
+ // A server that knows only the other name of the output limit: it is sent that one, now and from now on.
401
+ if (options.maxTokensField !== undefined || !refusesField(error, sent)) throw error;
402
+ const other = sent === "max_tokens" ? "max_completion_tokens" : "max_tokens";
403
+ if (maxTokensField === sent) maxTokensField = other;
404
+ response = await post(body(other), signal ? AbortSignal.any([signal, timeout]) : timeout, stopped);
405
+ }
406
+ const data = await readJson<Json>(response, stopped, unreachable, undefined, (error) => new OpenAiRequestError(notJsonMessage("The model's", response), response.status, { kind: "invalid", cause: error }));
248
407
  const used = usageOf(data.usage);
249
408
  onUsage?.(used);
250
409
  const choice = data.choices?.[0];
410
+ // DeepSeek stops a reply when its servers run short: that is the server's failure, sent again.
411
+ if (choice?.finish_reason === "insufficient_system_resource") throw interrupted();
251
412
  return {
252
413
  text: contentText(choice?.message?.content),
253
414
  cutOff: choice?.finish_reason === "length",
415
+ // Stopped by the content filter before its end: what it wrote is not all there is.
416
+ stopped: choice?.finish_reason === "content_filter",
254
417
  ...(typeof choice?.finish_reason === "string" ? { reason: choice.finish_reason } : {}),
255
418
  thoughts: used.thoughtTokens ?? 0,
256
419
  };
@@ -272,18 +435,53 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
272
435
 
273
436
  async send(request: ModelRequest, hooks: SendHooks = {}): Promise<ModelReply> {
274
437
  const stream = Boolean(hooks.onText) && options.stream !== false;
275
- const response = await post(bodyOf(request, stream), hooks.signal, () => Boolean(hooks.signal?.aborted));
438
+ // A key or token is fetched before the watch starts: the time that takes is not the model's.
439
+ const headers = await headersNow();
440
+ const watch = idleWatch(hooks.signal, { firstByteTimeoutMs: options.firstByteTimeoutMs, idleTimeoutMs: options.idleTimeoutMs });
441
+ // A request the watch aborted got nothing back for the whole wait: that is no failed connection.
442
+ const lost = (error: unknown) => (watch.expired ? silent(watch.waitedMs) : unreachable(error));
443
+ try {
444
+ // The headers are no piece of the reply: a server may send them at once and then think.
445
+ const response = await post(bodyOf(request, stream), watch.signal, () => Boolean(hooks.signal?.aborted), lost, headers);
446
+ return await readReply(response, stream, hooks, watch, lost);
447
+ } finally {
448
+ watch.stop();
449
+ }
450
+ },
451
+ };
452
+
453
+ /** The reply of a request that was answered: streamed, or in one piece. */
454
+ async function readReply(answer: Response, stream: boolean, hooks: SendHooks, watch: IdleWatch, lost: (error: unknown) => OpenAiRequestError): Promise<ModelReply> {
455
+ {
276
456
  let message: Json;
277
457
  let finish: unknown;
278
458
  let usage: Json | undefined;
279
459
  let text = "";
280
- if (stream && response.body && (response.headers.get("content-type") ?? "").includes("text/event-stream")) {
460
+ // A body that is no JSON (a gateway's page) is not the model's reply, and is not sent again.
461
+ const notJson = (error: unknown) => new OpenAiRequestError(notJsonMessage("The model's", answer), answer.status, { kind: "invalid", cause: error });
462
+ let response = answer;
463
+ let events = false;
464
+ if (stream && answer.body) {
465
+ try {
466
+ ({ events, response } = await streamedReply(answer, watch));
467
+ } catch (error) {
468
+ if (hooks.signal?.aborted) throw error;
469
+ throw noteCutReply(lost(error));
470
+ }
471
+ }
472
+ if (events && response.body) {
281
473
  let reasoning = "";
474
+ let reasoningText = "";
475
+ let refusal = "";
476
+ const details: Json[] = [];
282
477
  const toolCalls: Json[] = [];
478
+ let ended = false;
479
+ // "[DONE]" ends the reply: a server that leaves the connection open after it is not waited for.
480
+ const end = replyEnd(watch);
283
481
  try {
284
- for await (const chunk of parseSseJson<Json>(response.body)) {
482
+ for await (const chunk of parseSseJson<Json>(response.body, { onData: watch.pulse, onDone: () => { ended = true; end.reached(); }, signal: end.signal })) {
285
483
  const failed = (Array.isArray(chunk) ? chunk[0] : chunk)?.error;
286
- if (failed) throw new OpenAiRequestError(typeof failed === "string" ? failed : String(failed.message ?? "The model reported an error."), typeof failed.code === "number" ? failed.code : response.status);
484
+ if (failed) throw streamFailure(failed);
287
485
  if (chunk.usage) usage = chunk.usage as Json;
288
486
  const choice = chunk.choices?.[0] as Json | undefined;
289
487
  if (!choice) continue;
@@ -294,6 +492,11 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
294
492
  hooks.onText?.(piece);
295
493
  }
296
494
  if (typeof delta.reasoning_content === "string") reasoning += delta.reasoning_content;
495
+ // What a non-streamed reply holds in fields of its own: a refusal, and the reasoning of
496
+ // OpenRouter, whose details (a thought signature among them) must go back with the turn.
497
+ if (typeof delta.refusal === "string") refusal += delta.refusal;
498
+ if (typeof delta.reasoning === "string") reasoningText += delta.reasoning;
499
+ if (Array.isArray(delta.reasoning_details)) for (const detail of delta.reasoning_details as unknown[]) addReasoningDetail(details, detail);
297
500
  for (const part of (Array.isArray(delta.tool_calls) ? delta.tool_calls : []) as Json[]) {
298
501
  // A call arrives in pieces under its index: first its ID and name, then its arguments, a few characters at a time.
299
502
  const at = typeof part.index === "number" ? part.index : part.id || toolCalls.length === 0 ? toolCalls.length : toolCalls.length - 1;
@@ -301,45 +504,110 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
301
504
  for (const [key, value] of Object.entries(part)) {
302
505
  if (key !== "index" && key !== "function" && value !== undefined && value !== null && !(key === "id" && call.id)) call[key] = value;
303
506
  }
304
- if (typeof part.function?.name === "string") call.function.name += part.function.name;
507
+ // The name comes whole in the first piece of a call. A server that sends it again with
508
+ // each piece does not make it longer; one that sends it in pieces does.
509
+ const name = part.function?.name;
510
+ if (typeof name === "string" && name !== call.function.name) call.function.name += name;
305
511
  if (typeof part.function?.arguments === "string") call.function.arguments += part.function.arguments;
306
512
  }
307
513
  finish = choice.finish_reason ?? finish;
308
514
  }
309
515
  } catch (error) {
310
- if (hooks.signal?.aborted || error instanceof OpenAiRequestError) throw error;
311
- // The connection went while the answer was on its way.
312
- throw new OpenAiRequestError(`The model could not be reached${unreachableReason(error)}.`, 0, { cause: error });
516
+ // The reply ended with "[DONE]", and the connection then stayed open, or broke rather than
517
+ // end: what came before it is whole.
518
+ const whole = end.left(error) || (end.whole && !hooks.signal?.aborted && !(error instanceof OpenAiRequestError));
519
+ if (!whole) {
520
+ if (hooks.signal?.aborted || error instanceof OpenAiRequestError) throw error;
521
+ // An event too long to read would come again: it is not sent again, like a page in the reply's place.
522
+ if (error instanceof SseEventTooLongError) throw new OpenAiRequestError(eventTooLongMessage("The model's", error), answer.status, { kind: "invalid", cause: error });
523
+ // The connection went while the answer was on its way, or nothing came for the whole wait.
524
+ throw noteCutReply(lost(error));
525
+ }
526
+ } finally {
527
+ end.dispose();
313
528
  }
529
+ // A stream ends with a reason for its end, and with "[DONE]". One that closed with neither
530
+ // was cut off on its way (a proxy, a dropped connection): it is not a whole reply, and is
531
+ // sent again like a connection that failed, unless text of it was shown.
532
+ if (finish === undefined && !ended) throw noteCutReply(new OpenAiRequestError("The model's reply ended before it was complete.", 0));
314
533
  const calls = toolCalls.filter(Boolean);
315
- message = { role: "assistant", content: text || null, ...(reasoning ? { reasoning_content: reasoning } : {}), ...(calls.length > 0 ? { tool_calls: calls } : {}) };
534
+ message = {
535
+ role: "assistant",
536
+ content: text || null,
537
+ ...(refusal ? { refusal } : {}),
538
+ ...(reasoning ? { reasoning_content: reasoning } : {}),
539
+ ...(reasoningText ? { reasoning: reasoningText } : {}),
540
+ ...(details.length > 0 ? { reasoning_details: details } : {}),
541
+ ...(calls.length > 0 ? { tool_calls: calls } : {}),
542
+ };
543
+ // A refusal is what the model has to say to the user, as it is without streaming.
544
+ if (!text && refusal) {
545
+ text = refusal;
546
+ hooks.onText?.(refusal);
547
+ }
316
548
  } else {
317
549
  // In one piece: no streaming was asked for, or the server answered without it.
318
- const data = await response.json() as Json;
550
+ const data = await readJson<Json>(response, () => Boolean(hooks.signal?.aborted), lost, watch, notJson);
319
551
  const choice = data.choices?.[0] as Json | undefined;
320
552
  message = (choice?.message ?? { role: "assistant", content: null }) as Json;
321
553
  finish = choice?.finish_reason;
322
554
  usage = data.usage as Json | undefined;
555
+ // The whole reply is in hand: one that the server stopped is sent again before any of it is shown.
556
+ if (finish === "insufficient_system_resource") throw interrupted();
323
557
  // A refusal is what the model has to say to the user, in a field of its own.
324
558
  text = contentText(message.content) || (typeof message.refusal === "string" ? message.refusal : "");
325
559
  if (text) hooks.onText?.(text);
326
560
  }
561
+ // DeepSeek stops a reply when its servers run short: what came of it is not the model's whole
562
+ // turn. That is the server's failure, sent again unless text of it was shown.
563
+ if (finish === "insufficient_system_resource") throw interrupted();
327
564
  // Cut off at the output limit with a call half-written: the call is answered, not run.
328
565
  const cutOff = finish === "length" ? "This call was cut off at the output limit before its arguments were complete, and was not run. Send it again." : undefined;
329
566
  const calls: ToolCall[] = (Array.isArray(message.tool_calls) ? message.tool_calls as Json[] : [])
330
567
  .filter((call) => typeof call?.function?.name === "string" && call.function.name)
331
568
  .map((call) => {
332
- const { args, problem = cutOff } = readArguments(call.function.arguments);
333
- return { ...(typeof call.id === "string" && call.id ? { id: call.id } : {}), name: call.function.name as string, args, ...(problem ? { problem } : {}) };
569
+ const read = readArguments(call.function.arguments);
570
+ // Arguments that are not a JSON object go back as none, and so do arguments that are
571
+ // empty: a server that reads every call of the conversation (vLLM before 0.29) refuses
572
+ // the next request when one is not JSON.
573
+ const written = call.function.arguments;
574
+ if (read.problem || typeof written !== "string" || !written.trim()) call.function = { ...call.function, arguments: read.problem ? "{}" : JSON.stringify(read.args) };
575
+ const problem = read.problem ?? cutOff;
576
+ return { ...(typeof call.id === "string" && call.id ? { id: call.id } : {}), name: call.function.name as string, args: read.args, ...(problem ? { problem } : {}) };
334
577
  });
578
+ const kind = finishOfOpenAi(finish);
335
579
  return {
336
580
  text,
337
581
  calls,
338
582
  raw: message,
339
583
  ...(typeof finish === "string" ? { finishReason: finish } : {}),
584
+ ...(kind ? { finish: kind } : {}),
340
585
  ...(finish === "content_filter" && !text && calls.length === 0 ? { blockReason: "content_filter" } : {}),
341
586
  ...(usage ? { usage: usageOf(usage), providerUsage: usage } : {}),
342
587
  };
343
- },
344
- };
588
+ }
589
+ }
590
+ }
591
+
592
+ /** A request that got no answer: the reason, without the stack of the HTTP client. */
593
+ function unreachable(error: unknown): OpenAiRequestError {
594
+ return new OpenAiRequestError(`The model could not be reached${unreachableReason(error)}.`, 0, { cause: error });
595
+ }
596
+
597
+ /** A request that got nothing back for the whole wait of its `IdleWatch`. */
598
+ function silent(waitMs: number): OpenAiRequestError {
599
+ return new OpenAiRequestError(`The model sent nothing for ${Math.round(waitMs / 1_000)} s.`, 0, { kind: "timeout" });
600
+ }
601
+
602
+ /** A reply the server stopped because it ran short (DeepSeek's `insufficient_system_resource`). */
603
+ function interrupted(): OpenAiRequestError {
604
+ return new OpenAiRequestError("The model's server stopped the reply: it ran short of resources.", 503);
605
+ }
606
+
607
+ /** `finish_reason` in the terms of `ModelReply.finish`. Undefined for a reason it does not know. */
608
+ function finishOfOpenAi(reason: unknown): ModelReply["finish"] {
609
+ if (reason === "stop" || reason === "tool_calls" || reason === "function_call") return "complete";
610
+ if (reason === "length") return "cut";
611
+ if (reason === "content_filter") return "filtered";
612
+ return undefined;
345
613
  }
@@ -26,11 +26,31 @@ function remember(model: string, limit: number): void {
26
26
  learnedLimits.set(model, limit);
27
27
  }
28
28
 
29
+ /**
30
+ * The errors `completeWithinLimit` threw for a reply with no text, with why the reply stopped, in
31
+ * the provider's word ("" when it did not say).
32
+ */
33
+ const noTextErrors = new WeakMap<object, string>();
34
+
35
+ /**
36
+ * Why a reply had no text, when this error is the one `completeWithinLimit` throws for it: the
37
+ * provider's word for why it stopped ("SAFETY", "refusal"), or "" when it did not say. Undefined
38
+ * for any other error. The message of that error is the package's own.
39
+ */
40
+ export function noTextReason(error: unknown): string | undefined {
41
+ return typeof error === "object" && error !== null ? noTextErrors.get(error) : undefined;
42
+ }
43
+
29
44
  /** A reply to a plain completion. */
30
45
  export type LimitedReply = {
31
46
  text: string;
32
47
  /** True when the model stopped because it reached the output limit. */
33
48
  cutOff: boolean;
49
+ /**
50
+ * True when the provider stopped the reply before its end for another reason (its safety
51
+ * filters): what it wrote is kept, and said to be incomplete, as a reply cut off at the limit is.
52
+ */
53
+ stopped?: boolean;
34
54
  /** Why it stopped, in the provider's word, for the message when there is no text. */
35
55
  reason?: string;
36
56
  /** Tokens the model spent thinking, when the provider says. */
@@ -41,8 +61,9 @@ export type LimitedReply = {
41
61
  * Sends a completion with an output limit, and once more with `THINKING_OUTPUT_TOKENS` when the
42
62
  * reply was cut off with nothing written, or with half the limit or more gone on thoughts. What
43
63
  * was learned is kept under `model` (a URL, or a URL and a model name): later requests start with
44
- * the larger limit, and a model that refused it (HTTP 400) is not asked for it again. Requests
45
- * that arrive while the first one to a model is on its way wait for it.
64
+ * the larger limit, and a model that refused it (HTTP 400, but not for a request too large for the
65
+ * window with it) is not asked for it again, nor is one whose window, or allowance a minute, is no
66
+ * larger than that limit. Requests that arrive while the first one to a model is on its way wait for it.
46
67
  */
47
68
  export async function completeWithinLimit(model: string, maxOutputTokens: number, send: (limit: number) => Promise<LimitedReply>, options: {
48
69
  signal?: AbortSignal | undefined;
@@ -83,15 +104,30 @@ export async function completeWithinLimit(model: string, maxOutputTokens: number
83
104
  } catch (error) {
84
105
  if (signal?.aborted) throw error;
85
106
  // A model or a gateway that refuses the larger limit (HTTP 400) is not asked for it again.
86
- // Any other failure says nothing about the limit: the next request starts with it. What
87
- // the first reply had is kept; with nothing in it, this error is the one to report.
88
- if ((error as { status?: unknown } | null)?.status === 400) remember(model, 0);
107
+ // A refusal of this request as too large for the window with that limit is no such refusal,
108
+ // unless the window is no larger than the limit itself: a smaller part may fit. Nothing is
109
+ // learned from it, and the next request starts as this one did. A request too large for
110
+ // what the provider allows in a minute (OpenAI's or Groq's TPM, HTTP 429 or 413) is too
111
+ // large the same way, with that allowance as the window. Any other failure says nothing
112
+ // about the limit: the next request starts with it. What the first reply had is kept; with
113
+ // nothing in it, this error is the one to report.
114
+ const { status, kind, limitTokens } = (error ?? {}) as { status?: unknown; kind?: unknown; limitTokens?: unknown };
115
+ if (status === 400 || kind === "context_overflow") {
116
+ const tooLarge = kind === "context_overflow" && !(typeof limitTokens === "number" && limitTokens <= THINKING_OUTPUT_TOKENS);
117
+ if (!tooLarge) remember(model, 0);
118
+ else if (learnedLimits.get(model) === THINKING_OUTPUT_TOKENS) learnedLimits.delete(model);
119
+ }
89
120
  if (!reply.text.trim()) throw error;
90
121
  }
91
122
  }
92
- if (!reply.text.trim()) throw new Error(`The model returned no text${reply.reason ? ` (${reply.reason})` : ""}.`);
93
- // The text stops mid-list when the output limit is reached. Say so instead of passing it off as complete.
94
- if (reply.cutOff) options.onTruncated?.();
123
+ if (!reply.text.trim()) {
124
+ const error = new Error(`The model returned no text${reply.reason ? ` (${reply.reason})` : ""}.`);
125
+ noTextErrors.set(error, reply.reason ?? "");
126
+ throw error;
127
+ }
128
+ // The text stops mid-list when the output limit is reached, or when a filter stopped it. Say so
129
+ // instead of passing it off as complete.
130
+ if (reply.cutOff || reply.stopped) options.onTruncated?.();
95
131
  return reply.text;
96
132
  } finally {
97
133
  learned();
package/src/pause.ts ADDED
@@ -0,0 +1,41 @@
1
+ /** Lets other work on the server run (an answer streaming to another user) before going on. */
2
+ export const pause = () => new Promise<void>((resolve) => setImmediate(resolve));
3
+
4
+ let turn: Promise<void> = Promise.resolve();
5
+
6
+ /**
7
+ * `pause`, taken in turns: each caller waits for the pause before it, so one slice of work runs in
8
+ * a turn of the event loop. Ten uploads that pause at once then hold the server for one slice
9
+ * between two turns, not ten.
10
+ */
11
+ export const fairPause = (): Promise<void> => (turn = turn.then(pause));
12
+
13
+ /** Work done between two pauses of a long loop, in milliseconds: short enough that nobody waits. */
14
+ const SLICE_MS = 12;
15
+
16
+ /**
17
+ * Splits a long piece of synchronous work into slices, so that one upload does not hold the whole
18
+ * server: call `maybePause()` now and then (every few thousand items), and it pauses once the
19
+ * current slice has run for about 12 ms. It also stops the work when `signal` is aborted.
20
+ */
21
+ export class TimeSlicer {
22
+ private sliceStart = performance.now();
23
+
24
+ constructor(private readonly signal?: AbortSignal) {}
25
+
26
+ /** Whether the current slice has run its time: `maybePause` would pause now. */
27
+ get due(): boolean {
28
+ return performance.now() - this.sliceStart >= SLICE_MS;
29
+ }
30
+
31
+ async maybePause(): Promise<void> {
32
+ if (this.due) await this.pauseNow();
33
+ }
34
+
35
+ /** Pauses, then starts a new slice. Throws the reason of `signal` when it was aborted meanwhile. */
36
+ async pauseNow(): Promise<void> {
37
+ await fairPause();
38
+ this.signal?.throwIfAborted();
39
+ this.sliceStart = performance.now();
40
+ }
41
+ }