llm-large-files 0.4.0 → 0.5.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 (156) hide show
  1. package/CHANGELOG.md +205 -0
  2. package/README.md +48 -8
  3. package/dist/anthropic/adapter.d.ts +106 -0
  4. package/dist/anthropic/adapter.d.ts.map +1 -0
  5. package/dist/anthropic/adapter.js +391 -0
  6. package/dist/anthropic/adapter.js.map +1 -0
  7. package/dist/anthropic/index.d.ts +3 -0
  8. package/dist/anthropic/index.d.ts.map +1 -0
  9. package/dist/anthropic/index.js +2 -0
  10. package/dist/anthropic/index.js.map +1 -0
  11. package/dist/ask.d.ts +144 -0
  12. package/dist/ask.d.ts.map +1 -0
  13. package/dist/ask.js +540 -0
  14. package/dist/ask.js.map +1 -0
  15. package/dist/budget.d.ts +23 -0
  16. package/dist/budget.d.ts.map +1 -0
  17. package/dist/budget.js +64 -0
  18. package/dist/budget.js.map +1 -0
  19. package/dist/cache.d.ts +11 -2
  20. package/dist/cache.d.ts.map +1 -1
  21. package/dist/cache.js +36 -7
  22. package/dist/cache.js.map +1 -1
  23. package/dist/errors.d.ts +21 -0
  24. package/dist/errors.d.ts.map +1 -0
  25. package/dist/errors.js +44 -0
  26. package/dist/errors.js.map +1 -0
  27. package/dist/evidence.d.ts +40 -0
  28. package/dist/evidence.d.ts.map +1 -0
  29. package/dist/evidence.js +137 -0
  30. package/dist/evidence.js.map +1 -0
  31. package/dist/gemini/adapter.d.ts +50 -0
  32. package/dist/gemini/adapter.d.ts.map +1 -0
  33. package/dist/gemini/adapter.js +179 -0
  34. package/dist/gemini/adapter.js.map +1 -0
  35. package/dist/gemini/chat.d.ts +32 -71
  36. package/dist/gemini/chat.d.ts.map +1 -1
  37. package/dist/gemini/chat.js +38 -284
  38. package/dist/gemini/chat.js.map +1 -1
  39. package/dist/gemini/errors.d.ts +11 -0
  40. package/dist/gemini/errors.d.ts.map +1 -0
  41. package/dist/gemini/errors.js +14 -0
  42. package/dist/gemini/errors.js.map +1 -0
  43. package/dist/gemini/generate.d.ts +12 -13
  44. package/dist/gemini/generate.d.ts.map +1 -1
  45. package/dist/gemini/generate.js +62 -26
  46. package/dist/gemini/generate.js.map +1 -1
  47. package/dist/gemini/index.d.ts +3 -1
  48. package/dist/gemini/index.d.ts.map +1 -1
  49. package/dist/gemini/index.js +2 -1
  50. package/dist/gemini/index.js.map +1 -1
  51. package/dist/gemini/sse.d.ts +1 -2
  52. package/dist/gemini/sse.d.ts.map +1 -1
  53. package/dist/gemini/sse.js +1 -38
  54. package/dist/gemini/sse.js.map +1 -1
  55. package/dist/http.d.ts +20 -0
  56. package/dist/http.d.ts.map +1 -0
  57. package/dist/http.js +55 -0
  58. package/dist/http.js.map +1 -0
  59. package/dist/index.d.ts +14 -2
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +12 -4
  62. package/dist/index.js.map +1 -1
  63. package/dist/library.d.ts +50 -5
  64. package/dist/library.d.ts.map +1 -1
  65. package/dist/library.js +56 -26
  66. package/dist/library.js.map +1 -1
  67. package/dist/map-reduce.d.ts +15 -0
  68. package/dist/map-reduce.d.ts.map +1 -1
  69. package/dist/map-reduce.js +58 -27
  70. package/dist/map-reduce.js.map +1 -1
  71. package/dist/model.d.ts +196 -0
  72. package/dist/model.d.ts.map +1 -0
  73. package/dist/model.js +41 -0
  74. package/dist/model.js.map +1 -0
  75. package/dist/openai/adapter.d.ts +85 -0
  76. package/dist/openai/adapter.d.ts.map +1 -0
  77. package/dist/openai/adapter.js +293 -0
  78. package/dist/openai/adapter.js.map +1 -0
  79. package/dist/openai/index.d.ts +3 -0
  80. package/dist/openai/index.d.ts.map +1 -0
  81. package/dist/openai/index.js +2 -0
  82. package/dist/openai/index.js.map +1 -0
  83. package/dist/output-limit.d.ts +30 -0
  84. package/dist/output-limit.d.ts.map +1 -0
  85. package/dist/output-limit.js +92 -0
  86. package/dist/output-limit.js.map +1 -0
  87. package/dist/plan.d.ts +20 -4
  88. package/dist/plan.d.ts.map +1 -1
  89. package/dist/plan.js +44 -7
  90. package/dist/plan.js.map +1 -1
  91. package/dist/ranged.d.ts +2 -2
  92. package/dist/ranged.d.ts.map +1 -1
  93. package/dist/ranged.js +11 -4
  94. package/dist/ranged.js.map +1 -1
  95. package/dist/retry.d.ts +54 -0
  96. package/dist/retry.d.ts.map +1 -0
  97. package/dist/retry.js +111 -0
  98. package/dist/retry.js.map +1 -0
  99. package/dist/search.d.ts +16 -2
  100. package/dist/search.d.ts.map +1 -1
  101. package/dist/search.js +109 -26
  102. package/dist/search.js.map +1 -1
  103. package/dist/sse.d.ts +3 -0
  104. package/dist/sse.d.ts.map +1 -0
  105. package/dist/sse.js +39 -0
  106. package/dist/sse.js.map +1 -0
  107. package/dist/stores.d.ts +5 -1
  108. package/dist/stores.d.ts.map +1 -1
  109. package/dist/stores.js +58 -15
  110. package/dist/stores.js.map +1 -1
  111. package/dist/text.d.ts +12 -1
  112. package/dist/text.d.ts.map +1 -1
  113. package/dist/text.js +43 -15
  114. package/dist/text.js.map +1 -1
  115. package/dist/tools.d.ts +23 -0
  116. package/dist/tools.d.ts.map +1 -1
  117. package/dist/tools.js +115 -35
  118. package/dist/tools.js.map +1 -1
  119. package/dist/types.d.ts +33 -3
  120. package/dist/types.d.ts.map +1 -1
  121. package/docs/api.md +253 -28
  122. package/docs/configuration.md +89 -10
  123. package/docs/getting-started.md +69 -16
  124. package/docs/how-it-works.md +46 -4
  125. package/docs/security.md +36 -3
  126. package/package.json +21 -3
  127. package/src/anthropic/adapter.ts +454 -0
  128. package/src/anthropic/index.ts +2 -0
  129. package/src/ask.ts +675 -0
  130. package/src/budget.ts +71 -0
  131. package/src/cache.ts +32 -8
  132. package/src/errors.ts +42 -0
  133. package/src/evidence.ts +162 -0
  134. package/src/gemini/adapter.ts +218 -0
  135. package/src/gemini/chat.ts +62 -333
  136. package/src/gemini/errors.ts +15 -0
  137. package/src/gemini/generate.ts +72 -30
  138. package/src/gemini/index.ts +3 -1
  139. package/src/gemini/sse.ts +1 -34
  140. package/src/http.ts +59 -0
  141. package/src/index.ts +34 -4
  142. package/src/library.ts +102 -29
  143. package/src/map-reduce.ts +52 -23
  144. package/src/model.ts +200 -0
  145. package/src/openai/adapter.ts +345 -0
  146. package/src/openai/index.ts +2 -0
  147. package/src/output-limit.ts +99 -0
  148. package/src/plan.ts +46 -7
  149. package/src/ranged.ts +13 -6
  150. package/src/retry.ts +132 -0
  151. package/src/search.ts +116 -25
  152. package/src/sse.ts +34 -0
  153. package/src/stores.ts +51 -15
  154. package/src/text.ts +39 -12
  155. package/src/tools.ts +127 -38
  156. package/src/types.ts +29 -3
