llm-large-files 0.1.0 → 0.3.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 (91) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +32 -6
  3. package/dist/analyze.d.ts.map +1 -1
  4. package/dist/analyze.js +5 -1
  5. package/dist/analyze.js.map +1 -1
  6. package/dist/extract.d.ts +30 -7
  7. package/dist/extract.d.ts.map +1 -1
  8. package/dist/extract.js +94 -23
  9. package/dist/extract.js.map +1 -1
  10. package/dist/gemini/chat.d.ts +38 -2
  11. package/dist/gemini/chat.d.ts.map +1 -1
  12. package/dist/gemini/chat.js +83 -32
  13. package/dist/gemini/chat.js.map +1 -1
  14. package/dist/gemini/generate.d.ts +34 -4
  15. package/dist/gemini/generate.d.ts.map +1 -1
  16. package/dist/gemini/generate.js +51 -8
  17. package/dist/gemini/generate.js.map +1 -1
  18. package/dist/gemini/index.d.ts +3 -3
  19. package/dist/gemini/index.d.ts.map +1 -1
  20. package/dist/gemini/index.js +2 -2
  21. package/dist/gemini/index.js.map +1 -1
  22. package/dist/index.d.ts +4 -3
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +2 -2
  25. package/dist/index.js.map +1 -1
  26. package/dist/library.d.ts +37 -1
  27. package/dist/library.d.ts.map +1 -1
  28. package/dist/library.js +59 -7
  29. package/dist/library.js.map +1 -1
  30. package/dist/map-reduce.d.ts +7 -0
  31. package/dist/map-reduce.d.ts.map +1 -1
  32. package/dist/map-reduce.js +58 -16
  33. package/dist/map-reduce.js.map +1 -1
  34. package/dist/pdf-layout.d.ts +39 -0
  35. package/dist/pdf-layout.d.ts.map +1 -0
  36. package/dist/pdf-layout.js +820 -0
  37. package/dist/pdf-layout.js.map +1 -0
  38. package/dist/pdf-pages.d.ts +45 -0
  39. package/dist/pdf-pages.d.ts.map +1 -0
  40. package/dist/pdf-pages.js +336 -0
  41. package/dist/pdf-pages.js.map +1 -0
  42. package/dist/pdf-pictures.d.ts +20 -0
  43. package/dist/pdf-pictures.d.ts.map +1 -0
  44. package/dist/pdf-pictures.js +336 -0
  45. package/dist/pdf-pictures.js.map +1 -0
  46. package/dist/plan.d.ts +13 -3
  47. package/dist/plan.d.ts.map +1 -1
  48. package/dist/plan.js +27 -18
  49. package/dist/plan.js.map +1 -1
  50. package/dist/search.d.ts +17 -4
  51. package/dist/search.d.ts.map +1 -1
  52. package/dist/search.js +90 -24
  53. package/dist/search.js.map +1 -1
  54. package/dist/stores.d.ts +7 -1
  55. package/dist/stores.d.ts.map +1 -1
  56. package/dist/stores.js +37 -5
  57. package/dist/stores.js.map +1 -1
  58. package/dist/text.d.ts +18 -4
  59. package/dist/text.d.ts.map +1 -1
  60. package/dist/text.js +155 -15
  61. package/dist/text.js.map +1 -1
  62. package/dist/tools.d.ts +11 -0
  63. package/dist/tools.d.ts.map +1 -1
  64. package/dist/tools.js +156 -16
  65. package/dist/tools.js.map +1 -1
  66. package/dist/types.d.ts +63 -3
  67. package/dist/types.d.ts.map +1 -1
  68. package/docs/api.md +56 -11
  69. package/docs/configuration.md +298 -6
  70. package/docs/getting-started.md +41 -7
  71. package/docs/how-it-works.md +77 -11
  72. package/docs/security.md +54 -6
  73. package/package.json +96 -91
  74. package/src/analyze.ts +3 -1
  75. package/src/extract.ts +105 -24
  76. package/src/gemini/chat.ts +116 -34
  77. package/src/gemini/generate.ts +66 -10
  78. package/src/gemini/index.ts +3 -3
  79. package/src/index.ts +4 -3
  80. package/src/library.ts +308 -226
  81. package/src/map-reduce.ts +69 -16
  82. package/src/node/handlers.ts +122 -122
  83. package/src/pdf-layout.ts +807 -0
  84. package/src/pdf-pages.ts +315 -0
  85. package/src/pdf-pictures.ts +324 -0
  86. package/src/plan.ts +120 -98
  87. package/src/search.ts +85 -25
  88. package/src/stores.ts +165 -132
  89. package/src/text.ts +131 -14
  90. package/src/tools.ts +408 -264
  91. package/src/types.ts +228 -168
