llm-large-files 0.9.0 → 0.10.1

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 (222) hide show
  1. package/CHANGELOG.md +500 -0
  2. package/README.md +13 -7
  3. package/dist/access.d.ts +45 -3
  4. package/dist/access.d.ts.map +1 -1
  5. package/dist/access.js +106 -3
  6. package/dist/access.js.map +1 -1
  7. package/dist/aggregate.d.ts +6 -0
  8. package/dist/aggregate.d.ts.map +1 -1
  9. package/dist/aggregate.js +86 -13
  10. package/dist/aggregate.js.map +1 -1
  11. package/dist/analyze.d.ts +4 -0
  12. package/dist/analyze.d.ts.map +1 -1
  13. package/dist/analyze.js +2 -2
  14. package/dist/analyze.js.map +1 -1
  15. package/dist/answer-info.d.ts +26 -0
  16. package/dist/answer-info.d.ts.map +1 -0
  17. package/dist/answer-info.js +32 -0
  18. package/dist/answer-info.js.map +1 -0
  19. package/dist/anthropic/adapter.d.ts +5 -1
  20. package/dist/anthropic/adapter.d.ts.map +1 -1
  21. package/dist/anthropic/adapter.js +35 -10
  22. package/dist/anthropic/adapter.js.map +1 -1
  23. package/dist/ask.d.ts +115 -14
  24. package/dist/ask.d.ts.map +1 -1
  25. package/dist/ask.js +572 -103
  26. package/dist/ask.js.map +1 -1
  27. package/dist/citations.d.ts +36 -0
  28. package/dist/citations.d.ts.map +1 -0
  29. package/dist/citations.js +298 -0
  30. package/dist/citations.js.map +1 -0
  31. package/dist/error-info.d.ts +13 -0
  32. package/dist/error-info.d.ts.map +1 -1
  33. package/dist/error-info.js +37 -1
  34. package/dist/error-info.js.map +1 -1
  35. package/dist/errors.d.ts +3 -1
  36. package/dist/errors.d.ts.map +1 -1
  37. package/dist/errors.js +3 -1
  38. package/dist/errors.js.map +1 -1
  39. package/dist/events.d.ts +27 -8
  40. package/dist/events.d.ts.map +1 -1
  41. package/dist/events.js.map +1 -1
  42. package/dist/evidence.d.ts.map +1 -1
  43. package/dist/evidence.js +21 -2
  44. package/dist/evidence.js.map +1 -1
  45. package/dist/extract.d.ts.map +1 -1
  46. package/dist/extract.js +6 -1
  47. package/dist/extract.js.map +1 -1
  48. package/dist/gemini/adapter.d.ts +35 -4
  49. package/dist/gemini/adapter.d.ts.map +1 -1
  50. package/dist/gemini/adapter.js +68 -29
  51. package/dist/gemini/adapter.js.map +1 -1
  52. package/dist/gemini/chat.d.ts +28 -55
  53. package/dist/gemini/chat.d.ts.map +1 -1
  54. package/dist/gemini/chat.js +20 -27
  55. package/dist/gemini/chat.js.map +1 -1
  56. package/dist/gemini/endpoints.d.ts +59 -11
  57. package/dist/gemini/endpoints.d.ts.map +1 -1
  58. package/dist/gemini/endpoints.js +33 -7
  59. package/dist/gemini/endpoints.js.map +1 -1
  60. package/dist/gemini/errors.d.ts +39 -5
  61. package/dist/gemini/errors.d.ts.map +1 -1
  62. package/dist/gemini/errors.js +70 -9
  63. package/dist/gemini/errors.js.map +1 -1
  64. package/dist/gemini/generate.d.ts +53 -2
  65. package/dist/gemini/generate.d.ts.map +1 -1
  66. package/dist/gemini/generate.js +100 -50
  67. package/dist/gemini/generate.js.map +1 -1
  68. package/dist/gemini/index.d.ts +3 -3
  69. package/dist/gemini/index.d.ts.map +1 -1
  70. package/dist/http.d.ts +41 -3
  71. package/dist/http.d.ts.map +1 -1
  72. package/dist/http.js +40 -2
  73. package/dist/http.js.map +1 -1
  74. package/dist/index.d.ts +7 -5
  75. package/dist/index.d.ts.map +1 -1
  76. package/dist/index.js +4 -2
  77. package/dist/index.js.map +1 -1
  78. package/dist/ingest.d.ts +9 -1
  79. package/dist/ingest.d.ts.map +1 -1
  80. package/dist/ingest.js +50 -25
  81. package/dist/ingest.js.map +1 -1
  82. package/dist/library.d.ts +129 -2
  83. package/dist/library.d.ts.map +1 -1
  84. package/dist/library.js +224 -149
  85. package/dist/library.js.map +1 -1
  86. package/dist/map-reduce.d.ts +176 -10
  87. package/dist/map-reduce.d.ts.map +1 -1
  88. package/dist/map-reduce.js +804 -58
  89. package/dist/map-reduce.js.map +1 -1
  90. package/dist/model.d.ts +36 -4
  91. package/dist/model.d.ts.map +1 -1
  92. package/dist/model.js +17 -1
  93. package/dist/model.js.map +1 -1
  94. package/dist/node/handlers.d.ts +29 -8
  95. package/dist/node/handlers.d.ts.map +1 -1
  96. package/dist/node/handlers.js +148 -126
  97. package/dist/node/handlers.js.map +1 -1
  98. package/dist/node/index.d.ts +1 -1
  99. package/dist/node/index.d.ts.map +1 -1
  100. package/dist/node/index.js.map +1 -1
  101. package/dist/node/ingest-child.js +2 -2
  102. package/dist/node/ingest-child.js.map +1 -1
  103. package/dist/node/spool.d.ts +9 -5
  104. package/dist/node/spool.d.ts.map +1 -1
  105. package/dist/node/spool.js +28 -15
  106. package/dist/node/spool.js.map +1 -1
  107. package/dist/node/sse.d.ts +6 -5
  108. package/dist/node/sse.d.ts.map +1 -1
  109. package/dist/node/sse.js +8 -7
  110. package/dist/node/sse.js.map +1 -1
  111. package/dist/openai/adapter.d.ts +5 -1
  112. package/dist/openai/adapter.d.ts.map +1 -1
  113. package/dist/openai/adapter.js +53 -12
  114. package/dist/openai/adapter.js.map +1 -1
  115. package/dist/output-limit.d.ts +2 -1
  116. package/dist/output-limit.d.ts.map +1 -1
  117. package/dist/output-limit.js +5 -2
  118. package/dist/output-limit.js.map +1 -1
  119. package/dist/pdf-outline.d.ts +71 -0
  120. package/dist/pdf-outline.d.ts.map +1 -0
  121. package/dist/pdf-outline.js +414 -0
  122. package/dist/pdf-outline.js.map +1 -0
  123. package/dist/plan.d.ts +137 -7
  124. package/dist/plan.d.ts.map +1 -1
  125. package/dist/plan.js +248 -26
  126. package/dist/plan.js.map +1 -1
  127. package/dist/prepare.d.ts +50 -0
  128. package/dist/prepare.d.ts.map +1 -0
  129. package/dist/prepare.js +207 -0
  130. package/dist/prepare.js.map +1 -0
  131. package/dist/ranged.d.ts +2 -1
  132. package/dist/ranged.d.ts.map +1 -1
  133. package/dist/ranged.js +16 -3
  134. package/dist/ranged.js.map +1 -1
  135. package/dist/search.d.ts +7 -0
  136. package/dist/search.d.ts.map +1 -1
  137. package/dist/search.js +72 -10
  138. package/dist/search.js.map +1 -1
  139. package/dist/stores.d.ts +6 -0
  140. package/dist/stores.d.ts.map +1 -1
  141. package/dist/stores.js +82 -11
  142. package/dist/stores.js.map +1 -1
  143. package/dist/tools.d.ts +22 -2
  144. package/dist/tools.d.ts.map +1 -1
  145. package/dist/tools.js +323 -76
  146. package/dist/tools.js.map +1 -1
  147. package/dist/types.d.ts +49 -1
  148. package/dist/types.d.ts.map +1 -1
  149. package/dist/whole-cost.d.ts +37 -0
  150. package/dist/whole-cost.d.ts.map +1 -0
  151. package/dist/whole-cost.js +46 -0
  152. package/dist/whole-cost.js.map +1 -0
  153. package/docs/README.md +4 -0
  154. package/docs/guides/anthropic.md +5 -2
  155. package/docs/guides/conversations.md +1 -1
  156. package/docs/guides/costs-and-limits.md +133 -36
  157. package/docs/guides/deployment.md +106 -13
  158. package/docs/guides/errors-and-reliability.md +158 -45
  159. package/docs/guides/explorer-model.md +4 -1
  160. package/docs/guides/openai-compatible.md +47 -7
  161. package/docs/guides/own-adapter-and-loop.md +33 -6
  162. package/docs/guides/pdfs.md +96 -7
  163. package/docs/guides/storage.md +46 -3
  164. package/docs/guides/testing.md +71 -0
  165. package/docs/guides/vertex-and-gemini.md +159 -50
  166. package/docs/guides/web-app.md +10 -6
  167. package/docs/how-it-works.md +120 -22
  168. package/docs/measurements.md +172 -5
  169. package/docs/publishing.md +76 -4
  170. package/docs/reference/anthropic.md +12 -7
  171. package/docs/reference/ask.md +264 -35
  172. package/docs/reference/errors-and-retries.md +30 -2
  173. package/docs/reference/events.md +27 -10
  174. package/docs/reference/gemini.md +189 -68
  175. package/docs/reference/library.md +190 -23
  176. package/docs/reference/node.md +51 -17
  177. package/docs/reference/openai.md +21 -10
  178. package/docs/reference/tools.md +273 -26
  179. package/docs/security.md +101 -12
  180. package/docs/troubleshooting.md +14 -12
  181. package/docs/upgrading-0.10.md +484 -0
  182. package/package.json +5 -1
  183. package/src/access.ts +127 -4
  184. package/src/aggregate.ts +92 -14
  185. package/src/analyze.ts +2 -2
  186. package/src/answer-info.ts +45 -0
  187. package/src/anthropic/adapter.ts +40 -11
  188. package/src/ask.ts +646 -106
  189. package/src/citations.ts +301 -0
  190. package/src/error-info.ts +36 -1
  191. package/src/errors.ts +3 -1
  192. package/src/events.ts +31 -7
  193. package/src/evidence.ts +21 -2
  194. package/src/extract.ts +6 -1
  195. package/src/gemini/adapter.ts +99 -32
  196. package/src/gemini/chat.ts +53 -82
  197. package/src/gemini/endpoints.ts +89 -16
  198. package/src/gemini/errors.ts +74 -11
  199. package/src/gemini/generate.ts +147 -57
  200. package/src/gemini/index.ts +3 -3
  201. package/src/http.ts +65 -4
  202. package/src/index.ts +7 -5
  203. package/src/ingest.ts +58 -27
  204. package/src/library.ts +336 -142
  205. package/src/map-reduce.ts +855 -67
  206. package/src/model.ts +44 -4
  207. package/src/node/handlers.ts +159 -118
  208. package/src/node/index.ts +1 -0
  209. package/src/node/ingest-child.ts +2 -2
  210. package/src/node/spool.ts +28 -14
  211. package/src/node/sse.ts +8 -7
  212. package/src/openai/adapter.ts +56 -13
  213. package/src/output-limit.ts +5 -2
  214. package/src/pdf-outline.ts +400 -0
  215. package/src/plan.ts +287 -36
  216. package/src/prepare.ts +253 -0
  217. package/src/ranged.ts +16 -3
  218. package/src/search.ts +69 -13
  219. package/src/stores.ts +76 -11
  220. package/src/tools.ts +327 -75
  221. package/src/types.ts +45 -1
  222. package/src/whole-cost.ts +64 -0
