llm-large-files 0.3.6 → 0.4.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 (90) hide show
  1. package/CHANGELOG.md +115 -0
  2. package/dist/cache.d.ts +49 -0
  3. package/dist/cache.d.ts.map +1 -0
  4. package/dist/cache.js +110 -0
  5. package/dist/cache.js.map +1 -0
  6. package/dist/errors.d.ts +21 -0
  7. package/dist/errors.d.ts.map +1 -0
  8. package/dist/errors.js +44 -0
  9. package/dist/errors.js.map +1 -0
  10. package/dist/gemini/chat.d.ts +5 -0
  11. package/dist/gemini/chat.d.ts.map +1 -1
  12. package/dist/gemini/chat.js +17 -1
  13. package/dist/gemini/chat.js.map +1 -1
  14. package/dist/gemini/generate.d.ts +10 -0
  15. package/dist/gemini/generate.d.ts.map +1 -1
  16. package/dist/gemini/generate.js +110 -25
  17. package/dist/gemini/generate.js.map +1 -1
  18. package/dist/gemini/index.d.ts +1 -1
  19. package/dist/gemini/index.d.ts.map +1 -1
  20. package/dist/gemini/index.js +1 -1
  21. package/dist/gemini/index.js.map +1 -1
  22. package/dist/index.d.ts +3 -2
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +3 -2
  25. package/dist/index.js.map +1 -1
  26. package/dist/library.d.ts +48 -2
  27. package/dist/library.d.ts.map +1 -1
  28. package/dist/library.js +192 -52
  29. package/dist/library.js.map +1 -1
  30. package/dist/limiter.d.ts +20 -0
  31. package/dist/limiter.d.ts.map +1 -0
  32. package/dist/limiter.js +55 -0
  33. package/dist/limiter.js.map +1 -0
  34. package/dist/map-reduce.d.ts +14 -4
  35. package/dist/map-reduce.d.ts.map +1 -1
  36. package/dist/map-reduce.js +99 -33
  37. package/dist/map-reduce.js.map +1 -1
  38. package/dist/plan.d.ts +25 -7
  39. package/dist/plan.d.ts.map +1 -1
  40. package/dist/plan.js +51 -13
  41. package/dist/plan.js.map +1 -1
  42. package/dist/ranged.d.ts +102 -0
  43. package/dist/ranged.d.ts.map +1 -0
  44. package/dist/ranged.js +321 -0
  45. package/dist/ranged.js.map +1 -0
  46. package/dist/search.d.ts +93 -15
  47. package/dist/search.d.ts.map +1 -1
  48. package/dist/search.js +472 -131
  49. package/dist/search.js.map +1 -1
  50. package/dist/stores.d.ts +26 -2
  51. package/dist/stores.d.ts.map +1 -1
  52. package/dist/stores.js +181 -21
  53. package/dist/stores.js.map +1 -1
  54. package/dist/text-index.d.ts +64 -0
  55. package/dist/text-index.d.ts.map +1 -0
  56. package/dist/text-index.js +211 -0
  57. package/dist/text-index.js.map +1 -0
  58. package/dist/text.d.ts +14 -2
  59. package/dist/text.d.ts.map +1 -1
  60. package/dist/text.js +50 -16
  61. package/dist/text.js.map +1 -1
  62. package/dist/tools.d.ts +14 -2
  63. package/dist/tools.d.ts.map +1 -1
  64. package/dist/tools.js +53 -21
  65. package/dist/tools.js.map +1 -1
  66. package/dist/types.d.ts +20 -0
  67. package/dist/types.d.ts.map +1 -1
  68. package/docs/api.md +24 -10
  69. package/docs/configuration.md +50 -3
  70. package/docs/getting-started.md +2 -0
  71. package/docs/how-it-works.md +11 -3
  72. package/docs/security.md +21 -3
  73. package/package.json +7 -3
  74. package/src/cache.ts +107 -0
  75. package/src/errors.ts +42 -0
  76. package/src/gemini/chat.ts +22 -1
  77. package/src/gemini/generate.ts +107 -25
  78. package/src/gemini/index.ts +1 -1
  79. package/src/index.ts +3 -2
  80. package/src/library.ts +229 -50
  81. package/src/limiter.ts +51 -0
  82. package/src/map-reduce.ts +101 -33
  83. package/src/plan.ts +54 -14
  84. package/src/ranged.ts +355 -0
  85. package/src/search.ts +524 -121
  86. package/src/stores.ts +178 -23
  87. package/src/text-index.ts +228 -0
  88. package/src/text.ts +46 -13
  89. package/src/tools.ts +61 -23
  90. package/src/types.ts +20 -0
@@ -73,9 +73,36 @@ export function geminiFunctionResponseTurns(calls: GeminiToolAnswer[], options:
73
73
  return [{ role: "user", parts: responses }, ...(files.length > 0 ? [{ role: "user" as const, parts: files }] : [])];
74
74
  }