package/src/plan.ts CHANGED
@@ -18,7 +18,7 @@ export function planDocuments(
18
18
  const byteRoom = budget.maxRequestBytes - REQUEST_BYTES_MARGIN - base.bytes;
19
19
  const plan: DocumentPlan = { inline: [], searchable: [], inlineTokens: 0, inlineBytes: 0 };
20
20
  for (const meta of [...documents].sort((left, right) => left.estimatedTokens - right.estimatedTokens)) {
21
- const bytes = Math.ceil(meta.textBytes * 1.08) + 200;
21
+ const bytes = (meta.jsonBytes ?? Math.ceil(meta.textBytes * 1.08)) + 200;
22
22
  if (plan.inlineTokens + meta.estimatedTokens <= tokenRoom && plan.inlineBytes + bytes <= byteRoom) {
23
23
  plan.inline.push(meta);
24
24
  plan.inlineTokens += meta.estimatedTokens;
@@ -30,6 +30,41 @@ export function planDocuments(
30
30
  return plan;
31
31
  }
32
32
 
33
+ /** The digits of the numbers 1 to `count`, written out: what the line numbers of a text take. */
34
+ function digitsUpTo(count: number): number {
35
+ let digits = 0;
36
+ for (let width = 1, first = 1; first <= count; width++, first *= 10) digits += (Math.min(count, first * 10 - 1) - first + 1) * width;
37
+ return digits;
38
+ }
39
+
40
+ /**
41
+ * About how many parts a whole-document read of a document takes, from its metadata alone:
42
+ * counting them exactly means reading the whole text. In the prompt every line carries its number
43
+ * (`12345| `), at about 1.2 tokens a digit and one for the bar, and each line's estimate is
44
+ * rounded up. A part ends at the end of a line, so it is short of full by half a line on average.
45
+ * On logs, prose, tables and blank-heavy text this lands within a few percent of the count.
46
+ */
47
+ export function estimateParts(meta: Pick<DocumentMeta, "estimatedTokens" | "lines" | "textBytes" | "jsonBytes">, budget: Budget): number {
48
+ const lines = Math.max(1, meta.lines);
49
+ const digits = digitsUpTo(lines);
50
+ const tokens = meta.estimatedTokens + 1.2 * digits + 1.5 * lines;
51
+ const bytes = (meta.jsonBytes ?? meta.textBytes * 1.08) + digits + 4 * lines;
52
+ const room = (limit: number, size: number) => Math.max(1, limit - size / lines / 2);
53
+ const maxBytes = Math.floor(budget.maxRequestBytes * 0.8);
54
+ return Math.max(1, Math.ceil(Math.max(tokens / room(budget.mapChunkTokens, tokens), bytes / room(maxBytes, bytes))));
55
+ }
56
+
57
+ /**
58
+ * Whether a whole-document read of a document is within `maxMapChunks`, as far as its metadata
59
+ * tells. The estimate runs a few percent high, so a file just over the limit by it is let through:
60
+ * the read counts its parts, and refuses with the reason if they are too many after all.
61
+ */
62
+ export function canBeReadWhole(meta: Pick<DocumentMeta, "estimatedTokens" | "lines" | "textBytes" | "jsonBytes">, budget: Budget): boolean {
63
+ const parts = estimateParts(meta, budget);
64
+ // Metadata that does not say (a record of a document that an application kept in part): not refused here.
65
+ return !Number.isFinite(parts) || parts <= budget.maxMapChunks * 1.05;
66
+ }
67
+
33
68
  function formatCount(value: number): string {
34
69
  if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
35
70
  if (value >= 10_000) return `${Math.round(value / 1_000)}K`;
@@ -59,14 +94,17 @@ export const CARD_LINES = CARD_HEAD_LINES;
59
94
  /**
60
95
  * A compact stand-in for a document that is too large for the prompt. `head` is its first
61
96
  * `CARD_LINES` lines, numbered. `viewable` adds a line saying that its pages can be looked at
62
- * with `view_pages`.
97
+ * with `view_pages`. `readableWhole` is false for a file that a whole-document read would refuse:
98
+ * the card then does not offer one.
63
99
  */
64
- export function renderCard(meta: DocumentMeta, head: string, viewable = false): string {
100
+ export function renderCard(meta: DocumentMeta, head: string, viewable = false, readableWhole = true): string {
65
101
  const out = [
66
102
  `--- Large attached file: ${meta.name} ---`,
67
103
  `document_id: ${meta.id}`,
68
104
  `${meta.format} · ${formatBytes(meta.bytes)} · ${meta.lines.toLocaleString("en-US")} lines${meta.pages ? ` · ${meta.pages} pages` : ""} · about ${formatCount(meta.estimatedTokens)} tokens`,
69
- "This file is NOT in your context. Use the document tools to search it, read line ranges, or analyze all of it.",
105
+ readableWhole
106
+ ? "This file is NOT in your context. Use the document tools to search it, read line ranges, or analyze all of it."
107
+ : "This file is NOT in your context. Use the document tools to search it and to read line ranges. It is too large to be analyzed whole.",
70
108
  ...(viewable ? ["Its text cannot show pictures. To see a picture, a chart or the layout of a page, look at the page with view_pages."] : []),
71
109
  ];
72
110
  const profile = meta.logProfile;
@@ -91,9 +129,10 @@ export function renderCard(meta: DocumentMeta, head: string, viewable = false):
91
129
  /**
92
130
  * The tool guide for the system prompt. `searchable` are the files the model reads through the
93
131
  * text tools. `viewable` are the PDFs whose pages it can look at with `view_pages`: some of them
94
- * may be searchable, and some may have their whole text in the prompt.
132
+ * may be searchable, and some may have their whole text in the prompt. `wholeReads` is false when
133
+ * every searchable file is too large for `analyze_whole_document`: the guide then leaves it out.
95
134
  */
96
- export function documentToolsInstruction(searchable: DocumentMeta[], viewable: DocumentMeta[] = []): string {
135
+ export function documentToolsInstruction(searchable: DocumentMeta[], viewable: DocumentMeta[] = [], wholeReads = true): string {
97
136
  // File names come from uploads. Quoting keeps a name that reads like an instruction a name.
98
137
  const named = (meta: DocumentMeta, detail = "") => `${JSON.stringify(meta.name)} (document_id ${meta.id}${detail})`;
99
138
  const guide: string[] = [];
@@ -104,7 +143,7 @@ export function documentToolsInstruction(searchable: DocumentMeta[], viewable: D
104
143
  "- search_document finds lines (exact or regex) or the most relevant passages (keywords).",
105
144
  "- read_document reads a line range. Read around search hits before you rely on them.",
106
145
  "- get_document_overview returns the outline, log profile, and the start and end of a file.",
107
- "- analyze_whole_document reads the entire file in parts. Use it only when the task needs all of it (a full summary, every occurrence, a timeline). It is slow and costly.",
146
+ ...(wholeReads ? ["- analyze_whole_document reads the entire file in parts. Use it only when the task needs all of it (a full summary, every occurrence, a timeline). It is slow and costly."] : []),
108
147
  "You have a limited number of tool turns. Call several tools in the same turn when the searches do not depend on each other, and answer as soon as you have enough evidence.",
109
148
  "Base your answer on text you actually read. Cite line numbers like (app.log L1203). If the tools did not find something, say so rather than guessing.",
110
149
  );
package/src/ranged.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  * text the first time an older document without one is opened, and saved for next time.
6
6
  */
7
7
  import type { Limiter } from "./limiter.js";
8
- import { pagesOfLines, type DocumentSource, type TextChunk } from "./search.js";
8
+ import { pagesOfLines, pause, type DocumentSource, type ScanFeed, type TextChunk } from "./search.js";
9
9
  import { canSerialize, parseTextIndex, positionOf, serializeTextIndex, TextIndexBuilder, type TextIndex } from "./text-index.js";
10
10
  import { foldCase, LineIndex } from "./text.js";
11
11
  import type { DocumentMeta, DocumentStore } from "./types.js";
@@ -49,7 +49,7 @@ const decoder = new TextDecoder("utf-8");
49
49
  const gone = (id: string) => new Error(`${id} is no longer available on the server. Ask the user to attach the file again.`);
50
50
 
51
51
  /** A scan of a document: fed the pieces in order until it says it is done. */
52
- type Consumer = { feed: (chunk: TextChunk) => boolean | void; done: boolean; settle: (error?: unknown) => void };
52
+ type Consumer = { feed: ScanFeed; done: boolean; settle: (error?: unknown) => void };
53
53
 
54
54
  export class RangedDocument implements DocumentSource {
55
55
  /**
@@ -140,7 +140,7 @@ export class RangedDocument implements DocumentSource {
140
140
  * the pieces are then read, decoded and lowercased once, for all of them. A scan asked for once
141
141
  * the pass has started waits for the next one, since every scan must see the text from the start.
142
142
  */
143
- scan(feed: (chunk: TextChunk) => boolean | void, signal?: AbortSignal): Promise<void> {
143
+ scan(feed: ScanFeed, signal?: AbortSignal): Promise<void> {
144
144
  return new Promise<void>((resolve, reject) => {
145
145
  if (signal?.aborted) {
146
146
  reject(signal.reason);
@@ -184,14 +184,21 @@ export class RangedDocument implements DocumentSource {
184
184
  for (const consumer of group) {
185
185
  if (consumer.done) continue;
186
186
  try {
187
- if (consumer.feed(chunk) === true) consumer.settle();
188
- else open++;
187
+ let more = consumer.feed(chunk);
188
+ // A scan that asks for the same piece again has stopped part-way to let other work run.
189
+ while (more === "again" && !consumer.done) {
190
+ await pause();
191
+ slice = performance.now();
192
+ more = consumer.feed(chunk);
193
+ }
194
+ if (more === true) consumer.settle();
195
+ else if (!consumer.done) open++;
189
196
  } catch (error) {
190
197
  consumer.settle(error);
191
198
  }
192
199
  // Many scans on one piece add up: give other work (answers streaming to other users) a turn.
193
200
  if (performance.now() - slice > YIELD_AFTER_MS) {
194
- await new Promise((resolve) => setImmediate(resolve));
201
+ await pause();
195
202
  slice = performance.now();
196
203
  }
197
204
  }
package/src/retry.ts ADDED
@@ -0,0 +1,132 @@
1
+ // One rule for sending a model request again, used by the chat loop and by whole-file part reads.
2
+
3
+ /** How a model request that failed is sent again. */
4
+ export type RetryOptions = {
5
+ /** How many times a failed request is sent again. Defaults to 3. 0 turns it off. */
6
+ retries?: number;
7
+ /** The first wait in milliseconds. Each later one is twice as long. Defaults to 500. */
8
+ baseDelayMs?: number;
9
+ /**
10
+ * The longest wait in milliseconds. Defaults to 60,000. When the provider asks for a longer one
11
+ * (`Retry-After`), the request is not sent again and the error is reported.
12
+ */
13
+ maxDelayMs?: number;
14
+ /** For tests: the wait itself. */
15
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
16
+ /** For tests: the source of the jitter, a number from 0 up to 1. */
17
+ random?: () => number;
18
+ };
19
+
20
+ export const DEFAULT_RETRIES = 3;
21
+ const DEFAULT_BASE_DELAY_MS = 500;
22
+ const DEFAULT_MAX_DELAY_MS = 60_000;
23
+
24
+ /** The HTTP status of an error, when it carries one. 0 stands for a connection that failed. */
25
+ export function statusOf(error: unknown): number | undefined {
26
+ const status = (error as { status?: unknown } | null)?.status;
27
+ return typeof status === "number" && Number.isFinite(status) ? status : undefined;
28
+ }
29
+
30
+ /**
31
+ * Whether a request that failed with this status is worth sending again: the model could not be
32
+ * reached, timed out, was busy, or failed on its side. A request it refused (400, 401, 403, 404)
33
+ * would be refused again.
34
+ */
35
+ export function isRetryableStatus(status: number): boolean {
36
+ return status === 0 || status === 408 || status === 409 || status === 429 || status >= 500;
37
+ }
38
+
39
+ /** A wait that ends early, with the signal's reason, when the signal aborts. */
40
+ export function sleep(ms: number, signal?: AbortSignal): Promise<void> {
41
+ return new Promise<void>((resolve, reject) => {
42
+ if (signal?.aborted) {
43
+ reject(signal.reason);
44
+ return;
45
+ }
46
+ const done = () => {
47
+ signal?.removeEventListener("abort", stop);
48
+ resolve();
49
+ };
50
+ const timer = setTimeout(done, ms);
51
+ const stop = () => {
52
+ clearTimeout(timer);
53
+ reject(signal!.reason);
54
+ };
55
+ signal?.addEventListener("abort", stop, { once: true });
56
+ });
57
+ }
58
+
59
+ /**
60
+ * The wait a provider asked for, in milliseconds: the `retry-after-ms` or `Retry-After` header
61
+ * (seconds, or a date), or the `retryDelay` of a `google.rpc.RetryInfo` in the error body ("17s").
62
+ */
63
+ export function retryAfterMs(headers: Headers | undefined, body?: unknown, now: () => number = Date.now): number | undefined {
64
+ const exact = Number(headers?.get("retry-after-ms"));
65
+ if (headers?.get("retry-after-ms") && Number.isFinite(exact) && exact >= 0) return exact;
66
+ const header = headers?.get("retry-after");
67
+ if (header) {
68
+ const seconds = Number(header);
69
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.round(seconds * 1000);
70
+ const date = Date.parse(header);
71
+ if (Number.isFinite(date)) return Math.max(0, date - now());
72
+ }
73
+ const details = (body as { error?: { details?: unknown } } | null)?.error?.details;
74
+ if (Array.isArray(details)) {
75
+ for (const detail of details as Array<{ retryDelay?: unknown }>) {
76
+ const match = typeof detail?.retryDelay === "string" ? /^(\d+(?:\.\d+)?)s$/.exec(detail.retryDelay) : null;
77
+ if (match) return Math.round(Number(match[1]) * 1000);
78
+ }
79
+ }
80
+ return undefined;
81
+ }
82
+
83
+ export type RetryNotice = { error: unknown; attempt: number; delayMs: number };
84
+
85
+ /**
86
+ * Runs a model request, and runs it again when it failed in a way that another try can mend.
87
+ * - An error with a retryable status (see `isRetryableStatus`) is retried after a wait that doubles
88
+ * each time, with jitter, or after the wait the provider asked for.
89
+ * - An error with another status is not retried.
90
+ * - An error without a status is retried once, at once, when `unknownErrors` is "once"; otherwise not.
91
+ * Nothing is retried after the signal aborted, or once `canRetry` says no.
92
+ */
93
+ export async function withRetry<T>(run: () => Promise<T>, options: {
94
+ retry?: RetryOptions | undefined;
95
+ signal?: AbortSignal | undefined;
96
+ /** False once the attempt did something that must not happen twice: text was shown to the user. */
97
+ canRetry?: () => boolean;
98
+ onRetry?: (notice: RetryNotice) => void;
99
+ unknownErrors?: "once" | "never";
100
+ } = {}): Promise<T> {
101
+ const retries = Math.max(0, Math.trunc(options.retry?.retries ?? DEFAULT_RETRIES));
102
+ const base = Math.max(0, options.retry?.baseDelayMs ?? DEFAULT_BASE_DELAY_MS);
103
+ const longest = Math.max(0, options.retry?.maxDelayMs ?? DEFAULT_MAX_DELAY_MS);
104
+ const wait = options.retry?.sleep ?? sleep;
105
+ const random = options.retry?.random ?? Math.random;
106
+ let unknownRetried = false;
107
+ for (let attempt = 0; ; attempt++) {
108
+ try {
109
+ return await run();
110
+ } catch (error) {
111
+ if (options.signal?.aborted || options.canRetry?.() === false) throw error;
112
+ const status = statusOf(error);
113
+ if (status === undefined) {
114
+ if (options.unknownErrors !== "once" || unknownRetried || retries === 0) throw error;
115
+ unknownRetried = true;
116
+ continue;
117
+ }
118
+ if (!isRetryableStatus(status) || attempt >= retries) throw error;
119
+ const asked = (error as { retryAfterMs?: unknown }).retryAfterMs;
120
+ let delayMs: number;
121
+ if (typeof asked === "number" && Number.isFinite(asked) && asked >= 0) {
122
+ // Waiting longer than the caller allows helps no one who is waiting for an answer.
123
+ if (asked > longest) throw error;
124
+ delayMs = asked;
125
+ } else {
126
+ delayMs = Math.min(longest, base * 2 ** attempt * (0.5 + random() / 2));
127
+ }
128
+ options.onRetry?.({ error, attempt: attempt + 1, delayMs });
129
+ await wait(delayMs, options.signal);
130
+ }
131
+ }
132
+ }
package/src/search.ts CHANGED
@@ -6,7 +6,14 @@ import type { DocumentMeta, StoredDocument } from "./types.js";
6
6
  const MAX_OCCURRENCES_PER_TERM = 200_000;
7
7
  const MAX_EXACT_MATCHES = 1_000_000;
8
8
  const MAX_PHRASE_PASSAGES = 10_000;
9
- const REGEX_TIME_LIMIT_MS = 3_000;
9
+ /** The most time one regex search may spend matching. */
10
+ export const REGEX_TIME_LIMIT_MS = 3_000;
11
+ /**
12
+ * A regex scan runs in slices of this length, and other work gets a turn between two slices. A
13
+ * line that takes two whole slices is a pattern that backtracks without end on it: the search
14
+ * stops there, long before its time limit.
15
+ */
16
+ const REGEX_SLICE_MS = 250;
10
17
  const SHOWN_LINE_CHARACTERS = 400;
11
18
 
12
19
  const STOPWORDS = new Set([
@@ -53,13 +60,31 @@ export interface DocumentSource {
53
60
  * Optional: feeds the pieces in order to `feed` until it returns true, sharing one pass over the
54
61
  * text with other scans of the same document where it can.
55
62
  */
56
- scan?(feed: (chunk: TextChunk) => boolean | void, signal?: AbortSignal): Promise<void>;
63
+ scan?(feed: ScanFeed, signal?: AbortSignal): Promise<void>;
57
64
  }
58
65
 
66
+ /**
67
+ * What a scan does with a piece of the text. True: it has all it needs, so nothing more is read.
68
+ * "again": it stopped part-way through the piece to let other work run, and wants the same piece
69
+ * once more.
70
+ */
71
+ export type ScanFeed = (chunk: TextChunk) => boolean | void | "again";
72
+
73
+ /** Lets other work on the server run (an answer streaming to another user) before going on. */
74
+ export const pause = () => new Promise<void>((resolve) => setImmediate(resolve));
75
+
59
76
  /** Feeds a document's text, a piece at a time, to `feed` until it returns true or the text ends. */
60
- export async function scanSource(source: DocumentSource, feed: (chunk: TextChunk) => boolean | void, signal?: AbortSignal): Promise<void> {
77
+ export async function scanSource(source: DocumentSource, feed: ScanFeed, signal?: AbortSignal): Promise<void> {
61
78
  if (source.scan) return source.scan(feed, signal);
62
- for await (const chunk of source.chunks(signal)) if (feed(chunk) === true) break;
79
+ for await (const chunk of source.chunks(signal)) {
80
+ let more = feed(chunk);
81
+ while (more === "again") {
82
+ await pause();
83
+ signal?.throwIfAborted();
84
+ more = feed(chunk);
85
+ }
86
+ if (more === true) break;
87
+ }
63
88
  }
64
89
 
65
90
  /** Lines as the tools show them: "12| text", one a line. */
@@ -212,6 +237,8 @@ export type GrepOptions = {
212
237
  contextLines: number;
213
238
  /** Regex mode only. Defaults to 3 seconds of scanning. */
214
239
  timeLimitMs?: number;
240
+ /** Regex mode only: the time spent matching is added to `usedMs`, for a caller that keeps a budget over several searches. */
241
+ regexClock?: { usedMs: number };
215
242
  };
216
243
 
217
244
  function clip(line: string, column: number): string {
@@ -263,6 +290,19 @@ export function unsafeRegexReason(pattern: string): string | null {
263
290
  return null;
264
291
  }
265
292
 
293
+ /**
294
+ * The pattern as a regular expression. With the Unicode flag when the pattern allows it, so that
295
+ * `\p{L}` means a letter and a character outside the basic plane is one character; without it for
296
+ * a pattern that is only valid the old way (`[\w-.]`, `\-`).
297
+ */
298
+ function compileRegex(pattern: string, flags: string): RegExp {
299
+ try {
300
+ return new RegExp(pattern, `${flags}u`);
301
+ } catch {
302
+ return new RegExp(pattern, flags);
303
+ }
304
+ }
305
+
266
306
  const newlinesIn = (text: string) => text.split("\n").length - 1;
267
307
 
268
308
  /**
@@ -308,13 +348,17 @@ class LineSearch {
308
348
  private lastLine = 0;
309
349
  private readonly pattern?: RegExp;
310
350
  private timeLeft: number;
351
+ /** Regex mode: the piece whose scan stopped at the end of a time slice, and the next line of it to look at. */
352
+ private unfinished?: { chunk: TextChunk; next: number };
353
+ /** Regex mode: the line that took a whole slice without being finished. A second such slice ends the search. */
354
+ private stuck?: number;
311
355
 
312
356
  constructor(query: string, private readonly settings: GrepOptions, private readonly lineCount: number) {
313
357
  if (!query) throw new Error("The search query is empty.");
314
358
  if (settings.regex) {
315
359
  const problem = unsafeRegexReason(query);
316
360
  if (problem) throw new Error(problem);
317
- this.pattern = new RegExp(query, settings.caseSensitive ? "" : "i");
361
+ this.pattern = compileRegex(query, settings.caseSensitive ? "" : "i");
318
362
  } else {
319
363
  this.needle = settings.caseSensitive ? query : foldCase(query);
320
364
  this.newlines = newlinesIn(this.needle);
@@ -324,10 +368,25 @@ class LineSearch {
324
368
  this.keep = this.context + this.newlines;
325
369
  }
326
370
 
371
+ /** Scans a piece to its end, without a pause: for a caller that cannot wait. See `addSome`. */
327
372
  add(chunk: TextChunk): void {
328
- if (this.done) return;
329
- if (this.pattern) this.scanRegex(chunk);
330
- else this.scanExact(chunk);
373
+ while (!this.addSome(chunk)) {
374
+ // The next slice of a regex scan.
375
+ }
376
+ }
377
+
378
+ /**
379
+ * Scans a piece, or goes on scanning it. False means that a regex scan reached the end of a time
380
+ * slice with lines of this piece still to look at: let other work run, then call this again with
381
+ * the same piece. Exact search always finishes the piece.
382
+ */
383
+ addSome(chunk: TextChunk): boolean {
384
+ if (this.done) return true;
385
+ if (this.pattern) {
386
+ if (!this.scanRegex(chunk)) return false;
387
+ } else {
388
+ this.scanExact(chunk);
389
+ }
331
390
  if (this.unfilled > 0) {
332
391
  const last = chunk.firstLine + chunk.lines.lineCount - 1;
333
392
  for (const [line, text] of this.shown) {
@@ -339,6 +398,7 @@ class LineSearch {
339
398
  }
340
399
  }
341
400
  this.recent = remember(this.recent, chunk, this.keep);
401
+ return true;
342
402
  }
343
403
 
344
404
  /** Lines to show that were not in the pieces read (the scan stopped early). Read them and `fill` them. */
@@ -410,27 +470,52 @@ class LineSearch {
410
470
  }
411
471
  }
412
472
 
413
- private scanRegex(chunk: TextChunk): void {
414
- if (this.timeLeft <= 0) {
473
+ /**
474
+ * One time slice of a regex scan of a piece. True when the piece is finished, or the search is
475
+ * (out of time, or stopped at a line the pattern cannot get past); false when lines of the piece
476
+ * are left for the next slice.
477
+ */
478
+ private scanRegex(chunk: TextChunk): boolean {
479
+ const stop = (): true => {
415
480
  this.stoppedEarly = true;
416
481
  this.done = true;
417
- return;
418
- }
482
+ return true;
483
+ };
484
+ // Where to go on: in a piece that was left at the end of a slice, or at the start of a new one.
485
+ let next = this.unfinished?.chunk === chunk ? this.unfinished.next : 1;
486
+ this.unfinished = undefined;
487
+ if (this.timeLeft <= 0) return stop();
419
488
  const pattern = this.pattern!;
420
489
  const { lines, firstLine } = chunk;
490
+ const from = next;
491
+ const slice = Math.min(this.timeLeft, REGEX_SLICE_MS);
421
492
  const started = performance.now();
422
493
  const finished = withinTimeLimit(() => {
423
- for (let local = 1; local <= lines.lineCount; local++) {
424
- const text = lines.line(local);
494
+ for (; next <= lines.lineCount; next++) {
495
+ const line = firstLine + next - 1;
496
+ const text = lines.line(next);
425
497
  const match = pattern.exec(text);
426
- if (match) this.record(firstLine + local - 1, match.index, text);
498
+ // A line is recorded once, also when a slice ended while it was being recorded and it is looked at again.
499
+ if (match && line > this.lastLine) {
500
+ this.lastLine = line;
501
+ this.record(line, match.index, text);
502
+ }
427
503
  }
428
- }, this.timeLeft);
429
- this.timeLeft -= performance.now() - started;
430
- if (!finished) {
431
- this.stoppedEarly = true;
432
- this.done = true;
504
+ }, slice);
505
+ const spent = performance.now() - started;
506
+ this.timeLeft -= spent;
507
+ if (this.settings.regexClock) this.settings.regexClock.usedMs += spent;
508
+ if (finished) return true;
509
+ if (this.timeLeft <= 0) return stop();
510
+ // The slice ended in the middle of line `next`. A whole slice without one line finished can be
511
+ // a stall of the machine, once. Twice on the same line, it is the pattern.
512
+ if (next === from && slice >= REGEX_SLICE_MS) {
513
+ const line = firstLine + next - 1;
514
+ if (this.stuck === line) return stop();
515
+ this.stuck = line;
433
516
  }
517
+ this.unfinished = { chunk, next };
518
+ return false;
434
519
  }
435
520
  }
436
521
 
@@ -455,12 +540,18 @@ export function grep(document: SearchableDocument, query: string, options: GrepO
455
540
 
456
541
  /** `grep` over any document: one held in memory, or one read from the store a piece at a time. */
457
542
  export async function grepSource(source: DocumentSource, query: string, options: GrepOptions & { signal?: AbortSignal }): Promise<GrepResult> {
458
- if (source instanceof SearchableDocument) return grep(source, query, options);
459
543
  const search = new LineSearch(query, options, source.lineCount);
460
- await scanSource(source, (chunk) => {
461
- search.add(chunk);
462
- return search.done;
463
- }, options.signal);
544
+ if (source instanceof SearchableDocument) {
545
+ const chunk = source.wholeChunk();
546
+ // A regex scan runs a slice at a time, and other work gets a turn between two slices.
547
+ while (!search.addSome(chunk)) {
548
+ await pause();
549
+ options.signal?.throwIfAborted();
550
+ }
551
+ for (const line of search.missing()) search.fill(line, source.lines.line(line));
552
+ return search.result();
553
+ }
554
+ await scanSource(source, (chunk) => (search.addSome(chunk) ? search.done : "again"), options.signal);
464
555
  const missing = search.missing();
465
556
  if (missing.length) await readSome(source, missing, (line, text) => search.fill(line, text));
466
557
  return search.result();
package/src/sse.ts ADDED
@@ -0,0 +1,34 @@
1
+ /** Parses a `text/event-stream` body into JSON objects, one per `data:` event. */
2
+ export async function* parseSseJson<T>(stream: ReadableStream<Uint8Array>): AsyncGenerator<T> {
3
+ const reader = stream.getReader();
4
+ const decoder = new TextDecoder();
5
+ let buffer = "";
6
+ const parse = (block: string): T | undefined => {
7
+ const data = block
8
+ .split("\n")
9
+ .filter((line) => line.startsWith("data:"))
10
+ .map((line) => line.slice(5).trimStart())
11
+ .join("\n");
12
+ return data && data !== "[DONE]" ? JSON.parse(data) as T : undefined;
13
+ };
14
+ try {
15
+ while (true) {
16
+ const { done, value } = await reader.read();
17
+ buffer += decoder.decode(value, { stream: !done });
18
+ buffer = buffer.replace(/\r\n/g, "\n");
19
+ let boundary = buffer.indexOf("\n\n");
20
+ while (boundary >= 0) {
21
+ const event = parse(buffer.slice(0, boundary));
22
+ buffer = buffer.slice(boundary + 2);
23
+ if (event !== undefined) yield event;
24
+ boundary = buffer.indexOf("\n\n");
25
+ }
26
+ if (done) break;
27
+ }
28
+ const last = buffer.trim() ? parse(buffer.trim()) : undefined;
29
+ if (last !== undefined) yield last;
30
+ } finally {
31
+ await reader.cancel().catch(() => undefined);
32
+ reader.releaseLock();
33
+ }
34
+ }
package/src/stores.ts CHANGED
@@ -74,6 +74,18 @@ const RETRY_RENAME = new Set(["EPERM", "EACCES", "EBUSY"]);
74
74
  const RENAME_PAUSES_MS = [10, 20, 40, 80, 160, 320, 500, 500, 500, 500];
75
75
 
76
76
  const code = (error: unknown) => (error as { code?: unknown } | null)?.code;
77
+ /** There is no such file. Every other failure (a volume that does not answer, too many open files) says nothing about the file. */
78
+ const missing = (error: unknown) => code(error) === "ENOENT";
79
+
80
+ /** Metadata as it was written, or undefined for text that is not that: cut short, or damaged. */
81
+ function parseMeta(raw: string): DocumentMeta | undefined {
82
+ try {
83
+ const meta = JSON.parse(raw) as DocumentMeta | null;
84
+ return meta !== null && typeof meta === "object" && typeof meta.expiresAt === "string" ? meta : undefined;
85
+ } catch {
86
+ return undefined;
87
+ }
88
+ }
77
89
 
78
90
  /**
79
91
  * Writes a file whole or not at all, as other processes see it: to a temporary name first, then
@@ -142,12 +154,18 @@ export class FileDocumentStore implements DocumentStore {
142
154
  async getMeta(id: string): Promise<DocumentMeta | undefined> {
143
155
  const paths = this.paths(id);
144
156
  if (!paths) return undefined;
145
- let meta: DocumentMeta;
157
+ let raw: string;
146
158
  try {
147
- meta = JSON.parse(await readFile(paths.meta, "utf8")) as DocumentMeta;
148
- } catch {
149
- return undefined;
159
+ raw = await readFile(paths.meta, "utf8");
160
+ } catch (error) {
161
+ // Only a file that is not there means that the document is not there. A read that failed for
162
+ // another reason is thrown, so that a busy volume is not taken for a deleted document.
163
+ if (missing(error)) return undefined;
164
+ throw error;
150
165
  }
166
+ // Metadata that cannot be parsed is an upload being written by a server of 0.3.x, or damaged: absent.
167
+ const meta = parseMeta(raw);
168
+ if (!meta) return undefined;
151
169
  if (expired(meta, this.now())) {
152
170
  await this.delete(id);
153
171
  return undefined;
@@ -161,8 +179,9 @@ export class FileDocumentStore implements DocumentStore {
161
179
  if (!meta || !paths) return undefined;
162
180
  try {
163
181
  return { meta, text: await readFile(paths.text, "utf8") };
164
- } catch {
165
- return undefined;
182
+ } catch (error) {
183
+ if (missing(error)) return undefined;
184
+ throw error;
166
185
  }
167
186
  }
168
187
 
@@ -213,7 +232,11 @@ export class FileDocumentStore implements DocumentStore {
213
232
  const paths = this.paths(id);
214
233
  if (!paths) return false;
215
234
  const existed = Boolean(await readFile(paths.meta, "utf8").catch(() => null));
216
- await Promise.all([paths.meta, paths.text, paths.original, paths.index].map((file) => rm(file, { force: true })));
235
+ // The metadata first: a document is there while its metadata is. If that file cannot be removed,
236
+ // nothing else is, and the document stays whole. The other way round, a document whose text is
237
+ // gone would still be listed.
238
+ await rm(paths.meta, { force: true });
239
+ await Promise.all([paths.text, paths.original, paths.index].map((file) => rm(file, { force: true })));
217
240
  return existed;
218
241
  }
219
242
 
@@ -232,16 +255,21 @@ export class FileDocumentStore implements DocumentStore {
232
255
  try {
233
256
  const file = await readFile(paths.original);
234
257
  return new Uint8Array(file.buffer, file.byteOffset, file.byteLength);
235
- } catch {
236
- return undefined;
258
+ } catch (error) {
259
+ if (missing(error)) return undefined;
260
+ throw error;
237
261
  }
238
262
  }
239
263
 
240
264
  /**
241
265
  * Removes expired documents and returns how many. Also removes files that belong to no
242
266
  * document, and temporary files, once they are older than `orphanAgeMs`. A document whose
243
- * metadata cannot be read is removed only when that file is that old too: it may be being
267
+ * metadata is not valid is removed only when that file is that old too: it may be being
244
268
  * written by a server of an older version, which does not write whole files.
269
+ *
270
+ * A document whose metadata could not be read at all (the volume did not answer, too many files
271
+ * were open) is left alone, whatever its age: the next sweep looks at it again. A document that
272
+ * cannot be removed is left for the next sweep too, and does not stop this one.
245
273
  */
246
274
  async sweep(now = this.now()): Promise<number> {
247
275
  let entries: string[];
@@ -266,11 +294,19 @@ export class FileDocumentStore implements DocumentStore {
266
294
  for (const [id, names] of files) {
267
295
  const metaFile = `${id}.json`;
268
296
  if (names.includes(metaFile)) {
269
- const meta = await readFile(path.join(this.directory, metaFile), "utf8").then((value) => JSON.parse(value) as DocumentMeta).catch(() => null);
270
- if (meta ? expired(meta, now) : await old(metaFile)) {
271
- await this.delete(id);
272
- removed++;
273
- continue;
297
+ let raw: string | undefined;
298
+ try {
299
+ raw = await readFile(path.join(this.directory, metaFile), "utf8");
300
+ } catch (error) {
301
+ // Not read is not the same as not valid: nothing of this document is touched.
302
+ if (!missing(error)) continue;
303
+ }
304
+ if (raw !== undefined) {
305
+ const meta = parseMeta(raw);
306
+ if (meta ? expired(meta, now) : await old(metaFile)) {
307
+ if (await this.delete(id).then(() => true, () => false)) removed++;
308
+ continue;
309
+ }
274
310
  }
275
311
  }
276
312
  // Temporary files of this document, and every file of one without metadata, once they are old.