@@ -1,7 +1,7 @@
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
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";
4
+ import { base64, idleWatch, noteCutReply, notJsonMessage, parseArguments, partTimer, readArguments, readJson, replyEnd, resolveHeaderSource, resolveSecret, streamedReply, unreachableReason, until, waitText, type HeaderSource, type IdleWatch, type PartTimer, type SecretSource } from "../http.js";
5
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";
6
6
  import { completeWithinLimit, type LimitedReply } from "../output-limit.js";
7
7
  import { retryAfterMs } from "../retry.js";
@@ -75,7 +75,11 @@ export type OpenAiCompatibleOptions = {
75
75
  pageTokens?: number | undefined;
76
76
  /** This model's tokens for one token of the library's estimate. Defaults to 1. */
77
77
  tokenScale?: number | undefined;
78
- /** Milliseconds a part read may take. Defaults to 180,000. */
78
+ /**
79
+ * Milliseconds a part read may take, its whole reply included. Defaults to 180,000; 0 sets none
80
+ * (since 0.10.0). A part past it is an `OpenAiRequestError` of kind "timeout" and status 0 (since
81
+ * 0.10.0; before, the abort of the timer), which a whole-file read sends again once.
82
+ */
79
83
  timeoutMs?: number | undefined;
80
84
  /**
81
85
  * The longest wait, in milliseconds, for the first piece of a chat reply. Headers do not count:
@@ -312,6 +316,9 @@ export function fromOpenAiMessages(history: OpenAiMessage[]): { system: string;
312
316
  return { system: system.join("\n\n"), messages };
313
317
  }
314
318
 
319
+ /** An ID for a call that came without one: no round of another question has it. */
320
+ const newCallId = (): string => `call_${randomUUID().replaceAll("-", "").slice(0, 24)}`;
321
+
315
322
  /**
316
323
  * The tool rounds a question returned (`AskResult.toolTurns`) as Chat Completions messages, for an
317
324
  * application that keeps its history in that form: put them between the question and its answer.
@@ -320,7 +327,7 @@ export function openAiToolTurns(turns: ToolTurn[]): OpenAiMessage[] {
320
327
  return turns.flatMap((turn, index) => {
321
328
  // A call that came without an ID is given one that no round of another question has: these
322
329
  // messages are kept, and sent again next to those of later questions.
323
- const answers = turn.calls.map(({ result, ...call }) => ({ call: call.id ? call : { ...call, id: `call_${randomUUID().replaceAll("-", "").slice(0, 24)}` }, result: laterResult(result) }));
330
+ const answers = turn.calls.map(({ result, ...call }) => ({ call: call.id ? call : { ...call, id: newCallId() }, result: laterResult(result) }));
324
331
  return roundMessages({ role: "tools", calls: answers.map((answer) => answer.call), answers }, index + 1, false);
325
332
  });
326
333
  }
@@ -375,10 +382,15 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
375
382
  };
376
383
  };
377
384
 
378
- const post = async (body: Json, signal: AbortSignal | undefined, stopped: () => boolean, lost: (error: unknown) => OpenAiRequestError = unreachable, headers?: Record<string, string>): Promise<Response> => {
385
+ /**
386
+ * Sends a request. A `bounded` one (a part read, whose time limit is its signal) stops waiting
387
+ * when the signal aborts, even for a fetch that does not stop then itself.
388
+ */
389
+ const post = async (body: Json, signal: AbortSignal | undefined, stopped: () => boolean, lost: (error: unknown) => OpenAiRequestError = unreachable, headers?: Record<string, string>, bounded = false): Promise<Response> => {
379
390
  let response: Response;
380
391
  try {
381
- response = await fetchImpl(url, { method: "POST", headers: headers ?? await headersNow(), body: JSON.stringify(body), ...(signal ? { signal } : {}) });
392
+ const sent = fetchImpl(url, { method: "POST", headers: headers ?? await headersNow(), body: JSON.stringify(body), ...(signal ? { signal } : {}) });
393
+ response = await (bounded ? until(sent, signal) : sent);
382
394
  } catch (error) {
383
395
  if (stopped()) throw error;
384
396
  throw lost(error);
@@ -389,8 +401,17 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
389
401
 
390
402
  const generateText: GenerateText = ({ system, prompt, maxOutputTokens, signal, onTruncated, onUsage }) => {
391
403
  const send = async (limit: number): Promise<LimitedReply> => {
392
- const timeout = AbortSignal.timeout(options.timeoutMs ?? 180_000);
393
- const stopped = () => Boolean(signal?.aborted) || timeout.aborted;
404
+ const timer = partTimer(signal, options.timeoutMs);
405
+ try {
406
+ return await read(limit, timer);
407
+ } finally {
408
+ timer.stop();
409
+ }
410
+ };
411
+ /** One part read, within its time limit: past it, a timeout. A stop of the caller's is reported as it is. */
412
+ const read = async (limit: number, timer: PartTimer): Promise<LimitedReply> => {
413
+ const stopped = () => Boolean(signal?.aborted);
414
+ const lost = (error: unknown) => (timer.expired && !signal?.aborted ? tooSlow(timer.limitMs) : unreachable(error));
394
415
  const body = (field: string): Json => ({
395
416
  model: options.model,
396
417
  messages: [{ role: systemRole, content: system }, { role: "user", content: prompt }],
@@ -401,15 +422,15 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
401
422
  // The name this request is sent with: part reads run together, and another may learn the other name meanwhile.
402
423
  const sent = maxTokensField;
403
424
  try {
404
- response = await post(body(sent), signal ? AbortSignal.any([signal, timeout]) : timeout, stopped);
425
+ response = await post(body(sent), timer.signal, stopped, lost, undefined, true);
405
426
  } catch (error) {
406
427
  // A server that knows only the other name of the output limit: it is sent that one, now and from now on.
407
428
  if (options.maxTokensField !== undefined || !refusesField(error, sent)) throw error;
408
429
  const other = sent === "max_tokens" ? "max_completion_tokens" : "max_tokens";
409
430
  if (maxTokensField === sent) maxTokensField = other;
410
- response = await post(body(other), signal ? AbortSignal.any([signal, timeout]) : timeout, stopped);
431
+ response = await post(body(other), timer.signal, stopped, lost, undefined, true);
411
432
  }
412
- const data = await readJson<Json>(response, stopped, unreachable, undefined, (error) => new OpenAiRequestError(notJsonMessage("The model's", response), response.status, { kind: "invalid", cause: error }));
433
+ const data = await readJson<Json>(response, stopped, lost, timer.signal ? { pulse: () => undefined, signal: timer.signal } : undefined, (error) => new OpenAiRequestError(notJsonMessage("The model's", response), response.status, { kind: "invalid", cause: error }));
413
434
  // An error in a body that came with 200 (OpenRouter, once generation has started): thrown as
414
435
  // a stream's error is, with its status, so that a 502 is sent again rather than read as no text.
415
436
  const failed = bodyError(data);
@@ -467,6 +488,13 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
467
488
  let finish: unknown;
468
489
  let usage: Json | undefined;
469
490
  let text = "";
491
+ /** The provider's ID of the response and the model that wrote it, when it names them. */
492
+ let responseId: string | undefined;
493
+ let responseModel: string | undefined;
494
+ const named = (data: Json | undefined) => {
495
+ if (typeof data?.id === "string" && data.id) responseId = data.id;
496
+ if (typeof data?.model === "string" && data.model) responseModel = data.model;
497
+ };
470
498
  // A body that is no JSON (a gateway's page) is not the model's reply, and is not sent again.
471
499
  const notJson = (error: unknown) => new OpenAiRequestError(notJsonMessage("The model's", answer), answer.status, { kind: "invalid", cause: error });
472
500
  let response = answer;
@@ -492,6 +520,7 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
492
520
  for await (const chunk of parseSseJson<Json>(response.body, { onData: watch.pulse, onDone: () => { ended = true; end.reached(); }, signal: end.signal })) {
493
521
  const failed = (Array.isArray(chunk) ? chunk[0] : chunk)?.error;
494
522
  if (failed) throw streamFailure(failed);
523
+ named(chunk);
495
524
  if (chunk.usage) usage = chunk.usage as Json;
496
525
  const choice = chunk.choices?.[0] as Json | undefined;
497
526
  if (!choice) continue;
@@ -508,8 +537,11 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
508
537
  if (typeof delta.reasoning === "string") reasoningText += delta.reasoning;
509
538
  if (Array.isArray(delta.reasoning_details)) for (const detail of delta.reasoning_details as unknown[]) addReasoningDetail(details, detail);
510
539
  for (const part of (Array.isArray(delta.tool_calls) ? delta.tool_calls : []) as Json[]) {
511
- // A call arrives in pieces under its index: first its ID and name, then its arguments, a few characters at a time.
512
- const at = typeof part.index === "number" ? part.index : part.id || toolCalls.length === 0 ? toolCalls.length : toolCalls.length - 1;
540
+ // A call arrives in pieces under its index: first its ID and name, then its arguments, a
541
+ // few characters at a time. A server that sends no index starts a new call with an ID
542
+ // that is not the last call's: one that sends the ID with every piece adds to that call.
543
+ const last = toolCalls[toolCalls.length - 1] as Json | undefined;
544
+ const at = typeof part.index === "number" ? part.index : toolCalls.length === 0 || (part.id && part.id !== last?.id) ? toolCalls.length : toolCalls.length - 1;
513
545
  const call = (toolCalls[at] ??= { type: "function", function: { name: "", arguments: "" } });
514
546
  for (const [key, value] of Object.entries(part)) {
515
547
  if (key !== "index" && key !== "function" && value !== undefined && value !== null && !(key === "id" && call.id)) call[key] = value;
@@ -565,6 +597,7 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
565
597
  message = (choice?.message ?? { role: "assistant", content: null }) as Json;
566
598
  finish = choice?.finish_reason;
567
599
  usage = data.usage as Json | undefined;
600
+ named(data);
568
601
  // The whole reply is in hand: one that the server stopped is sent again before any of it is shown.
569
602
  if (finish === "insufficient_system_resource") throw interrupted();
570
603
  // A refusal is what the model has to say to the user, in a field of its own.
@@ -579,6 +612,9 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
579
612
  const calls: ToolCall[] = (Array.isArray(message.tool_calls) ? message.tool_calls as Json[] : [])
580
613
  .filter((call) => typeof call?.function?.name === "string" && call.function.name)
581
614
  .map((call) => {
615
+ // A call that came without an ID is given one, once, in the turn that goes back too: its
616
+ // tool message must name the same ID as the call does.
617
+ if (typeof call.id !== "string" || !call.id) call.id = newCallId();
582
618
  const read = readArguments(call.function.arguments);
583
619
  // Arguments that are not a JSON object go back as none, and so do arguments that are
584
620
  // empty: a server that reads every call of the conversation (vLLM before 0.29) refuses
@@ -586,7 +622,7 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
586
622
  const written = call.function.arguments;
587
623
  if (read.problem || typeof written !== "string" || !written.trim()) call.function = { ...call.function, arguments: read.problem ? "{}" : JSON.stringify(read.args) };
588
624
  const problem = read.problem ?? cutOff;
589
- return { ...(typeof call.id === "string" && call.id ? { id: call.id } : {}), name: call.function.name as string, args: read.args, ...(problem ? { problem } : {}) };
625
+ return { id: call.id as string, name: call.function.name as string, args: read.args, ...(problem ? { problem } : {}) };
590
626
  });
591
627
  const kind = finishOfOpenAi(finish);
592
628
  return {
@@ -596,6 +632,8 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
596
632
  ...(typeof finish === "string" ? { finishReason: finish } : {}),
597
633
  ...(kind ? { finish: kind } : {}),
598
634
  ...(finish === "content_filter" && !text && calls.length === 0 ? { blockReason: "content_filter" } : {}),
635
+ ...(responseId ? { responseId } : {}),
636
+ ...(responseModel ? { responseModel } : {}),
599
637
  ...(usage ? { usage: usageOf(usage), providerUsage: usage } : {}),
600
638
  };
601
639
  }
@@ -612,6 +650,11 @@ function silent(waitMs: number): OpenAiRequestError {
612
650
  return new OpenAiRequestError(`The model sent nothing for ${Math.round(waitMs / 1_000)} s.`, 0, { kind: "timeout" });
613
651
  }
614
652
 
653
+ /** A part read whose whole reply did not come within its time limit (`timeoutMs`). */
654
+ function tooSlow(limitMs: number): OpenAiRequestError {
655
+ return new OpenAiRequestError(`The model took longer than ${waitText(limitMs)} to answer.`, 0, { kind: "timeout" });
656
+ }
657
+
615
658
  /** A reply the server stopped because it ran short (DeepSeek's `insufficient_system_resource`). */
616
659
  function interrupted(): OpenAiRequestError {
617
660
  return new OpenAiRequestError("The model's server stopped the reply: it ran short of resources.", 503);
@@ -1,5 +1,6 @@
1
1
  // A plain completion on a model that may think its output limit away: shared by the part readers
2
2
  // of every adapter.
3
+ import { until } from "./http.js";
3
4
 
4
5
  /**
5
6
  * A model that thinks counts its thoughts in its output limit. Asked for 4,096 tokens of notes on
@@ -63,7 +64,8 @@ export type LimitedReply = {
63
64
  * was learned is kept under `model` (a URL, or a URL and a model name): later requests start with
64
65
  * the larger limit, and a model that refused it (HTTP 400, but not for a request too large for the
65
66
  * 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.
67
+ * larger than that limit. Requests that arrive while the first one to a model is on its way wait for it,
68
+ * until their own signal aborts.
67
69
  */
68
70
  export async function completeWithinLimit(model: string, maxOutputTokens: number, send: (limit: number) => Promise<LimitedReply>, options: {
69
71
  signal?: AbortSignal | undefined;
@@ -77,7 +79,8 @@ export async function completeWithinLimit(model: string, maxOutputTokens: number
77
79
  if (!answered.has(model)) {
78
80
  const first = firstRequests.get(model);
79
81
  if (first) {
80
- await first;
82
+ // The first request may be another question's: this one's abort ends the wait at once.
83
+ await until(first, signal);
81
84
  signal?.throwIfAborted();
82
85
  } else {
83
86
  firstRequests.set(model, new Promise<void>((resolve) => {
@@ -0,0 +1,400 @@
1
+ /**
2
+ * The outline of a PDF from the size of its type (0.10.0).
3
+ *
4
+ * The text rules of the outline (analyze.ts) rarely fire on a PDF: pdf.js gives no blank line
5
+ * between paragraphs, and Hebrew has no capitals, so an unnumbered Hebrew PDF had no outline at
6
+ * all. Its headings are set in larger type than its body, and pdf.js gives the size of each piece
7
+ * of text. The PDF extractor collects the lines set larger than the body (`PdfHeadingFinder`) and
8
+ * returns them with their page (`ExtractedText.headings`). Ingest finds each one among the lines of
9
+ * its page in the stored text, and uses them when the text rules found fewer than 3 headings and 3
10
+ * or more of these are found (`pdfOutline`): a PDF whose text has an outline keeps it as it was, and
11
+ * so does one with a title alone.
12
+ *
13
+ * pdf.js does not say which text is bold (its text content names a generic family, such as
14
+ * "sans-serif", and no weight), so a heading in bold type of the body's size is not found.
15
+ */
16
+ import { pickOutline } from "./analyze.js";
17
+ import type { TimeSlicer } from "./pause.js";
18
+ import type { PdfTextItem } from "./pdf-layout.js";
19
+ import { composed, removeInvisible } from "./text.js";
20
+ import type { ExtractedText, OutlineEntry } from "./types.js";
21
+
22
+ /**
23
+ * A heading of a PDF, as the extractor returns it: its page, from 1; its level, from 1; its text;
24
+ * and, when lines above it on its page read the same (spaces aside: a contents list, a running
25
+ * header), how many, so that ingest passes over them.
26
+ */
27
+ export type PdfHeading = { page: number; level: number; title: string; skip?: number };
28
+
29
+ /** Sizes are compared in steps of half a unit: Word's 10.56 and 10.5 are one size. */
30
+ const SIZE_STEP = 0.5;
31
+ /**
32
+ * A heading is set at least this much larger than the body: Word's Heading 2 (13 pt over 11),
33
+ * HTML's h3 (1.17 em), LibreOffice's Heading 2 (115%). Word's Heading 3 (12 pt over 11) is not: a
34
+ * lower ratio takes body text set a point larger, a quotation or a note, for headings.
35
+ */
36
+ const HEADING_RATIO = 1.15;
37
+ /** Of a line's characters, at least this share are of its size: a line that opens with a large word is body text. */
38
+ const UNIFORM_SHARE = 0.75;
39
+ /** When more of the text than this is set larger than the body, its sizes do not mark headings. */
40
+ const MAX_LARGE_SHARE = 0.3;
41
+ /** A heading has at least 3 letters, and no more digits than letters: "12,500", "2026" and "- 3 -" are not headings. */
42
+ const MIN_LETTERS = 3;
43
+ /** The longest heading, as for the text rules. */
44
+ const MAX_TITLE_CHARACTERS = 120;
45
+ /** Levels come from the rank of the sizes: the largest is 1, the third and smaller are 3. */
46
+ const MAX_LEVELS = 3;
47
+ /** Lines kept while the pages are read, before the size of the body is known: past this, the smallest size kept goes. */
48
+ const MAX_KEPT_LINES = 20_000;
49
+ /** Sizes kept while the pages are read: past this, the smallest goes. A document uses a few dozen; the bound keeps each line's work small. */
50
+ const MAX_KEPT_SIZES = 64;
51
+ /**
52
+ * A gap wider than this many times the size of the type, between two pieces of one line, is between
53
+ * two cells: the line is a table row. The tab after a heading's number is at most half an inch,
54
+ * less than 3 times the size of a heading.
55
+ */
56
+ const CELL_GAP = 3;
57
+ /** An outline has at least this many headings, from the text rules or the sizes: one or two are seldom an outline. */
58
+ export const MIN_TEXT_HEADINGS = 3;
59
+ /** The most headings `ingest` reads from an extractor. */
60
+ const MAX_GIVEN_HEADINGS = 10_000;
61
+ /** A stored line longer than this is not looked at: a heading is at most 120 characters, with a space between its words. */
62
+ const MAX_LINE_CHARACTERS = 2 * MAX_TITLE_CHARACTERS;
63
+
64
+ type Line = { page: number; order: number; size: number; title: string; skip: number };
65
+
66
+ /** The size of a piece of text, in steps of `SIZE_STEP`, or undefined when it has none. */
67
+ function sizeOf(item: PdfTextItem): number | undefined {
68
+ const matrix: unknown = item.transform;
69
+ // pdf.js gives the height of horizontal text; vertical text has none, and its matrix gives the size.
70
+ const raw = item.height > 0 ? item.height : Array.isArray(matrix) ? Math.hypot(Number(matrix[0]), Number(matrix[1])) : Number.NaN;
71
+ const size = Math.round(raw / SIZE_STEP) * SIZE_STEP;
72
+ return Number.isFinite(size) && size > 0 ? size : undefined;
73
+ }
74
+
75
+ /** Where a piece of text starts along its line (it ends `width` further), or NaN when that cannot be told. */
76
+ function startOf(item: PdfTextItem): number {
77
+ const matrix: unknown = item.transform;
78
+ if (!Array.isArray(matrix) || !(item.width > 0)) return Number.NaN;
79
+ const a = Number(matrix[0]);
80
+ const b = Number(matrix[1]);
81
+ return (Number(matrix[4]) * a + Number(matrix[5]) * b) / Math.hypot(a, b);
82
+ }
83
+
84
+ /** Whether a line's text can be a heading: not too long, not a table row, and words rather than a number. */
85
+ function mayBeHeading(title: string): boolean {
86
+ if (title.length > MAX_TITLE_CHARACTERS || title.startsWith("|")) return false;
87
+ const letters = title.match(/\p{L}/gu)?.length ?? 0;
88
+ const digits = title.match(/\p{Nd}/gu)?.length ?? 0;
89
+ return letters >= MIN_LETTERS && letters >= digits;
90
+ }
91
+
92
+ /** A text as it is compared with a heading: cleaned and composed as ingest stores text, without its spaces. */
93
+ const compared = (text: string) => composed(removeInvisible(text)).replace(/\s+/g, "");
94
+ /** A line's text with each number written "#", or undefined when it has none: "Page 3 of 10" is the same on every page. */
95
+ const numberless = (title: string) => (/\p{Nd}/u.test(title) ? title.replace(/\s+/g, "").replace(/\p{Nd}+/gu, "#") : undefined);
96
+
97
+ /** Adds `page` to the pages of `key`. */
98
+ function seenOn(pages: Map<string, Set<number>>, key: string, page: number): void {
99
+ const set = pages.get(key);
100
+ if (set) set.add(page);
101
+ else pages.set(key, new Set([page]));
102
+ }
103
+
104
+ /**
105
+ * Finds the headings of a PDF from the size of its type, page by page as pdf.js reads them. A line
106
+ * is the text up to the end of a line (`hasEOL`), as the extractor writes it, and its size is the
107
+ * size most of its characters have. A line with a gap of more than 3 times its size between two
108
+ * pieces is a table row (cells, or a label and its value): it counts for neither the body nor the
109
+ * headings. Once every page is read, `headings()` gives the lines set at least 15% larger than the
110
+ * body, the commonest size of the other lines, but for:
111
+ * - lines over 120 characters, with fewer than 3 letters, with more digits than letters, or that
112
+ * start with "|";
113
+ * - lines with less than three quarters of their characters at their size;
114
+ * - running headers and footers: the same line on 3 pages or more, or on 2 pages and half the
115
+ * pages; or a page number (`pageNumbered`);
116
+ * - the lines after the first of a heading set on several lines in a row, at one size;
117
+ * - all of them, when more than 30% of the text is set larger than the body (sizes then mark
118
+ * something else).
119
+ *
120
+ * Levels follow the sizes of several headings: the largest is level 1, the next 2, the others 3. A
121
+ * size of one heading, larger than all of those (a title, the lines of a cover), is level 1, and the
122
+ * others then start at 2. At most 400 headings, picked as the text rules' outline is. The work is
123
+ * linear in the text: at most 20,000 lines in 64 sizes are kept until the end.
124
+ */
125
+ export class PdfHeadingFinder {
126
+ /** The characters of each size, over all the text. */
127
+ private readonly characters = new Map<number, number>();
128
+ /** The lines that may be headings, by size. */
129
+ private readonly kept = new Map<number, Line[]>();
130
+ private keptLines = 0;
131
+ /** Lines of this size or smaller are no longer kept: there were too many. */
132
+ private floor = 0;
133
+ private pages = 0;
134
+ /** The lines of the page being read, by their text without spaces: how many so far. */
135
+ private readonly onPage = new Map<string, number>();
136
+
137
+ /** Adds the text of page `page` (from 1): `page.getTextContent().items`. */
138
+ addPage(page: number, items: readonly PdfTextItem[]): void {
139
+ this.pages++;
140
+ this.onPage.clear();
141
+ let order = 0;
142
+ let start = 0;
143
+ for (let index = 0; index <= items.length; index++) {
144
+ if (index < items.length && !items[index]!.hasEOL) continue;
145
+ if (this.addLine(page, order, items.slice(start, index + 1))) order++;
146
+ start = index + 1;
147
+ }
148
+ }
149
+
150
+ /** Adds one line; false when it has no visible character. */
151
+ private addLine(page: number, order: number, items: readonly PdfTextItem[]): boolean {
152
+ let text = "";
153
+ let total = 0;
154
+ let row = false;
155
+ /** The last piece with text: where it starts and ends along the line, and its size (NaN when not known). */
156
+ let lastStart = Number.NaN;
157
+ let lastEnd = Number.NaN;
158
+ let lastSize = 0;
159
+ const bySize = new Map<number, number>();
160
+ for (const item of items) {
161
+ if (typeof item.str !== "string") continue;
162
+ text += item.str;
163
+ const count = item.str.replace(/\s+/g, "").length;
164
+ const size = count > 0 ? sizeOf(item) : undefined;
165
+ if (size === undefined) continue;
166
+ bySize.set(size, (bySize.get(size) ?? 0) + count);
167
+ total += count;
168
+ // Right-to-left text runs the other way: the gap is the space between the two pieces either way.
169
+ const start = startOf(item);
170
+ const end = start + item.width;
171
+ if (Math.max(start - lastEnd, lastStart - end) > CELL_GAP * Math.max(size, lastSize)) row = true;
172
+ lastStart = start;
173
+ lastEnd = end;
174
+ lastSize = size;
175
+ }
176
+ if (total === 0) return false;
177
+ const title = text.replace(/\s+/g, " ").trim();
178
+ // A heading is the line after those above it on its page that read the same (a contents list).
179
+ const key = title.length <= MAX_LINE_CHARACTERS ? title.replace(/ /g, "") : "";
180
+ const skip = this.onPage.get(key) ?? 0;
181
+ if (key) this.onPage.set(key, skip + 1);
182
+ if (row) return true;
183
+ let size = 0;
184
+ let most = 0;
185
+ for (const [each, count] of bySize) {
186
+ this.characters.set(each, (this.characters.get(each) ?? 0) + count);
187
+ if (count > most || (count === most && each < size)) {
188
+ size = each;
189
+ most = count;
190
+ }
191
+ }
192
+ if (most >= UNIFORM_SHARE * total && size > this.floor && mayBeHeading(title)) this.keep({ page, order, size, title, skip });
193
+ return true;
194
+ }
195
+
196
+ private keep(line: Line): void {
197
+ const lines = this.kept.get(line.size);
198
+ if (lines) lines.push(line);
199
+ else this.kept.set(line.size, [line]);
200
+ this.keptLines++;
201
+ // Headings are larger than the body, so the smallest size goes first, and is not kept again.
202
+ // Each size goes at most once, and there are at most 65 to look through.
203
+ while (this.keptLines > MAX_KEPT_LINES || this.kept.size > MAX_KEPT_SIZES) {
204
+ const smallest = Math.min(...this.kept.keys());
205
+ this.keptLines -= this.kept.get(smallest)!.length;
206
+ this.kept.delete(smallest);
207
+ this.floor = smallest;
208
+ }
209
+ }
210
+
211
+ /** The headings found, in the order of the text. Empty when the sizes mark none. */
212
+ headings(): PdfHeading[] {
213
+ // The body: the size with the most characters, the smaller of two with as many.
214
+ let body = 0;
215
+ let most = 0;
216
+ let all = 0;
217
+ for (const [size, count] of this.characters) {
218
+ all += count;
219
+ if (count > most || (count === most && size < body)) {
220
+ body = size;
221
+ most = count;
222
+ }
223
+ }
224
+ const least = body * HEADING_RATIO;
225
+ let large = 0;
226
+ for (const [size, count] of this.characters) if (size >= least) large += count;
227
+ // No larger type; too much of it; or lines of a heading's size were let go (over 20,000 of them).
228
+ if (large === 0 || large > MAX_LARGE_SHARE * all || this.floor >= least) return [];
229
+ const lines = [...this.kept].flatMap(([size, kept]) => (size >= least ? kept : []));
230
+ lines.sort((left, right) => left.page - right.page || left.order - right.order);
231
+ // Running headers and footers: the same line on many pages, or a page number.
232
+ const exactly = new Map<string, Set<number>>();
233
+ const numbered = new Map<string, Line[]>();
234
+ for (const line of lines) {
235
+ seenOn(exactly, line.title.replace(/\s+/g, ""), line.page);
236
+ const key = numberless(line.title);
237
+ if (key === undefined) continue;
238
+ const alike = numbered.get(key);
239
+ if (alike) alike.push(line);
240
+ else numbered.set(key, [line]);
241
+ }
242
+ const paged = new Set([...numbered].flatMap(([key, alike]) => (pageNumbered(alike, this.pages) ? [key] : [])));
243
+ const running = (line: Line) => {
244
+ const same = exactly.get(line.title.replace(/\s+/g, ""))!.size;
245
+ const key = numberless(line.title);
246
+ return same >= 3 || (same >= 2 && same * 2 >= this.pages) || (key !== undefined && paged.has(key));
247
+ };
248
+ const found: Line[] = [];
249
+ let previous: Line | undefined;
250
+ for (const line of lines) {
251
+ if (running(line)) continue;
252
+ const continues = previous !== undefined && previous.page === line.page && previous.order + 1 === line.order && previous.size === line.size;
253
+ previous = line;
254
+ if (!continues) found.push(line);
255
+ }
256
+ const levelOf = levels(found.map((line) => line.size));
257
+ return pickOutline(found.map((line) => ({ page: line.page, level: levelOf.get(line.size)!, title: line.title, ...(line.skip > 0 ? { skip: line.skip } : {}) })));
258
+ }
259
+ }
260
+
261
+ /** The numbers of a line, in its order. */
262
+ const numbersOf = (title: string) => (title.match(/\p{Nd}+/gu) ?? []).map(Number);
263
+
264
+ /** Whether `after` is `before` with one of its numbers 1 more and the others the same. */
265
+ function oneMore(before: number[], after: number[]): boolean {
266
+ let more = 0;
267
+ for (const [index, number] of before.entries()) {
268
+ if (after[index] === number + 1) more++;
269
+ else if (after[index] !== number) return false;
270
+ }
271
+ return more === 1;
272
+ }
273
+
274
+ /**
275
+ * Whether lines that differ only by their numbers, in the order of the text, are a page number, a
276
+ * running header or footer ("עמוד 3 מתוך 10", "Annual Report page 7"): on 2 pages or more and at
277
+ * least half the pages, never counting up on one page (the same number in a page's header and its
278
+ * footer is one page number), and not counting as section numbers do. Section
279
+ * numbers count headings: each is the one before with one number 1 more, with pages without one
280
+ * between some of them ("פרק 1" to "פרק 5" on the odd pages). A page number counts pages: it skips
281
+ * the pages it is missing from ("page 1", "page 3" on the odd pages). Several on one page ("Article
282
+ * 1" to "Article 18", 3 to a page) are headings. On pages in a row, counting by one, the two read
283
+ * the same, and are taken for a page number: chapters one to a page on pages in a row, half the
284
+ * pages or more, are lost.
285
+ */
286
+ function pageNumbered(alike: Line[], pages: number): boolean {
287
+ const on = new Set(alike.map((line) => line.page)).size;
288
+ if (on < 2 || on * 2 < pages) return false;
289
+ let counts = true;
290
+ let skips = false;
291
+ for (let index = 1; index < alike.length; index++) {
292
+ const before = alike[index - 1]!;
293
+ const line = alike[index]!;
294
+ if (line.page === before.page) {
295
+ // Several on one page that count up are headings ("Article 1" to "Article 3"); the same
296
+ // number twice on a page is a page number in the header and the footer.
297
+ if (oneMore(numbersOf(before.title), numbersOf(line.title))) return false;
298
+ continue;
299
+ }
300
+ skips ||= line.page > before.page + 1;
301
+ counts &&= oneMore(numbersOf(before.title), numbersOf(line.title));
302
+ }
303
+ return !(counts && skips);
304
+ }
305
+
306
+ /**
307
+ * The level of each size of `sizes`, those of the headings found: the sizes of several headings rank
308
+ * from the largest, 1 to 3; a size of one heading, larger than all of those (a title, the lines of a
309
+ * cover), is level 1, and the ranks then start at 2, so that a cover does not take the levels of
310
+ * the body's headings. When every size is of one heading, they all rank.
311
+ */
312
+ function levels(sizes: number[]): Map<number, number> {
313
+ const uses = new Map<number, number>();
314
+ for (const size of sizes) uses.set(size, (uses.get(size) ?? 0) + 1);
315
+ const all = [...uses.keys()].sort((left, right) => right - left);
316
+ const ranked = all.filter((size) => uses.get(size)! >= 2);
317
+ const top = ranked[0];
318
+ if (top === undefined) return new Map(all.map((size, rank) => [size, Math.min(rank + 1, MAX_LEVELS)]));
319
+ const first = all[0]! > top ? 2 : 1;
320
+ return new Map(all.map((size) => [size, size > top ? 1 : Math.min(first + ranked.filter((each) => each > size).length, MAX_LEVELS)]));
321
+ }
322
+
323
+ /**
324
+ * The headings an extractor returned (`ExtractedText.headings`): the first 10,000 entries, those of
325
+ * the right shape (a page and a level that are whole numbers from 1, the level up to 6, a title of
326
+ * 1 to 1,000 characters, and a `skip` that is a whole number from 0, or none). Undefined when there
327
+ * are none.
328
+ */
329
+ export function headingsOf(extracted: ExtractedText): PdfHeading[] | undefined {
330
+ const given: unknown = extracted.headings;
331
+ if (!Array.isArray(given)) return undefined;
332
+ const headings: PdfHeading[] = [];
333
+ for (const entry of given.slice(0, MAX_GIVEN_HEADINGS) as unknown[]) {
334
+ if (typeof entry !== "object" || entry === null) continue;
335
+ const { page, level, title, skip } = entry as { page?: unknown; level?: unknown; title?: unknown; skip?: unknown };
336
+ if (!Number.isSafeInteger(page) || (page as number) < 1 || !Number.isSafeInteger(level) || (level as number) < 1 || (level as number) > 6) continue;
337
+ if (typeof title !== "string" || !title.trim() || title.length > 1_000) continue;
338
+ if (skip !== undefined && (!Number.isSafeInteger(skip) || (skip as number) < 0)) continue;
339
+ headings.push({ page: page as number, level: level as number, title, ...(skip ? { skip: skip as number } : {}) });
340
+ }
341
+ return headings.length > 0 ? headings : undefined;
342
+ }
343
+
344
+ /**
345
+ * The outline of the stored text from the headings of the extractor: each heading is the line of its
346
+ * page, after the one taken for the heading before it, with the same text once spaces are left out
347
+ * (pdf.js gives Hebrew words without the space between them, and the extractor adds it), past the
348
+ * `skip` lines above it that read the same. Pages start at the lines `--- Page N ---`, from 1, each
349
+ * continuing the count. A heading that is not found is left out; the title is the line as it is stored.
350
+ */
351
+ async function placeHeadings(lines: string[], headings: PdfHeading[], slicer: TimeSlicer): Promise<OutlineEntry[]> {
352
+ const byPage = new Map<number, Map<string, PdfHeading[]>>();
353
+ for (const heading of headings) {
354
+ const key = compared(heading.title);
355
+ if (!key) continue;
356
+ let page = byPage.get(heading.page);
357
+ if (!page) byPage.set(heading.page, (page = new Map()));
358
+ const same = page.get(key);
359
+ if (same) same.push(heading);
360
+ else page.set(key, [heading]);
361
+ }
362
+ const outline: OutlineEntry[] = [];
363
+ let next = 1;
364
+ let marker = "--- Page 1 ---";
365
+ let page: Map<string, PdfHeading[]> | undefined;
366
+ /** The lines of the page so far, by their text without spaces: how many. */
367
+ const seen = new Map<string, number>();
368
+ for (let index = 0; index < lines.length; index++) {
369
+ if ((index & 4095) === 4095) await slicer.maybePause();
370
+ const line = lines[index]!;
371
+ if (line === marker) {
372
+ page = byPage.get(next++);
373
+ marker = `--- Page ${next} ---`;
374
+ seen.clear();
375
+ continue;
376
+ }
377
+ if (!page || line.length > MAX_LINE_CHARACTERS) continue;
378
+ const key = line.replace(/\s+/g, "");
379
+ const waiting = page.get(key);
380
+ if (!waiting?.length) continue;
381
+ const above = seen.get(key) ?? 0;
382
+ seen.set(key, above + 1);
383
+ if ((waiting[0]!.skip ?? 0) > above) continue;
384
+ const heading = waiting.shift()!;
385
+ outline.push({ line: index + 1, level: heading.level, title: line.trim() });
386
+ }
387
+ return outline;
388
+ }
389
+
390
+ /**
391
+ * The outline of a PDF: `outline`, from the text rules, when it has 3 headings or more, or when
392
+ * fewer than 3 of the extractor's headings are found in the stored text (one or two are seldom an
393
+ * outline: a title alone tells nothing); otherwise those found, at most 400, picked as the text
394
+ * rules' are.
395
+ */
396
+ export async function pdfOutline(outline: OutlineEntry[], lines: string[], headings: PdfHeading[] | undefined, slicer: TimeSlicer): Promise<OutlineEntry[]> {
397
+ if (!headings || outline.length >= MIN_TEXT_HEADINGS) return outline;
398
+ const placed = await placeHeadings(lines, headings, slicer);
399
+ return placed.length >= MIN_TEXT_HEADINGS ? pickOutline(placed) : outline;
400
+ }