75
75
 
76
+ /**
77
+ * A model that thinks counts its thoughts in `maxOutputTokens`. Asked for 4,096 tokens of notes on
78
+ * a part of a log, Gemini 3.8 Flash spent 3,931 of them thinking and wrote two lines, and Gemini 4
79
+ * wrote nothing at all (November 2026). A reply that was cut off that way is asked for again with
80
+ * this limit, the least Google recommends for a Gemini 4 model.
81
+ */
82
+ export const THINKING_OUTPUT_TOKENS = 32_768;
83
+
84
+ /**
85
+ * What has been learned about the model behind a URL, so that a whole-file read does not pay for
86
+ * the wasted request with every part: the output limit it needs, or 0 when it refused that limit.
87
+ */
88
+ const learnedLimits = new Map<string, number>();
89
+ /** The first request to a URL that is still on its way. Others wait for what it learns. */
90
+ const firstRequests = new Map<string, Promise<void>>();
91
+ /** URLs that have answered at least once. */
92
+ const answered = new Set<string>();
93
+ const MOST_REMEMBERED = 200;
94
+
95
+ function remember(url: string, limit: number): void {
96
+ if (learnedLimits.size >= MOST_REMEMBERED && !learnedLimits.has(url)) learnedLimits.clear();
97
+ learnedLimits.set(url, limit);
98
+ }
99
+
76
100
  /**
77
101
  * A `GenerateText` backed by a non-streaming `:generateContent` endpoint.
78
102
  * `generationConfig` lets the caller apply model-specific rules (thinking level, output floors).
103
+ *
104
+ * When a reply stops at the output limit with most of that limit spent on thoughts, the request
105
+ * is sent once more with `THINKING_OUTPUT_TOKENS`, and later requests to the same URL start there.
79
106
  */