package/src/library.ts CHANGED
@@ -1,226 +1,308 @@
1
- import { randomUUID } from "node:crypto";
2
- import { buildLogProfile, buildOutline, looksLikeLog } from "./analyze.js";
3
- import { detectFormat, extractText } from "./extract.js";
4
- import { documentToolsInstruction, formatBytes, planDocuments, renderCard, renderInline } from "./plan.js";
5
- import { SearchableDocument } from "./search.js";
6
- import { DOCUMENT_ID_PATTERN } from "./stores.js";
7
- import { estimateTokens, normalizeText, utf8Bytes, wrapLongLines } from "./text.js";
8
- import { createDocumentTools } from "./tools.js";
9
- import type {
10
- Budget,
11
- DocumentFormat,
12
- DocumentMeta,
13
- DocumentStore,
14
- DocumentSummary,
15
- Extractor,
16
- GenerateText,
17
- PreparedContext,
18
- ProgressListener,
19
- ToolSet,
20
- } from "./types.js";
21
-
22
- /** Defaults sized for a 1M-token model behind a 10 MB request limit. */
23
- export const DEFAULT_BUDGET: Budget = {
24
- contextTokens: 1_000_000,
25
- maxRequestBytes: 10_000_000,
26
- inlineTokens: 200_000,
27
- reservedTokens: 64_000,
28
- mapChunkTokens: 100_000,
29
- maxMapChunks: 30,
30
- toolResultCharacters: 24_000,
31
- };
32
-
33
- export type LargeFilesOptions = {
34
- /** Where extracted text is kept: `new FileDocumentStore(dir)`, `new MemoryDocumentStore()`, or your own. */
35
- store: DocumentStore;
36
- /** Your model's limits. Anything left out uses DEFAULT_BUDGET. */
37
- budget?: Partial<Budget>;
38
- /** How long uploaded documents are kept. Defaults to 72 hours. */
39
- ttlMs?: number;
40
- /** Largest accepted upload. Defaults to 100 MB. */
41
- maxUploadBytes?: number;
42
- /** Override or add text extractors per format. */
43
- extractors?: Partial<Record<DocumentFormat, Extractor>>;
44
- /** How many parsed documents to keep in memory for repeated tool calls. Defaults to 6. */
45
- cacheSize?: number;
46
- /** Clock override, for tests. */
47
- now?: () => Date;
48
- };
49
-
50
- export type IngestInput = {
51
- name: string;
52
- mimeType?: string;
53
- bytes: Uint8Array;
54
- /** The user (or tenant) the document belongs to. Later calls must pass the same owner. */
55
- owner?: string;
56
- };
57
-
58
- /** Access options. When a document has an owner, only that owner can use it. */
59
- export type AccessOptions = { owner?: string };
60
-
61
- export type ToolOptions = {
62
- /** Enables `analyze_whole_document`, which reads the entire file in parts. */
63
- generate?: GenerateText;
64
- /** Progress of whole-document reads, for status messages. */
65
- onProgress?: ProgressListener;
66
- signal?: AbortSignal;
67
- };
68
-
69
- export interface LargeFiles {
70
- /** The effective budget (defaults merged with your overrides). */
71
- readonly budget: Budget;
72
- readonly maxUploadBytes: number;
73
- /** Extracts, normalizes, profiles, and stores a file. Throws a user-readable Error on bad input. */
74
- ingest(input: IngestInput): Promise<DocumentMeta>;
75
- getMeta(id: string, access?: AccessOptions): Promise<DocumentMeta | undefined>;
76
- delete(id: string, access?: AccessOptions): Promise<boolean>;
77
- /** Removes expired documents from the store. Returns how many were removed. */
78
- sweep(): Promise<number>;
79
- /**
80
- * Plans one model request: which documents go in whole and which become searchable cards.
81
- * `base` is the size of everything else in the request (messages, system prompt, other files).
82
- */
83
- prepare(ids: string[], base: { tokens: number; bytes: number }, access?: AccessOptions): Promise<PreparedContext>;
84
- /** Tools scoped to these documents. Pass `generate` to enable whole-document analysis. */
85
- tools(documents: DocumentMeta[], options?: ToolOptions): ToolSet;
86
- }
87
-
88
- export function isDocumentId(value: unknown): value is string {
89
- return typeof value === "string" && DOCUMENT_ID_PATTERN.test(value);
90
- }
91
-
92
- /** The fields of a document that are safe to return to a browser. */
93
- export function toDocumentSummary(meta: DocumentMeta): DocumentSummary {
94
- return {
95
- id: meta.id,
96
- name: meta.name,
97
- mimeType: meta.mimeType,
98
- format: meta.format,
99
- bytes: meta.bytes,
100
- lines: meta.lines,
101
- estimatedTokens: meta.estimatedTokens,
102
- ...(meta.pages ? { pages: meta.pages } : {}),
103
- expiresAt: meta.expiresAt,
104
- };
105
- }
106
-
107
- function allowed(meta: DocumentMeta, access: AccessOptions | undefined): boolean {
108
- return meta.owner === undefined || meta.owner === access?.owner;
109
- }
110
-
111
- export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
112
- const budget: Budget = { ...DEFAULT_BUDGET, ...options.budget };
113
- const ttlMs = options.ttlMs ?? 72 * 60 * 60 * 1000;
114
- const maxUploadBytes = options.maxUploadBytes ?? 100 * 1024 * 1024;
115
- const now = options.now ?? (() => new Date());
116
- const cacheSize = Math.max(1, options.cacheSize ?? 6);
117
- const cache = new Map<string, SearchableDocument>();
118
-
119
- async function load(id: string): Promise<SearchableDocument | undefined> {
120
- const cached = cache.get(id);
121
- if (cached) {
122
- if (Date.parse(cached.meta.expiresAt) > now().getTime()) {
123
- // Refresh its place as most recently used.
124
- cache.delete(id);
125
- cache.set(id, cached);
126
- return cached;
127
- }
128
- cache.delete(id);
129
- }
130
- const stored = await options.store.get(id);
131
- if (!stored) return undefined;
132
- const document = new SearchableDocument(stored);
133
- cache.set(id, document);
134
- while (cache.size > cacheSize) cache.delete(cache.keys().next().value!);
135
- return document;
136
- }
137
-
138
- async function metaFor(id: string, access: AccessOptions | undefined): Promise<DocumentMeta | undefined> {
139
- if (!isDocumentId(id)) return undefined;
140
- const meta = await options.store.getMeta(id);
141
- return meta && allowed(meta, access) ? meta : undefined;
142
- }
143
-
144
- return {
145
- budget,
146
- maxUploadBytes,
147
-
148
- async ingest(input) {
149
- const name = input.name.trim().split(/[\\/]/).at(-1)?.slice(0, 255) || "file";
150
- const mimeType = input.mimeType?.trim() || "application/octet-stream";
151
- if (input.bytes.byteLength === 0) throw new Error(`${name} is empty.`);
152
- if (input.bytes.byteLength > maxUploadBytes) {
153
- throw new Error(`${name} is larger than the ${formatBytes(maxUploadBytes)} upload limit.`);
154
- }
155
- let format = detectFormat(name, mimeType);
156
- const extracted = await extractText(input.bytes, { name, mimeType, format }, options.extractors);
157
- const { text, wrapped } = wrapLongLines(normalizeText(extracted.text));
158
- if (!text.trim()) throw new Error(`${name} did not contain any text.`);
159
- const lines = text.split("\n");
160
- if (text.endsWith("\n")) lines.pop();
161
- if (format === "text" && looksLikeLog(lines)) format = "log";
162
- const created = now();
163
- const meta: DocumentMeta = {
164
- id: `doc_${randomUUID().replaceAll("-", "")}`,
165
- ...(input.owner !== undefined ? { owner: input.owner } : {}),
166
- name,
167
- mimeType,
168
- format,
169
- bytes: input.bytes.byteLength,
170
- textBytes: utf8Bytes(text),
171
- characters: text.length,
172
- lines: lines.length,
173
- estimatedTokens: estimateTokens(text),
174
- wrappedLines: wrapped,
175
- ...(extracted.pages ? { pages: extracted.pages } : {}),
176
- outline: buildOutline(lines, format),
177
- ...(format === "log" ? { logProfile: buildLogProfile(lines) } : {}),
178
- createdAt: created.toISOString(),
179
- expiresAt: new Date(created.getTime() + ttlMs).toISOString(),
180
- };
181
- await options.store.put({ meta, text });
182
- return meta;
183
- },
184
-
185
- getMeta: metaFor,
186
-
187
- async delete(id, access) {
188
- if (!await metaFor(id, access)) return false;
189
- cache.delete(id);
190
- return options.store.delete(id);
191
- },
192
-
193
- async sweep() {
194
- return options.store.sweep?.(now()) ?? 0;
195
- },
196
-
197
- async prepare(ids, base, access) {
198
- const unique = [...new Set(ids)];
199
- const documents: SearchableDocument[] = [];
200
- const missing: string[] = [];
201
- for (const id of unique) {
202
- const document = isDocumentId(id) ? await load(id) : undefined;
203
- // A document owned by someone else is reported as missing, not as forbidden.
204
- if (document && allowed(document.meta, access)) documents.push(document);
205
- else missing.push(id);
206
- }
207
- const plan = planDocuments(documents.map((document) => document.meta), budget, base);
208
- const inline = new Set(plan.inline.map((meta) => meta.id));
209
- const blocks = new Map<string, string>();
210
- for (const document of documents) {
211
- blocks.set(document.meta.id, inline.has(document.meta.id) ? renderInline(document) : renderCard(document));
212
- }
213
- return { plan, blocks, instruction: documentToolsInstruction(plan.searchable), missing };
214
- },
215
-
216
- tools(documents, toolOptions = {}) {
217
- return createDocumentTools({
218
- load,
219
- documentIds: documents.map((meta) => meta.id),
220
- names: Object.fromEntries(documents.map((meta) => [meta.id, meta.name])),
221
- budget,
222
- ...toolOptions,
223
- });
224
- },
225
- };
226
- }
1
+ import { randomUUID } from "node:crypto";
2
+ import { buildLogProfile, buildOutline, looksLikeLog } from "./analyze.js";
3
+ import { detectFormat, extractText } from "./extract.js";
4
+ import { documentToolsInstruction, formatBytes, planDocuments, renderCard, renderInline } from "./plan.js";
5
+ import { SearchableDocument } from "./search.js";
6
+ import { DOCUMENT_ID_PATTERN } from "./stores.js";
7
+ import { estimateTokens, normalizeText, utf8Bytes, wrapLongLines } from "./text.js";
8
+ import { createDocumentTools } from "./tools.js";
9
+ import type {
10
+ Budget,
11
+ DocumentFormat,
12
+ DocumentMeta,
13
+ DocumentStore,
14
+ DocumentSummary,
15
+ Extractor,
16
+ GenerateText,
17
+ PreparedContext,
18
+ ProgressListener,
19
+ ToolSet,
20
+ } from "./types.js";
21
+
22
+ /** Defaults sized for a 1M-token model behind a 10 MB request limit. */
23
+ export const DEFAULT_BUDGET: Budget = {
24
+ contextTokens: 1_000_000,
25
+ maxRequestBytes: 10_000_000,
26
+ inlineTokens: 200_000,
27
+ reservedTokens: 64_000,
28
+ mapChunkTokens: 100_000,
29
+ maxMapChunks: 30,
30
+ toolResultCharacters: 24_000,
31
+ };
32
+
33
+ export type LargeFilesOptions = {
34
+ /** Where extracted text is kept: `new FileDocumentStore(dir)`, `new MemoryDocumentStore()`, or your own. */
35
+ store: DocumentStore;
36
+ /** Your model's limits. Anything left out uses DEFAULT_BUDGET. */
37
+ budget?: Partial<Budget>;
38
+ /** How long uploaded documents are kept. Defaults to 72 hours. */
39
+ ttlMs?: number;
40
+ /** Largest accepted upload. Defaults to 100 MB. */
41
+ maxUploadBytes?: number;
42
+ /** Override or add text extractors per format. */
43
+ extractors?: Partial<Record<DocumentFormat, Extractor>>;
44
+ /**
45
+ * Formats whose uploaded file is kept in the store next to its text, for example `["pdf"]`.
46
+ * Empty by default: a kept file takes disk space, up to the upload limit, until the document
47
+ * expires. A store without `putOriginal` keeps none.
48
+ */
49
+ keepOriginals?: DocumentFormat[];
50
+ /**
51
+ * A PDF without any text (a scan) has nothing to search, and was always refused. When its
52
+ * original is kept, its pages can be shown to the model instead, so one of up to this many pages
53
+ * is accepted. Defaults to 30. 0 refuses every PDF without text, as before.
54
+ */
55
+ scannedPdfPages?: number;
56
+ /** How many parsed documents to keep in memory for repeated tool calls. Defaults to 6. */
57
+ cacheSize?: number;
58
+ /** Clock override, for tests. */
59
+ now?: () => Date;
60
+ };
61
+
62
+ export type IngestInput = {
63
+ name: string;
64
+ mimeType?: string;
65
+ bytes: Uint8Array;
66
+ /** The user (or tenant) the document belongs to. Later calls must pass the same owner. */
67
+ owner?: string;
68
+ };
69
+
70
+ /** Access options. When a document has an owner, only that owner can use it. */
71
+ export type AccessOptions = { owner?: string };
72
+
73
+ export type PrepareOptions = AccessOptions & {
74
+ /**
75
+ * Say that your tool loop can pass files to the model (see `ToolOptions.viewPages`). The result
76
+ * then lists the PDFs whose pages can be shown in `viewable`, and the instruction and the cards
77
+ * tell the model about `view_pages`. Without it, the result is that of 0.2.0.
78
+ */
79
+ viewPages?: boolean;
80
+ };
81
+
82
+ export type ToolOptions = {
83
+ /** Enables `analyze_whole_document`, which reads the entire file in parts. */
84
+ generate?: GenerateText;
85
+ /** Progress of whole-document reads, for status messages. */
86
+ onProgress?: ProgressListener;
87
+ signal?: AbortSignal;
88
+ /**
89
+ * Offers `view_pages`, which hands the model real pages of a PDF whose original file is kept
90
+ * (see `keepOriginals`). The pages come back as a file, so turn this on only when your loop
91
+ * runs tools with `executeWithFiles` and sends the files to the model. `true` offers it for the
92
+ * documents passed to `tools`; a list offers it for exactly those documents, which may include
93
+ * PDFs that are not searched because their text is already in the prompt.
94
+ */
95
+ viewPages?: boolean | DocumentMeta[];
96
+ };
97
+
98
+ export interface LargeFiles {
99
+ /** The effective budget (defaults merged with your overrides). */
100
+ readonly budget: Budget;
101
+ readonly maxUploadBytes: number;
102
+ /** Extracts, normalizes, profiles, and stores a file. Throws a user-readable Error on bad input. */
103
+ ingest(input: IngestInput): Promise<DocumentMeta>;
104
+ getMeta(id: string, access?: AccessOptions): Promise<DocumentMeta | undefined>;
105
+ /** The uploaded file itself, when it was kept (see `keepOriginals`). Treat the bytes as read-only. */
106
+ getOriginal(id: string, access?: AccessOptions): Promise<Uint8Array | undefined>;
107
+ delete(id: string, access?: AccessOptions): Promise<boolean>;
108
+ /** Removes expired documents from the store. Returns how many were removed. */
109
+ sweep(): Promise<number>;
110
+ /**
111
+ * Plans one model request: which documents go in whole and which become searchable cards.
112
+ * `base` is the size of everything else in the request (messages, system prompt, other files).
113
+ */
114
+ prepare(ids: string[], base: { tokens: number; bytes: number }, options?: PrepareOptions): Promise<PreparedContext>;
115
+ /** Tools scoped to these documents. Pass `generate` to enable whole-document analysis. */
116
+ tools(documents: DocumentMeta[], options?: ToolOptions): ToolSet;
117
+ }
118
+
119
+ export function isDocumentId(value: unknown): value is string {
120
+ return typeof value === "string" && DOCUMENT_ID_PATTERN.test(value);
121
+ }
122
+
123
+ /** The fields of a document that are safe to return to a browser. */
124
+ export function toDocumentSummary(meta: DocumentMeta): DocumentSummary {
125
+ return {
126
+ id: meta.id,
127
+ name: meta.name,
128
+ mimeType: meta.mimeType,
129
+ format: meta.format,
130
+ bytes: meta.bytes,
131
+ lines: meta.lines,
132
+ estimatedTokens: meta.estimatedTokens,
133
+ ...(meta.pages ? { pages: meta.pages } : {}),
134
+ expiresAt: meta.expiresAt,
135
+ };
136
+ }
137
+
138
+ /**
139
+ * A file name as one printable line: the last path segment, without control characters, line
140
+ * breaks, or text-direction overrides. Names are shown to the model and in UIs, so a name must
141
+ * not be able to start a new line of the prompt or disguise its extension.
142
+ */
143
+ export function cleanFileName(raw: string): string {
144
+ const base = raw.split(/[\\/]/).at(-1) ?? "";
145
+ return base
146
+ // Control characters, line and paragraph separators, and text-direction controls.
147
+ .replace(/[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]+/gu, " ")
148
+ .replace(/\s+/g, " ")
149
+ .trim()
150
+ .slice(0, 255) || "file";
151
+ }
152
+
153
+ function allowed(meta: DocumentMeta, access: AccessOptions | undefined): boolean {
154
+ return meta.owner === undefined || meta.owner === access?.owner;
155
+ }
156
+
157
+ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
158
+ const budget: Budget = { ...DEFAULT_BUDGET, ...options.budget };
159
+ const ttlMs = options.ttlMs ?? 72 * 60 * 60 * 1000;
160
+ const maxUploadBytes = options.maxUploadBytes ?? 100 * 1024 * 1024;
161
+ const now = options.now ?? (() => new Date());
162
+ const cacheSize = Math.max(1, options.cacheSize ?? 6);
163
+ const cache = new Map<string, SearchableDocument>();
164
+ const keepOriginals = new Set<DocumentFormat>(options.keepOriginals ?? []);
165
+ const scannedPdfPages = Math.max(0, Math.trunc(options.scannedPdfPages ?? 30));
166
+ /** Whether the uploaded file of a document of this format is kept. */
167
+ const keeps = (format: DocumentFormat) => keepOriginals.has(format) && typeof options.store.putOriginal === "function";
168
+
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);
179
+ }
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!);
185
+ return document;
186
+ }
187
+
188
+ 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);
191
+ return meta && allowed(meta, access) ? meta : undefined;
192
+ }
193
+
194
+ return {
195
+ budget,
196
+ maxUploadBytes,
197
+
198
+ async ingest(input) {
199
+ const name = cleanFileName(input.name);
200
+ const mimeType = input.mimeType?.trim() || "application/octet-stream";
201
+ if (input.bytes.byteLength === 0) throw new Error(`${name} is empty.`);
202
+ if (input.bytes.byteLength > maxUploadBytes) {
203
+ throw new Error(`${name} is larger than the ${formatBytes(maxUploadBytes)} upload limit.`);
204
+ }
205
+ let format = detectFormat(name, mimeType);
206
+ const extracted = await extractText(input.bytes, {
207
+ name,
208
+ mimeType,
209
+ format,
210
+ // A scan is worth storing only if its pages can be shown later: that needs the file itself.
211
+ ...(format === "pdf" && keeps(format) && scannedPdfPages > 0 ? { scannedPages: scannedPdfPages } : {}),
212
+ }, options.extractors);
213
+ const { text, wrapped } = wrapLongLines(normalizeText(extracted.text));
214
+ if (!text.trim()) throw new Error(`${name} did not contain any text.`);
215
+ const lines = text.split("\n");
216
+ if (text.endsWith("\n")) lines.pop();
217
+ if (format === "text" && looksLikeLog(lines)) format = "log";
218
+ const created = now();
219
+ const keepOriginal = keeps(format);
220
+ const meta: DocumentMeta = {
221
+ id: `doc_${randomUUID().replaceAll("-", "")}`,
222
+ ...(input.owner !== undefined ? { owner: input.owner } : {}),
223
+ name,
224
+ mimeType,
225
+ format,
226
+ bytes: input.bytes.byteLength,
227
+ textBytes: utf8Bytes(text),
228
+ characters: text.length,
229
+ lines: lines.length,
230
+ estimatedTokens: estimateTokens(text),
231
+ wrappedLines: wrapped,
232
+ ...(extracted.pages ? { pages: extracted.pages } : {}),
233
+ ...(keepOriginal ? { originalKept: true } : {}),
234
+ outline: buildOutline(lines, format),
235
+ ...(format === "log" ? { logProfile: buildLogProfile(lines) } : {}),
236
+ createdAt: created.toISOString(),
237
+ expiresAt: new Date(created.getTime() + ttlMs).toISOString(),
238
+ };
239
+ 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 });
243
+ } 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);
246
+ throw error;
247
+ }
248
+ return meta;
249
+ },
250
+
251
+ getMeta: metaFor,
252
+
253
+ async getOriginal(id, access) {
254
+ const meta = await metaFor(id, access);
255
+ return meta?.originalKept ? options.store.getOriginal?.(id) : undefined;
256
+ },
257
+
258
+ async delete(id, access) {
259
+ if (!await metaFor(id, access)) return false;
260
+ cache.delete(id);
261
+ return options.store.delete(id);
262
+ },
263
+
264
+ async sweep() {
265
+ return options.store.sweep?.(now()) ?? 0;
266
+ },
267
+
268
+ async prepare(ids, base, access) {
269
+ const unique = [...new Set(ids)];
270
+ const documents: SearchableDocument[] = [];
271
+ const missing: string[] = [];
272
+ 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);
276
+ else missing.push(id);
277
+ }
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)));
289
+ }
290
+ return { plan, blocks, instruction: documentToolsInstruction(plan.searchable, viewable), missing, viewable };
291
+ },
292
+
293
+ tools(documents, toolOptions = {}) {
294
+ const { viewPages, ...rest } = toolOptions;
295
+ const loadOriginal = options.store.getOriginal?.bind(options.store);
296
+ const viewable = (loadOriginal ? (viewPages === true ? documents : viewPages || []) : [])
297
+ .filter((meta) => meta.format === "pdf" && meta.originalKept);
298
+ return createDocumentTools({
299
+ load,
300
+ documentIds: documents.map((meta) => meta.id),
301
+ names: Object.fromEntries([...documents, ...viewable].map((meta) => [meta.id, meta.name])),
302
+ budget,
303
+ ...(loadOriginal && viewable.length > 0 ? { viewableIds: viewable.map((meta) => meta.id), loadOriginal } : {}),
304
+ ...rest,
305
+ });
306
+ },
307
+ };
308
+ }