80
107
  export function createGeminiGenerateText(options: {
81
108
  url: string;
@@ -85,31 +112,86 @@ export function createGeminiGenerateText(options: {
85
112
  timeoutMs?: number;
86
113
  }): GenerateText {
87
114
  const fetchImpl = options.fetchImpl ?? fetch;
115
+ const { url } = options;
88
116
  return async ({ system, prompt, maxOutputTokens, signal, onTruncated }) => {
89
- const timeout = AbortSignal.timeout(options.timeoutMs ?? 180_000);
90
- const response = await fetchImpl(options.url, {
91
- method: "POST",
92
- headers: options.headers,
93
- signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
94
- body: JSON.stringify({
95
- contents: [{ role: "user", parts: [{ text: prompt }] }],
96
- systemInstruction: { role: "system", parts: [{ text: system }] },
97
- generationConfig: options.generationConfig?.(maxOutputTokens) ?? { maxOutputTokens, temperature: 0.2 },
98
- }),
99
- });
100
- const data = await response.json().catch(() => null) as {
101
- error?: { message?: string };
102
- candidates?: Array<{ finishReason?: string; content?: { parts?: Array<{ text?: unknown; thought?: boolean }> } }>;
103
- } | null;
104
- if (!response.ok) throw new Error(data?.error?.message ?? `The model returned HTTP ${response.status}.`);
105
- const candidate = data?.candidates?.[0];
106
- const text = (candidate?.content?.parts ?? [])
107
- .filter((part) => part.thought !== true && typeof part.text === "string")
108
- .map((part) => part.text as string)
109
- .join("");
110
- if (!text.trim()) throw new Error(`The model returned no text${candidate?.finishReason ? ` (${candidate.finishReason})` : ""}.`);
111
- // The text stops mid-list when the output limit is reached. Say so instead of passing it off as complete.
112
- if (candidate?.finishReason === "MAX_TOKENS") onTruncated?.();
113
- return text;
117
+ /** One request with an output limit: the text of the reply, why it ended, and what it thought. */
118
+ const send = async (limit: number): Promise<{ text: string; finishReason?: string; thoughts: number }> => {
119
+ const timeout = AbortSignal.timeout(options.timeoutMs ?? 180_000);
120
+ const response = await fetchImpl(url, {
121
+ method: "POST",
122
+ headers: options.headers,
123
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
124
+ body: JSON.stringify({
125
+ contents: [{ role: "user", parts: [{ text: prompt }] }],
126
+ systemInstruction: { role: "system", parts: [{ text: system }] },
127
+ generationConfig: options.generationConfig?.(limit) ?? { maxOutputTokens: limit, temperature: 0.2 },
128
+ }),
129
+ });
130
+ const data = await response.json().catch(() => null) as {
131
+ error?: { message?: string };
132
+ candidates?: Array<{ finishReason?: string; content?: { parts?: Array<{ text?: unknown; thought?: boolean }> } }>;
133
+ usageMetadata?: { thoughtsTokenCount?: unknown };
134
+ } | null;
135
+ if (!response.ok) throw Object.assign(new Error(data?.error?.message ?? `The model returned HTTP ${response.status}.`), { status: response.status });
136
+ const candidate = data?.candidates?.[0];
137
+ const text = (candidate?.content?.parts ?? [])
138
+ .filter((part) => part.thought !== true && typeof part.text === "string")
139
+ .map((part) => part.text as string)
140
+ .join("");
141
+ const thoughts = data?.usageMetadata?.thoughtsTokenCount;
142
+ return {
143
+ text,
144
+ ...(candidate?.finishReason ? { finishReason: candidate.finishReason } : {}),
145
+ thoughts: typeof thoughts === "number" ? thoughts : 0,
146
+ };
147
+ };
148
+
149
+ // The first request to a model finds out whether it thinks its limit away. The parts of a
150
+ // whole-file read are sent four at a time: the others wait for it, and one request is wasted
151
+ // on such a model, not four.
152
+ let learned = () => undefined as void;
153
+ if (!answered.has(url)) {
154
+ const first = firstRequests.get(url);
155
+ if (first) {
156
+ await first;
157
+ signal?.throwIfAborted();
158
+ } else {
159
+ firstRequests.set(url, new Promise<void>((resolve) => {
160
+ learned = () => {
161
+ if (answered.size >= MOST_REMEMBERED) answered.clear();
162
+ answered.add(url);
163
+ firstRequests.delete(url);
164
+ resolve();
165
+ };
166
+ }));
167
+ }
168
+ }
169
+ try {
170
+ const known = learnedLimits.get(url);
171
+ const limit = Math.max(maxOutputTokens, known ?? 0);
172
+ let reply = await send(limit);
173
+ // Cut off, with nothing written or with at least half of the limit gone on thoughts: the
174
+ // limit was too low for this model, not the notes too long.
175
+ const starved = reply.finishReason === "MAX_TOKENS" && (!reply.text.trim() || reply.thoughts >= limit / 2);
176
+ if (starved && known !== 0 && limit < THINKING_OUTPUT_TOKENS) {
177
+ remember(url, THINKING_OUTPUT_TOKENS);
178
+ try {
179
+ reply = await send(THINKING_OUTPUT_TOKENS);
180
+ } catch (error) {
181
+ if (signal?.aborted) throw error;
182
+ // A model or a gateway that refuses the larger limit (HTTP 400) is not asked for it again.
183
+ // Any other failure says nothing about the limit: the next request starts with it. What
184
+ // the first reply had is kept; with nothing in it, this error is the one to report.
185
+ if ((error as { status?: unknown } | null)?.status === 400) remember(url, 0);
186
+ if (!reply.text.trim()) throw error;
187
+ }
188
+ }
189
+ if (!reply.text.trim()) throw new Error(`The model returned no text${reply.finishReason ? ` (${reply.finishReason})` : ""}.`);
190
+ // The text stops mid-list when the output limit is reached. Say so instead of passing it off as complete.
191
+ if (reply.finishReason === "MAX_TOKENS") onTruncated?.();
192
+ return reply.text;
193
+ } finally {
194
+ learned();
195
+ }
114
196
  };
115
197
  }
@@ -2,6 +2,6 @@ export { askGemini, DocumentsNotFoundError, EXPLORER_INSTRUCTION, FINAL_ANSWER_A
2
2
  export type { AskGeminiOptions, AskGeminiResult, ChatTurn, GeminiContent, GeminiPart } from "./chat.js";
3
3
  export { geminiApi, vertexAi, vertexHost } from "./endpoints.js";
4
4
  export type { GeminiEndpoint } from "./endpoints.js";
5
- export { createGeminiGenerateText, geminiFunctionResponses, geminiFunctionResponseTurns, toGeminiTools } from "./generate.js";
5
+ export { createGeminiGenerateText, geminiFunctionResponses, geminiFunctionResponseTurns, THINKING_OUTPUT_TOKENS, toGeminiTools } from "./generate.js";
6
6
  export type { GeminiFunctionCall, GeminiToolAnswer, GeminiToolFilePlacement } from "./generate.js";
7
7
  export { parseSseJson } from "./sse.js";
package/src/index.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  // Core: provider-neutral. Gemini helpers live in "llm-large-files/gemini",
2
2
  // Node HTTP handlers in "llm-large-files/node".
3
- export { createLargeFiles, DEFAULT_BUDGET, isDocumentId, toDocumentSummary } from "./library.js";
3
+ export { createLargeFiles, DEFAULT_BUDGET, DEFAULT_CACHE_BYTES, DEFAULT_WHOLE_DOCUMENT_BYTES, isDocumentId, NEVER_EXPIRES, toDocumentSummary } from "./library.js";
4
4
  export type { AccessOptions, IngestInput, LargeFiles, LargeFilesOptions, PrepareOptions, ToolOptions } from "./library.js";
5
+ export { DocumentStoreError } from "./errors.js";
5
6
  export { FileDocumentStore, MemoryDocumentStore, DOCUMENT_ID_PATTERN } from "./stores.js";
6
7
  export { createPdfExtractor, defaultExtractors, detectFormat } from "./extract.js";
7
8
  export type { PdfExtractorOptions } from "./extract.js";
8
9
  export { estimateTokens, utf8Bytes, jsonBytes } from "./text.js";
9
- export { MAX_VIEW_PAGES, TOOL_NAMES, toolResultSummary } from "./tools.js";
10
+ export { MAX_VIEW_PAGES, REGEX_BUDGET_MS, TOOL_NAMES, toolResultSummary } from "./tools.js";
10
11
  export type * from "./types.js";
package/src/library.ts CHANGED
@@ -1,10 +1,15 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { buildLogProfile, buildOutline, looksLikeLog } from "./analyze.js";
3
+ import { DocumentCache, documentVersion, type Sized } from "./cache.js";
4
+ import { DocumentStoreError } from "./errors.js";
3
5
  import { detectFormat, extractText } from "./extract.js";
4
- import { documentToolsInstruction, formatBytes, planDocuments, renderCard, renderInline } from "./plan.js";
5
- import { SearchableDocument } from "./search.js";
6
+ import { Limiter } from "./limiter.js";
7
+ import { canBeReadWhole, CARD_LINES, documentToolsInstruction, formatBytes, planDocuments, renderCard, renderInline } from "./plan.js";
8
+ import { openRangedDocument, pieceKey, type CachedPiece, type RangeStore, type ScanSettings } from "./ranged.js";
9
+ import { numberLines, SearchableDocument, type DocumentSource } from "./search.js";
6
10
  import { DOCUMENT_ID_PATTERN } from "./stores.js";
7
- import { estimateTokens, normalizeText, utf8Bytes, wrapLongLines } from "./text.js";
11
+ import { buildTextIndex, canSerialize, serializeTextIndex } from "./text-index.js";
12
+ import { estimateTokens, normalizeText, textSizes, wrapLongLines } from "./text.js";
8
13
  import { createDocumentTools } from "./tools.js";
9
14
  import type {
10
15
  Budget,
@@ -35,7 +40,10 @@ export type LargeFilesOptions = {
35
40
  store: DocumentStore;
36
41
  /** Your model's limits. Anything left out uses DEFAULT_BUDGET. */
37
42
  budget?: Partial<Budget>;
38
- /** How long uploaded documents are kept. Defaults to 72 hours. */
43
+ /**
44
+ * How long uploaded documents are kept. Defaults to 72 hours. `Infinity` keeps them until they
45
+ * are deleted: their `expiresAt` is then `NEVER_EXPIRES`.
46
+ */
39
47
  ttlMs?: number;
40
48
  /** Largest accepted upload. Defaults to 100 MB. */
41
49
  maxUploadBytes?: number;
@@ -53,8 +61,35 @@ export type LargeFilesOptions = {
53
61
  * is accepted. Defaults to 30. 0 refuses every PDF without text, as before.
54
62
  */
55
63
  scannedPdfPages?: number;
56
- /** How many parsed documents to keep in memory for repeated tool calls. Defaults to 6. */
64
+ /**
65
+ * The most memory, in bytes, that documents kept ready for repeated tool calls may take.
66
+ * Defaults to 256 MB. A document larger than this is read again for each call. 0 keeps none.
67
+ *
68
+ * Every use of a kept document first asks the store whether it is still there, so a document
69
+ * deleted or expired on another server sharing the store is never served from memory here.
70
+ */
71
+ cacheBytes?: number;
72
+ /**
73
+ * Also caps the number of documents kept (the only limit before 0.4). Unset: no cap on the
74
+ * number. The pieces kept of a document that is read by range are not counted, and go when
75
+ * their document does.
76
+ */
57
77
  cacheSize?: number;
78
+ /**
79
+ * Documents whose text is at most this many bytes are loaded whole into memory (and kept there
80
+ * within `cacheBytes`). Larger ones are read by range, when the store can (`readTextRange`, as
81
+ * `FileDocumentStore` does): a tool call reads the lines it needs, and a search reads the text a
82
+ * piece at a time, so memory does not grow with the size of the files or the number of users.
83
+ * Defaults to 2 MB. `Infinity` loads every document whole, as before 0.4; 0 reads every one by range.
84
+ */
85
+ wholeDocumentBytes?: number;
86
+ /** Reading by range: about this many bytes of text are read and searched at a time. Defaults to 1 MB. */
87
+ scanChunkBytes?: number;
88
+ /**
89
+ * Reading by range: how many scans of whole documents (searches, counting the parts of a file)
90
+ * run at once in this process. The others wait their turn. Defaults to 4.
91
+ */
92
+ maxConcurrentScans?: number;
58
93
  /** Clock override, for tests. */
59
94
  now?: () => Date;
60
95
  };
@@ -85,6 +120,13 @@ export type ToolOptions = {
85
120
  /** Progress of whole-document reads, for status messages. */
86
121
  onProgress?: ProgressListener;
87
122
  signal?: AbortSignal;
123
+ /**
124
+ * The most time, in milliseconds, that the regex searches of this tool set may take together.
125
+ * Past it, a regex search answers with an error that tells the model to search another way.
126
+ * Defaults to 6,000. One search still stops after 3,000, and at once at a line its pattern
127
+ * cannot get past.
128
+ */
129
+ regexBudgetMs?: number;
88
130
  /**
89
131
  * Offers `view_pages`, which hands the model real pages of a PDF whose original file is kept
90
132
  * (see `keepOriginals`). The pages come back as a file, so turn this on only when your loop
@@ -150,44 +192,154 @@ export function cleanFileName(raw: string): string {
150
192
  .slice(0, 255) || "file";
151
193
  }
152
194
 
195
+ /**
196
+ * A read of the store. Whatever it throws is passed on as a `DocumentStoreError`: a store that
197
+ * could not be read is not a document that is gone, and its own error names paths or hosts.
198
+ */
199
+ async function reading<T>(read: () => Promise<T>): Promise<T> {
200
+ try {
201
+ return await read();
202
+ } catch (error) {
203
+ throw error instanceof DocumentStoreError ? error : new DocumentStoreError(error);
204
+ }
205
+ }
206
+
207
+ /**
208
+ * The `expiresAt` of a document that never expires (`ttlMs: Infinity`): the last instant of the
209
+ * year 9999. A date, so that every comparison, and a server of an older version, reads it as any other.
210
+ */
211
+ export const NEVER_EXPIRES = "9999-12-31T23:59:59.999Z";
212
+
153
213
  function allowed(meta: DocumentMeta, access: AccessOptions | undefined): boolean {
154
214
  return meta.owner === undefined || meta.owner === access?.owner;
155
215
  }
156
216
 
217
+ /** Default for `cacheBytes`. */
218
+ export const DEFAULT_CACHE_BYTES = 256 * 1024 * 1024;
219
+ /** Default for `wholeDocumentBytes`. */
220
+ export const DEFAULT_WHOLE_DOCUMENT_BYTES = 2 * 1024 * 1024;
221
+
157
222
  export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
158
223
  const budget: Budget = { ...DEFAULT_BUDGET, ...options.budget };
159
224
  const ttlMs = options.ttlMs ?? 72 * 60 * 60 * 1000;
160
225
  const maxUploadBytes = options.maxUploadBytes ?? 100 * 1024 * 1024;
161
226
  const now = options.now ?? (() => new Date());
162
- const cacheSize = Math.max(1, options.cacheSize ?? 6);
163
- const cache = new Map<string, SearchableDocument>();
227
+ const { store } = options;
228
+ const cacheBytes = Math.max(0, options.cacheBytes ?? DEFAULT_CACHE_BYTES);
229
+ /** Documents ready to search, and decoded pieces of documents read by range, in one memory budget. */
230
+ const cache = new DocumentCache<Sized>(
231
+ cacheBytes,
232
+ options.cacheSize === undefined ? Number.POSITIVE_INFINITY : Math.max(0, Math.trunc(options.cacheSize)),
233
+ );
234
+ /** Forgets everything kept of a document: the document, and its pieces. */
235
+ const forget = (id: string) => {
236
+ cache.delete(id);
237
+ cache.deletePrefix(pieceKey(id, 0).slice(0, -1));
238
+ };
239
+ /** Documents being opened, so that calls arriving together open each one once. */
240
+ const opening = new Map<string, Promise<DocumentSource | undefined>>();
241
+ /** The store, when large documents can be read from it by range rather than loaded whole. */
242
+ const ranged: RangeStore | undefined = typeof store.readTextRange === "function" ? {
243
+ readTextRange: (id, start, end) => reading(() => store.readTextRange!(id, start, end)),
244
+ ...(store.getIndex ? { getIndex: (id: string) => reading(() => store.getIndex!(id)) } : {}),
245
+ ...(store.putIndex ? { putIndex: (id: string, index: Uint8Array) => store.putIndex!(id, index) } : {}),
246
+ } : undefined;
247
+ /** The uploaded file of a document, when the store keeps such files. */
248
+ const loadOriginal = store.getOriginal ? (id: string) => reading(() => store.getOriginal!(id)) : undefined;
249
+ const wholeDocumentBytes = Math.max(0, options.wholeDocumentBytes ?? DEFAULT_WHOLE_DOCUMENT_BYTES);
250
+ /** Documents whose saved index did not match their text: the next opening builds it from the text. */
251
+ const rebuildIndex = new Set<string>();
252
+ const scan: ScanSettings = {
253
+ chunkBytes: Math.max(1, Math.trunc(options.scanChunkBytes ?? 1024 * 1024)),
254
+ limiter: new Limiter(Math.max(1, Math.trunc(options.maxConcurrentScans ?? 4))),
255
+ onBroken: (id) => {
256
+ rebuildIndex.add(id);
257
+ forget(id);
258
+ },
259
+ pieces: {
260
+ get: (key, version) => cache.get(key, version) as CachedPiece | undefined,
261
+ // A piece belongs to its document: it is not one of the `cacheSize` documents, and leaves with it.
262
+ set: (key, version, piece) => cache.set(key, version, piece, key.slice(0, key.indexOf("#"))),
263
+ // A quarter of the cache: a few documents can be kept, and no one pushes out all the rest.
264
+ maxDocumentBytes: cacheBytes / 4,
265
+ },
266
+ };
164
267
  const keepOriginals = new Set<DocumentFormat>(options.keepOriginals ?? []);
165
268
  const scannedPdfPages = Math.max(0, Math.trunc(options.scannedPdfPages ?? 30));
166
269
  /** Whether the uploaded file of a document of this format is kept. */
167
270
  const keeps = (format: DocumentFormat) => keepOriginals.has(format) && typeof options.store.putOriginal === "function";
168
271
 
169
- async function load(id: string): Promise<SearchableDocument | undefined> {
170
- const cached = cache.get(id);
171
- if (cached) {
172
- if (Date.parse(cached.meta.expiresAt) > now().getTime()) {
173
- // Refresh its place as most recently used.
174
- cache.delete(id);
175
- cache.set(id, cached);
176
- return cached;
177
- }
178
- cache.delete(id);
272
+ /**
273
+ * The document as the store describes it now: undefined when it was never there, has been
274
+ * deleted (by this server or another one sharing the store), or has expired.
275
+ */
276
+ async function currentMeta(id: string): Promise<DocumentMeta | undefined> {
277
+ if (!isDocumentId(id)) return undefined;
278
+ const meta = await reading(() => store.getMeta(id));
279
+ if (!meta || Date.parse(meta.expiresAt) <= now().getTime()) {
280
+ forget(id);
281
+ return undefined;
179
282
  }
180
- const stored = await options.store.get(id);
181
- if (!stored) return undefined;
182
- const document = new SearchableDocument(stored);
183
- cache.set(id, document);
184
- while (cache.size > cacheSize) cache.delete(cache.keys().next().value!);
283
+ return meta;
284
+ }
285
+
286
+ /**
287
+ * A document ready to read and search. The store is asked first, every time: a kept copy is
288
+ * used only while the store still has the same document. `known` is metadata just read from
289
+ * the store, to save asking twice.
290
+ */
291
+ async function load(id: string, known?: DocumentMeta): Promise<DocumentSource | undefined> {
292
+ const meta = known ?? await currentMeta(id);
293
+ if (!meta) return undefined;
294
+ const version = documentVersion(meta);
295
+ const cached = cache.get(id, version) as DocumentSource | undefined;
296
+ if (cached && !cached.broken) return cached;
297
+ const key = `${id}|${version}`;
298
+ let pending = opening.get(key);
299
+ if (!pending) {
300
+ pending = open(id, meta).finally(() => opening.delete(key));
301
+ opening.set(key, pending);
302
+ }
303
+ const document = await pending;
304
+ if (document) cache.set(id, version, document);
185
305
  return document;
186
306
  }
187
307
 
308
+ /** Reads a document from the store: its index, to read it by range, or all of it. */
309
+ async function open(id: string, meta: DocumentMeta): Promise<DocumentSource | undefined> {
310
+ if (ranged && meta.textBytes > wholeDocumentBytes) {
311
+ const rebuild = rebuildIndex.delete(id);
312
+ return openRangedDocument(ranged, meta, scan, { ignoreSavedIndex: rebuild });
313
+ }
314
+ const stored = await reading(() => store.get(id));
315
+ return stored ? new SearchableDocument(stored) : undefined;
316
+ }
317
+
318
+ /**
319
+ * What a document contributes to the prompt: its text, or its card. Undefined when it is gone
320
+ * by now. A copy found to disagree with the store is opened again once.
321
+ */
322
+ async function block(id: string, meta: DocumentMeta, whole: boolean, viewable: boolean, readableWhole: boolean): Promise<string | undefined> {
323
+ for (let attempt = 0; attempt < 2; attempt++) {
324
+ const document = await load(id, attempt === 0 ? meta : undefined);
325
+ if (!document) return undefined;
326
+ try {
327
+ return whole
328
+ ? renderInline(document.meta, await document.readText())
329
+ : renderCard(document.meta, numberLines(await document.readLines(1, CARD_LINES), 1), viewable, readableWhole);
330
+ } catch (error) {
331
+ if (!document.broken) {
332
+ // Deleted between the look-up and the read: the same as missing.
333
+ if (!await currentMeta(id)) return undefined;
334
+ throw error;
335
+ }
336
+ }
337
+ }
338
+ return undefined;
339
+ }
340
+
188
341
  async function metaFor(id: string, access: AccessOptions | undefined): Promise<DocumentMeta | undefined> {
189
- if (!isDocumentId(id)) return undefined;
190
- const meta = await options.store.getMeta(id);
342
+ const meta = await currentMeta(id);
191
343
  return meta && allowed(meta, access) ? meta : undefined;
192
344
  }
193
345
 
@@ -216,6 +368,8 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
216
368
  if (text.endsWith("\n")) lines.pop();
217
369
  if (format === "text" && looksLikeLog(lines)) format = "log";
218
370
  const created = now();
371
+ const expires = created.getTime() + ttlMs;
372
+ const sizes = textSizes(text);
219
373
  const keepOriginal = keeps(format);
220
374
  const meta: DocumentMeta = {
221
375
  id: `doc_${randomUUID().replaceAll("-", "")}`,
@@ -224,7 +378,8 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
224
378
  mimeType,
225
379
  format,
226
380
  bytes: input.bytes.byteLength,
227
- textBytes: utf8Bytes(text),
381
+ textBytes: sizes.utf8,
382
+ jsonBytes: sizes.json,
228
383
  characters: text.length,
229
384
  lines: lines.length,
230
385
  estimatedTokens: estimateTokens(text),
@@ -234,15 +389,25 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
234
389
  outline: buildOutline(lines, format),
235
390
  ...(format === "log" ? { logProfile: buildLogProfile(lines) } : {}),
236
391
  createdAt: created.toISOString(),
237
- expiresAt: new Date(created.getTime() + ttlMs).toISOString(),
392
+ // Never, for a time to live without end (or one that runs past what a date can hold).
393
+ expiresAt: expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString(),
238
394
  };
395
+ // The line index, so that the text can be read by range: a few bytes a line, built from the
396
+ // UTF-8 bytes the store writes. Kept by any store that can keep it, even one this library
397
+ // then loads whole, so that switching to reading by range finds it ready.
398
+ const index = typeof store.putIndex === "function" ? buildTextIndex(text) : undefined;
399
+ const savedIndex = index && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters
400
+ ? serializeTextIndex(index)
401
+ : undefined;
239
402
  try {
240
- // The file first, the document last: a document is there once its metadata is.
241
- if (keepOriginal) await options.store.putOriginal!(meta.id, input.bytes);
242
- await options.store.put({ meta, text });
403
+ // The files first, the document last: a document is there once its metadata is.
404
+ if (keepOriginal) await store.putOriginal!(meta.id, input.bytes);
405
+ if (savedIndex) await store.putIndex!(meta.id, savedIndex);
406
+ await store.put({ meta, text });
243
407
  } catch (error) {
244
- // Do not leave a file of up to the upload limit behind for a document that does not exist.
245
- if (keepOriginal) await options.store.delete(meta.id).catch(() => undefined);
408
+ // Do not leave a file of up to the upload limit, or a part of one, behind for a document
409
+ // that does not exist.
410
+ await store.delete(meta.id).catch(() => undefined);
246
411
  throw error;
247
412
  }
248
413
  return meta;
@@ -252,12 +417,12 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
252
417
 
253
418
  async getOriginal(id, access) {
254
419
  const meta = await metaFor(id, access);
255
- return meta?.originalKept ? options.store.getOriginal?.(id) : undefined;
420
+ return meta?.originalKept ? loadOriginal?.(id) : undefined;
256
421
  },
257
422
 
258
423
  async delete(id, access) {
259
424
  if (!await metaFor(id, access)) return false;
260
- cache.delete(id);
425
+ forget(id);
261
426
  return options.store.delete(id);
262
427
  },
263
428
 
@@ -267,32 +432,44 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
267
432
 
268
433
  async prepare(ids, base, access) {
269
434
  const unique = [...new Set(ids)];
270
- const documents: SearchableDocument[] = [];
435
+ let documents: DocumentMeta[] = [];
271
436
  const missing: string[] = [];
272
437
  for (const id of unique) {
273
- const document = isDocumentId(id) ? await load(id) : undefined;
274
- // A document owned by someone else is reported as missing, not as forbidden.
275
- if (document && allowed(document.meta, access)) documents.push(document);
438
+ // A document owned by someone else is reported as missing, not as forbidden, and is not
439
+ // read at all.
440
+ const meta = await metaFor(id, access);
441
+ if (meta) documents.push(meta);
276
442
  else missing.push(id);
277
443
  }
278
- const plan = planDocuments(documents.map((document) => document.meta), budget, base);
279
- const inline = new Set(plan.inline.map((meta) => meta.id));
280
- // Pages can be shown for a PDF whose file is kept, whether its text is in the prompt or searched.
281
- const viewable = access?.viewPages && options.store.getOriginal
282
- ? documents.map((document) => document.meta).filter((meta) => meta.format === "pdf" && meta.originalKept)
283
- : [];
284
- const shown = new Set(viewable.map((meta) => meta.id));
285
- const blocks = new Map<string, string>();
286
- for (const document of documents) {
287
- const { id } = document.meta;
288
- blocks.set(id, inline.has(id) ? renderInline(document) : renderCard(document, shown.has(id)));
444
+ // Planning needs only the metadata. The text is read for the documents sent whole, and the
445
+ // first lines for the others. One that is gone by then is missing, and the plan is made again.
446
+ for (;;) {
447
+ const plan = planDocuments(documents, budget, base);
448
+ const inline = new Set(plan.inline.map((meta) => meta.id));
449
+ // Pages can be shown for a PDF whose file is kept, whether its text is in the prompt or searched.
450
+ const viewable = access?.viewPages && store.getOriginal
451
+ ? documents.filter((meta) => meta.format === "pdf" && meta.originalKept)
452
+ : [];
453
+ const shown = new Set(viewable.map((meta) => meta.id));
454
+ const blocks = new Map<string, string>();
455
+ const gone: string[] = [];
456
+ for (const meta of documents) {
457
+ const text = await block(meta.id, meta, inline.has(meta.id), shown.has(meta.id), canBeReadWhole(meta, budget));
458
+ if (text === undefined) gone.push(meta.id);
459
+ else blocks.set(meta.id, text);
460
+ }
461
+ if (gone.length === 0) {
462
+ // A whole-document read is named only when one of the files is small enough for it.
463
+ const wholeReads = plan.searchable.some((meta) => canBeReadWhole(meta, budget));
464
+ return { plan, blocks, instruction: documentToolsInstruction(plan.searchable, viewable, wholeReads), missing, viewable };
465
+ }
466
+ missing.push(...gone);
467
+ documents = documents.filter((meta) => !gone.includes(meta.id));
289
468
  }
290
- return { plan, blocks, instruction: documentToolsInstruction(plan.searchable, viewable), missing, viewable };
291
469
  },
292
470
 
293
471
  tools(documents, toolOptions = {}) {
294
472
  const { viewPages, ...rest } = toolOptions;
295
- const loadOriginal = options.store.getOriginal?.bind(options.store);
296
473
  const viewable = (loadOriginal ? (viewPages === true ? documents : viewPages || []) : [])
297
474
  .filter((meta) => meta.format === "pdf" && meta.originalKept);
298
475
  return createDocumentTools({
@@ -301,6 +478,8 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
301
478
  names: Object.fromEntries([...documents, ...viewable].map((meta) => [meta.id, meta.name])),
302
479
  budget,
303
480
  ...(loadOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal } : {}),
481
+ // `analyze_whole_document` is declared only when it can read at least one of the documents.
482
+ wholeReads: documents.some((meta) => canBeReadWhole(meta, budget)),
304
483
  ...rest,
305
484
  });
306
485
  },
package/src/limiter.ts ADDED
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Lets at most `max` tasks hold a slot at once; the others wait their turn, in order. Used for
3
+ * scans of whole documents: on one thread more of them at once do not finish sooner, they only
4
+ * hold more memory.
5
+ */
6
+ export class Limiter {
7
+ private active = 0;
8
+ private readonly waiting: Array<() => void> = [];
9
+
10
+ constructor(private readonly max: number) {}
11
+
12
+ /** Waits for a slot. Call the returned function once to give it back. */
13
+ async acquire(signal?: AbortSignal): Promise<() => void> {
14
+ signal?.throwIfAborted();
15
+ if (this.active < this.max) {
16
+ this.active++;
17
+ return this.releaser();
18
+ }
19
+ await new Promise<void>((resolve, reject) => {
20
+ const onAbort = () => {
21
+ const at = this.waiting.indexOf(start);
22
+ if (at !== -1) this.waiting.splice(at, 1);
23
+ reject(signal!.reason);
24
+ };
25
+ const start = () => {
26
+ signal?.removeEventListener("abort", onAbort);
27
+ resolve();
28
+ };
29
+ this.waiting.push(start);
30
+ signal?.addEventListener("abort", onAbort, { once: true });
31
+ });
32
+ // The slot was handed over by the task that gave it back: `active` already counts it.
33
+ return this.releaser();
34
+ }
35
+
36
+ /** Tasks holding a slot, and tasks waiting for one. */
37
+ get load(): { active: number; waiting: number } {
38
+ return { active: this.active, waiting: this.waiting.length };
39
+ }
40
+
41
+ private releaser(): () => void {
42
+ let released = false;
43
+ return () => {
44
+ if (released) return;
45
+ released = true;
46
+ const next = this.waiting.shift();
47
+ if (next) next();
48
+ else this.active--;
49
+ };
50
+ }
51
+ }