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
@@ -2,24 +2,33 @@
2
2
 
3
3
  ```
4
4
  upload ─► ingest ─► store extract text · normalize · index lines · outline · log profile
5
- │
5
+ │ (and the uploaded file itself, for formats in keepOriginals)
6
6
  chat turn ─► prepare(ids, size of the rest of the request)
7
7
  ├─ fits ────► full text in the prompt
8
8
  └─ too big ─► summary card in the prompt
9
9
  + tool guide in the system prompt
10
10
  + tools: search · read · overview · analyze-all
11
+ a PDF whose file is kept, in either branch
12
+ ─► + tool: view_pages (the real pages, as a small PDF)
11
13
  ```
12
14
 
13
15
  ## Ingest
14
16
 
15
- 1. **Extract** text by format (built-in extractors or your own).
16
- 2. **Normalize**: strip the BOM, unify line endings, remove control characters, split lines over
17
- 2,000 characters.
17
+ 1. **Extract** text by format (built-in extractors or your own). In a PDF, tables are rebuilt from
18
+ the position of their text and written as `| cell | cell | |` rows, so an empty cell stays an
19
+ empty cell ([details and limits](configuration.md#pdf-tables)). A page that shows a picture or a
20
+ drawing gets a line that says so. Those pages are found from the structure of the file: a small
21
+ interpreter follows each page's drawing instructions and notes where images are painted and
22
+ which shapes are filled, without decoding any image
23
+ ([what counts](configuration.md#the-line-that-marks-a-page)).
24
+ 2. **Normalize**: strip the BOM, unify line endings, remove terminal colour codes and control
25
+ characters, split lines over 2,000 characters.
18
26
  3. **Profile**: count lines, estimate tokens and UTF-8 bytes, and build an outline (headings with
19
27
  line numbers). For logs, also count levels, find the time range, and group ERROR/FATAL/WARN lines
20
28
  by *shape*. Numbers, IDs, IPs, hex, and quoted values are replaced with placeholders, so 800
21
29
  timeouts to different hosts become one entry: `[ERROR ×812, L1203] timeout after <n>ms to <ip>`.
22
- 4. **Store** the text and metadata. Nothing else is indexed up front.
30
+ 4. **Store** the text and metadata, and the uploaded file when its format is in `keepOriginals`.
31
+ Nothing else is indexed up front.
23
32
 
24
33
  ## The card
25
34
 
@@ -35,15 +44,46 @@ FATAL line listed on the card.
35
44
  substring hits. No index to build, it works in any language, and "timeout" also matches
36
45
  "timeouts". A passage containing the exact phrase gets a boost.
37
46
  - `exact` and `regex`: matching lines with optional context. Regexes with nested quantifiers are
38
- refused, and scans stop after 3 seconds.
47
+ refused up front, and every regex scan runs under a 3-second limit that can interrupt a match
48
+ in progress, so a slow pattern returns partial results instead of hanging the process.
39
49
  - **`read_document`**: numbered line ranges, trimmed to the result-size cap, with `next_start_line`
40
50
  for paging.
41
51
  - **`get_document_overview`**: the full outline and profile, the first and last lines, and how many
42
52
  parts a whole-file read would take.
43
53
  - **`analyze_whole_document`**: map-reduce (below).
54
+ - **`view_pages`**: pages of a PDF, cut out of the kept original into a PDF of their own
55
+ (below). It is the only tool that returns a file.
44
56
 
45
57
  Every result is capped (`toolResultCharacters`) and states what was cut, so one tool call can never
46
- overflow the request.
58
+ overflow the request. `view_pages` is capped in pages and in bytes instead.
59
+
60
+ ## Looking at pages
61
+
62
+ Text cannot show a chart. `view_pages(document_id, from_page, to_page)` gives the model the pages
63
+ themselves: up to five a call, as one PDF, which Gemini reads like any PDF.
64
+
65
+ Cutting pages out of a PDF sounds like copying them. Copied the way PDF libraries offer it, a page
66
+ brings along everything it refers to:
67
+
68
+ - **Links.** A contents page links to every section. Each link holds a reference to its target
69
+ page, so the copy took those pages too, with their pictures: the contents page of a 7.5 MB report
70
+ came out at 6.7 MB. Before copying, every page that is not wanted is replaced by an empty one, so
71
+ a reference to it costs a few bytes. The same contents page is then 55 KB.
72
+ - **Shared resources.** FPDF, TCPDF, jsPDF and others write one list of all images of the file and
73
+ give it to every page. A copy of one page carried all of them. The content of each wanted page is
74
+ read to see which images it paints, and the page gets a list of only those. Nothing is dropped
75
+ unless all content that could name an image was read.
76
+ - **Layers.** A file can hide a layer. The settings that say so are copied with the pages, or the
77
+ hidden layer would show.
78
+
79
+ The pages are counted against the request twice. As bytes: base64 makes them a third larger, and
80
+ they stay in the request until the question is answered, so the room for the next look shrinks.
81
+ As tokens: about 530 a page, against half of `reservedTokens`. When either runs out, the tool says
82
+ so and the model answers from what it has
83
+ ([limits and measurements](configuration.md#view_pages)).
84
+
85
+ A PDF whose text fits in the prompt gets `view_pages` too, and only that. Such a file is often a
86
+ slide deck: little text, a picture on every page.
47
87
 
48
88
  ## Map-reduce
49
89
 
@@ -55,17 +95,40 @@ overflow the request.
55
95
  3. If the notes are still too large, merge them in batches (or pairs) for up to 8 rounds.
56
96
  4. Write one answer from the notes, flagging contradictions and parts that couldn't be read.
57
97
 
98
+ Part notes are capped at 4,096 output tokens and the answer at 8,192. When either cap is reached,
99
+ the tool result says the answer is incomplete and points the model to exact search. That matters
100
+ for "list every…" tasks: in a live test with 1,200 matching lines, 492 came back, flagged as
101
+ incomplete. Even without reaching a cap the model can skip items (91 of 120 in the same test), so
102
+ for a complete list or an exact count, `search_document` in exact or regex mode is the reliable
103
+ tool: it reports `total_matching_lines`.
104
+
58
105
  Jobs needing more than `maxMapChunks` parts are refused, with advice to narrow the question first.
59
106
 
60
107
  ## The Gemini loop (`askGemini`)
61
108
 
109
+ - Document text and cards go at the **start of the first user turn** and stay there as the
110
+ conversation grows. Gemini's prompt cache works on a matching prefix, so a follow-up question
111
+ reuses the document instead of paying for it again (96% of input cached in a live test, against
112
+ 0% when the document was appended to the latest turn). `documentPlacement: "last"` restores the
113
+ old layout.
62
114
  - The model's turns are sent back **unchanged**, so Gemini 3 thought signatures stay intact.
63
115
  - Each tool result includes `tool_turns_left`, and the tool guide asks the model to batch
64
116
  independent searches and stop when it has enough. This keeps it from searching one thing per turn.
65
117
  - **Gemini can ignore `functionCallingConfig: { mode: "NONE" }`.** Live testing showed it kept
66
- calling tools on the turn meant to force an answer. So when the turns run out (or the model goes
67
- quiet), the final request **declares no tools at all** and adds a short "answer now" message.
68
- There is always a written answer.
118
+ calling tools on the turn meant to force an answer. So when the turns run out, or the model's
119
+ last turn has no text, the final request **declares no tools at all** and adds a short "answer
120
+ now" message. That request is the last of the `maxToolTurns`; no request is made whose tool
121
+ calls would be thrown away.
122
+ - If even that request has no text, or Gemini blocks the prompt, the result has `answered: false`
123
+ (and `blockReason`), so the caller can show its own message instead of an empty answer.
124
+ - Pages from `view_pages` go **inside the function response** (`functionResponse.parts`, with the
125
+ result naming the file as `{ "$ref": "pages-12-14.pdf" }`). `toolFilePlacement: "beside"` sends
126
+ them in a `user` turn of their own, right after the turn of function responses: Gemini 2.5 does
127
+ not see a file inside a function response. The files do not share a turn with the function
128
+ responses, because Vertex AI refuses a turn in which anything follows one. Both forms work with
129
+ Gemini 3.5 on the Gemini API and on Vertex AI.
130
+ - Tool results, pages included, live inside one call of `askGemini`. They are not sent again with
131
+ the next question.
69
132
 
70
133
  ## Live results
71
134
 
@@ -73,6 +136,9 @@ Jobs needing more than `maxMapChunks` parts are refused, with advice to narrow t
73
136
 
74
137
  | Case | Outcome |
75
138
  |---|---|
76
- | 5 MB, 60,000-line log (about 1.27M tokens, over the 1M limit) | Correct root cause, failover time, and affected services, citing the right lines (checked with grep). About 60 s, 11 tool calls, about 15K prompt tokens per turn. |
139
+ | 5 MB, 60,000-line log (1.27M tokens by the 0.1.0 estimate, which undercounted logs) | Correct root cause, failover time, and affected services, citing the right lines (checked with grep). About 60 s, 11 tool calls, about 15K prompt tokens per turn. |
77
140
  | 467 KB novel | Sent whole. Token estimate 116,840; Gemini billed 116,842. |
78
141
  | Map-reduce on the novel, 40K-token parts | 4 parts, 1 relevant. Correct answer citing L2036. 32 s. |
142
+
143
+ The checks of `view_pages`, on `gemini-3.5-flash-lite`, are in
144
+ [Pictures in PDFs](configuration.md#live-results).
package/docs/security.md CHANGED
@@ -24,7 +24,8 @@ can leak through logs, browser storage, or shared links.
24
24
  ## Tool scoping
25
25
 
26
26
  `files.tools(documents)` accepts only the IDs it was created with. A model (or a prompt injected
27
- into a file) can't reach another conversation's documents by naming their IDs.
27
+ into a file) can't reach another conversation's documents by naming their IDs. `view_pages` has
28
+ its own list, the PDFs passed as `viewPages`, and checks it the same way.
28
29
 
29
30
  ## Prompt injection
30
31
 
@@ -42,16 +43,63 @@ treat the model's output as untrusted.
42
43
  - Only IDs matching `doc_` plus 32 hex characters ever reach the file system, so there's no path
43
44
  traversal.
44
45
 
46
+ ## Original files
47
+
48
+ With `keepOriginals`, the uploaded file itself is stored next to its text (`<id>.bin` in
49
+ `FileDocumentStore`). That is off by default. When you turn it on:
50
+
51
+ - **More is kept than before.** The text of a PDF leaves out its pictures, signatures, stamps and
52
+ hidden layers; the file has them all, and its metadata (author, software, dates). Treat the
53
+ store as you treat the uploads themselves.
54
+ - **It follows the document.** The file has the document's owner and its expiry: it is returned
55
+ only to the owner (`files.getOriginal(id, { owner })`), it is gone for every reader once the
56
+ document has expired, and `delete` and `sweep` remove it from disk. A store of your own must do
57
+ the same in its `delete` and `sweep`.
58
+ - **It takes space.** Up to `maxUploadBytes` (100 MB) per document, for `ttlMs` (72 h). Lower
59
+ either, or sweep more often, if disk is short.
60
+ - **Pages go to the model.** `view_pages` sends the pages the model asks for to your model
61
+ provider, as the text of the file already goes. A PDF that is encrypted only to restrict printing
62
+ or copying is opened, and the cut is not encrypted: the restriction does not travel with it.
63
+
64
+ ## Reading PDFs for pages and pictures
65
+
66
+ Showing pages and marking pictures read the whole PDF into objects with `@cantoo/pdf-lib`, in your
67
+ process, on a file a user uploaded.
68
+
69
+ - **Memory.** About twice the size of the file, plus 1 to 1.6 KB for each object in it. A file of
70
+ 54 MB with 330,000 objects needed 700 MB. A file that declares more objects than the free heap
71
+ can hold, or more than a million, is refused before it is read (150,000 for the picture marks).
72
+ That check trusts what the file declares: a file that lies about it is still read.
73
+ - **Time, and no hard limit.** Reading cannot be interrupted once it has started. It pauses every
74
+ 4,000 objects so other requests get a turn, but a crafted file can hold the process: 1 MB of
75
+ junk between two objects took 3.6 seconds to skip. Errors are caught and the model is told that
76
+ the pages cannot be shown; a file that only takes long is not stopped.
77
+ - For uploads you do not trust, run ingest and the document tools in a worker thread or a separate
78
+ process with a memory limit and a timeout, as recommended for PDF text extraction below.
79
+
45
80
  ## Uploads
46
81
 
47
82
  - `maxUploadBytes` (default 100 MB) is enforced while reading, before the body is buffered fully.
48
83
  - The handlers buffer the upload in memory before extraction. Under heavy concurrent uploads, put a
49
84
  limit in front (a reverse proxy or a rate limiter).
50
- - Binary files are rejected. PDF parsing runs `unpdf` (pdf.js) on untrusted input in your process.
51
- Keep it updated, or move extraction to a worker or sandbox for high-risk deployments.
85
+ - Binary files are rejected, including compressed ones (`.gz`, `.zip`), which get a message
86
+ telling the user to decompress first. PDF parsing runs `unpdf` (pdf.js), and with it installed
87
+ `@cantoo/pdf-lib`, on untrusted input in your process. Keep them updated, or move extraction to a
88
+ worker or sandbox for high-risk deployments.
89
+ - File names are reduced to one printable line at ingest (no path, control characters, line
90
+ breaks, or text-direction overrides) and quoted in the system instruction, so a name can't add
91
+ lines to the prompt. The name is still text the model reads, like the file's content.
52
92
 
53
93
  ## Regex search
54
94
 
55
- Model-supplied regexes with nested quantifiers (`(a+)+`) are refused, and scans stop after 3
56
- seconds. A single very long line can still slow down a pathological pattern; lines are capped at
57
- 2,000 characters at ingest, which bounds the worst case.
95
+ The model writes the regex, and the model reads untrusted file text, so a file can ask for a
96
+ slow pattern. Two things bound the cost:
97
+
98
+ - Regexes with nested quantifiers (`(a+)+`) are refused up front. This is a quick filter, not a
99
+ guarantee: `(a|a)+$` and `((a+))+$` pass it.
100
+ - Every regex scan runs under a 3-second limit enforced by Node's `vm` timeout, which interrupts a
101
+ match that is still backtracking. The search returns what it found with a note that it stopped
102
+ early.
103
+
104
+ The scan is synchronous, so a slow pattern still holds the event loop for up to 3 seconds per
105
+ search. If that matters for your latency, run the document tools in a worker thread.
package/package.json CHANGED
@@ -1,91 +1,96 @@
1
- {
2
- "name": "llm-large-files",
3
- "version": "0.1.0",
4
- "description": "Let an LLM answer questions about books, logs, and other files larger than its request limit or context window: upload, plan, search and read tools, and map-reduce. Gemini and Vertex AI helpers included.",
5
- "keywords": [
6
- "llm",
7
- "gemini",
8
- "vertex-ai",
9
- "large-files",
10
- "long-context",
11
- "context-window",
12
- "function-calling",
13
- "tool-calling",
14
- "map-reduce",
15
- "logs",
16
- "pdf",
17
- "rag",
18
- "chatbot"
19
- ],
20
- "license": "MIT",
21
- "author": "renanbazinin",
22
- "repository": {
23
- "type": "git",
24
- "url": "git+https://github.com/renanbazinin/llm-large-files.git"
25
- },
26
- "homepage": "https://github.com/renanbazinin/llm-large-files#readme",
27
- "bugs": {
28
- "url": "https://github.com/renanbazinin/llm-large-files/issues"
29
- },
30
- "type": "module",
31
- "sideEffects": false,
32
- "engines": {
33
- "node": ">=20.19"
34
- },
35
- "main": "./dist/index.js",
36
- "types": "./dist/index.d.ts",
37
- "exports": {
38
- ".": {
39
- "types": "./dist/index.d.ts",
40
- "default": "./dist/index.js"
41
- },
42
- "./gemini": {
43
- "types": "./dist/gemini/index.d.ts",
44
- "default": "./dist/gemini/index.js"
45
- },
46
- "./node": {
47
- "types": "./dist/node/index.d.ts",
48
- "default": "./dist/node/index.js"
49
- },
50
- "./package.json": "./package.json"
51
- },
52
- "typesVersions": {
53
- "*": {
54
- "gemini": ["./dist/gemini/index.d.ts"],
55
- "node": ["./dist/node/index.d.ts"]
56
- }
57
- },
58
- "files": [
59
- "dist",
60
- "src",
61
- "docs",
62
- "CHANGELOG.md"
63
- ],
64
- "scripts": {
65
- "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
66
- "typecheck": "tsc --noEmit",
67
- "test": "vitest run",
68
- "test:watch": "vitest",
69
- "check": "npm run typecheck && npm test && npm run build",
70
- "prepublishOnly": "npm run check"
71
- },
72
- "peerDependencies": {
73
- "jszip": "^3.10.0",
74
- "unpdf": "^1.4.0"
75
- },
76
- "peerDependenciesMeta": {
77
- "jszip": {
78
- "optional": true
79
- },
80
- "unpdf": {
81
- "optional": true
82
- }
83
- },
84
- "devDependencies": {
85
- "@types/node": "^22.10.2",
86
- "jszip": "3.10.1",
87
- "typescript": "5.9.3",
88
- "unpdf": "1.4.0",
89
- "vitest": "3.2.7"
90
- }
91
- }
1
+ {
2
+ "name": "llm-large-files",
3
+ "version": "0.3.0",
4
+ "description": "Let an LLM answer questions about books, logs, and other files larger than its request limit or context window: upload, plan, search and read tools, map-reduce, and a look at the pages of a PDF. Gemini and Vertex AI helpers included.",
5
+ "keywords": [
6
+ "llm",
7
+ "gemini",
8
+ "vertex-ai",
9
+ "large-files",
10
+ "long-context",
11
+ "context-window",
12
+ "function-calling",
13
+ "tool-calling",
14
+ "map-reduce",
15
+ "logs",
16
+ "pdf",
17
+ "rag",
18
+ "chatbot"
19
+ ],
20
+ "license": "MIT",
21
+ "author": "renanbazinin",
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/renanbazinin/llm-large-files.git"
25
+ },
26
+ "homepage": "https://github.com/renanbazinin/llm-large-files#readme",
27
+ "bugs": {
28
+ "url": "https://github.com/renanbazinin/llm-large-files/issues"
29
+ },
30
+ "type": "module",
31
+ "sideEffects": false,
32
+ "engines": {
33
+ "node": ">=20.19"
34
+ },
35
+ "main": "./dist/index.js",
36
+ "types": "./dist/index.d.ts",
37
+ "exports": {
38
+ ".": {
39
+ "types": "./dist/index.d.ts",
40
+ "default": "./dist/index.js"
41
+ },
42
+ "./gemini": {
43
+ "types": "./dist/gemini/index.d.ts",
44
+ "default": "./dist/gemini/index.js"
45
+ },
46
+ "./node": {
47
+ "types": "./dist/node/index.d.ts",
48
+ "default": "./dist/node/index.js"
49
+ },
50
+ "./package.json": "./package.json"
51
+ },
52
+ "typesVersions": {
53
+ "*": {
54
+ "gemini": ["./dist/gemini/index.d.ts"],
55
+ "node": ["./dist/node/index.d.ts"]
56
+ }
57
+ },
58
+ "files": [
59
+ "dist",
60
+ "src",
61
+ "docs",
62
+ "CHANGELOG.md"
63
+ ],
64
+ "scripts": {
65
+ "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
66
+ "typecheck": "tsc --noEmit",
67
+ "test": "vitest run",
68
+ "test:watch": "vitest",
69
+ "check": "npm run typecheck && npm test && npm run build",
70
+ "prepublishOnly": "npm run check"
71
+ },
72
+ "peerDependencies": {
73
+ "@cantoo/pdf-lib": "^2.11.1",
74
+ "jszip": "^3.10.0",
75
+ "unpdf": "^1.4.0"
76
+ },
77
+ "peerDependenciesMeta": {
78
+ "@cantoo/pdf-lib": {
79
+ "optional": true
80
+ },
81
+ "jszip": {
82
+ "optional": true
83
+ },
84
+ "unpdf": {
85
+ "optional": true
86
+ }
87
+ },
88
+ "devDependencies": {
89
+ "@cantoo/pdf-lib": "2.11.1",
90
+ "@types/node": "^22.10.2",
91
+ "jszip": "3.10.1",
92
+ "typescript": "5.9.3",
93
+ "unpdf": "1.4.0",
94
+ "vitest": "3.2.7"
95
+ }
96
+ }
package/src/analyze.ts CHANGED
@@ -38,7 +38,9 @@ export function buildOutline(lines: string[], format: DocumentFormat): OutlineEn
38
38
  }
39
39
  if (entries.length <= MAX_OUTLINE_ENTRIES) return entries;
40
40
  // Keep the top levels first, then sample evenly so the outline still spans the document.
41
- const minLevel = Math.min(...entries.map((entry) => entry.level));
41
+ // A loop, not Math.min(...levels): spreading a few hundred thousand values overflows the stack.
42
+ let minLevel = Number.POSITIVE_INFINITY;
43
+ for (const entry of entries) if (entry.level < minLevel) minLevel = entry.level;
42
44
  const top = entries.filter((entry) => entry.level === minLevel);
43
45
  const pool = top.length >= 20 ? top : entries;
44
46
  const step = pool.length / MAX_OUTLINE_ENTRIES;
package/src/extract.ts CHANGED
@@ -1,4 +1,6 @@
1
- import type { DocumentFormat, ExtractedText, Extractor } from "./types.js";
1
+ import { layoutPage, plainPageText, type LayoutBox, type PdfTextItem } from "./pdf-layout.js";
2
+ import { findPicturePages, type PageGeometry } from "./pdf-pictures.js";
3
+ import type { DocumentFormat, ExtractedText, ExtractInput, Extractor } from "./types.js";
2
4
 
3
5
  const EXTENSION_FORMATS: Record<string, DocumentFormat> = {
4
6
  log: "log", out: "log", err: "log",
@@ -23,10 +25,22 @@ export function detectFormat(name: string, mimeType: string): DocumentFormat {
23
25
  return EXTENSION_FORMATS[extension] ?? MIME_FORMATS[mimeType.toLowerCase()] ?? "text";
24
26
  }
25
27
 
26
- /** Decodes text bytes, honoring UTF-8 and UTF-16 byte-order marks (common for Windows logs). */
28
+ const NOT_TEXT = "This file looks binary, not text. Attach a text, log, PDF, DOCX, or PPTX file.";
29
+
30
+ /**
31
+ * Decodes text bytes, honoring UTF-8 and UTF-16 byte-order marks (common for Windows logs).
32
+ * Throws a readable error for compressed and other binary files.
33
+ */
27
34
  export function decodeText(bytes: Uint8Array): string {
28
35
  if (bytes[0] === 0xff && bytes[1] === 0xfe) return new TextDecoder("utf-16le").decode(bytes.subarray(2));
29
36
  if (bytes[0] === 0xfe && bytes[1] === 0xff) return new TextDecoder("utf-16be").decode(bytes.subarray(2));
37
+ // Rotated logs often arrive as app.log.gz. Compressed bytes have few zeros, so name them here.
38
+ if (bytes[0] === 0x1f && bytes[1] === 0x8b) {
39
+ throw new Error("This file is gzip-compressed. Decompress it, then attach the text file inside.");
40
+ }
41
+ if (bytes[0] === 0x50 && bytes[1] === 0x4b && bytes[2] === 0x03 && bytes[3] === 0x04) {
42
+ throw new Error("This file is a ZIP archive. Extract it, then attach the text file you need.");
43
+ }
30
44
  const sample = bytes.subarray(0, 8_192);
31
45
  let zeros = 0;
32
46
  for (const byte of sample) if (byte === 0) zeros++;
@@ -41,9 +55,15 @@ export function decodeText(bytes: Uint8Array): string {
41
55
  const half = sample.length / 2;
42
56
  if (oddZeros / half > 0.6 && evenText / half > 0.6) return new TextDecoder("utf-16le").decode(bytes);
43
57
  }
44
- if (sample.length > 0 && zeros / sample.length > 0.01) {
45
- throw new Error("This file looks binary, not text. Attach a text, log, PDF, DOCX, or PPTX file.");
58
+ if (sample.length > 0 && zeros / sample.length > 0.01) throw new Error(NOT_TEXT);
59
+ // Compressed, encrypted, and media files spread control bytes evenly: about 1 byte in 10.
60
+ // Text has almost none, in UTF-8 or in a legacy single-byte encoding. Tab, line breaks, form
61
+ // feed, and ESC (colour codes) do not count.
62
+ let controls = 0;
63
+ for (const byte of sample) {
64
+ if (byte < 0x09 || (byte > 0x0d && byte < 0x20 && byte !== 0x1b) || byte === 0x7f) controls++;
46
65
  }
66
+ if (sample.length >= 64 && controls / sample.length > 0.03) throw new Error(NOT_TEXT);
47
67
  return new TextDecoder("utf-8").decode(bytes);
48
68
  }
49
69
 
@@ -120,40 +140,101 @@ const pptx: Extractor = async (bytes) => {
120
140
  return { text: slides.join("\n\n"), pages: names.length };
121
141
  };
122
142
 
123
- const pdf: Extractor = async (bytes) => {
124
- let unpdf: typeof import("unpdf");
125
- try {
126
- unpdf = await import("unpdf");
127
- } catch {
128
- throw new Error("Reading PDF files needs the optional dependency \"unpdf\".");
129
- }
130
- // pdf.js may detach the buffer it reads, so give it a copy.
131
- const document = await unpdf.getDocumentProxy(new Uint8Array(bytes));
132
- const { totalPages, text } = await unpdf.extractText(document, { mergePages: false });
133
- const pages = Array.isArray(text) ? text : [text];
134
- if (!pages.some((page) => page.trim())) {
135
- throw new Error("This PDF has no text layer (it may be scanned). It needs OCR before it can be searched.");
136
- }
137
- return {
138
- text: pages.map((page, index) => `--- Page ${index + 1} ---\n${page.trim()}`).join("\n\n"),
139
- pages: totalPages,
140
- };
143
+ export type PdfExtractorOptions = {
144
+ /**
145
+ * Rebuild tables from the position of the text, and write each row as `| cell | cell | |`, so an
146
+ * empty cell stays an empty cell. Defaults to true. With false, the text is in pdf.js order, as
147
+ * in version 0.1.0.
148
+ */
149
+ tables?: boolean;
150
+ /**
151
+ * Write a line under the page header of every page that shows a picture or a drawing, so the
152
+ * model knows that the text does not tell all of that page. Defaults to true. It needs the
153
+ * optional dependency `@cantoo/pdf-lib`; without it, and with false, the text is that of 0.2.0.
154
+ */
155
+ pictures?: boolean;
141
156
  };
142
157
 
158
+ /** Written in place of a page that has no text at all, so the model can say so instead of guessing. */
159
+ const PAGE_WITHOUT_TEXT = "[No text on this page. It may be a scan, a photo, or a chart.]";
160
+ /**
161
+ * Written under the header of a page that shows a picture or a drawing. The words hold whether or
162
+ * not the model is later given a way to look at the page.
163
+ */
164
+ export const PICTURE_ON_PAGE = "[Picture on this page. This text cannot show it.]";
165
+
166
+ /**
167
+ * The built-in PDF extractor (needs `unpdf`). Use it to change an option:
168
+ * `createLargeFiles({ extractors: { pdf: createPdfExtractor({ tables: false }) } })`.
169
+ */
170
+ export function createPdfExtractor(options: PdfExtractorOptions = {}): Extractor {
171
+ const tables = options.tables ?? true;
172
+ const pictures = options.pictures ?? true;
173
+ return async (bytes, input) => {
174
+ let unpdf: typeof import("unpdf");
175
+ try {
176
+ unpdf = await import("unpdf");
177
+ } catch {
178
+ throw new Error("Reading PDF files needs the optional dependency \"unpdf\".");
179
+ }
180
+ // pdf.js may detach the buffer it reads, so give it a copy.
181
+ const document = await unpdf.getDocumentProxy(new Uint8Array(bytes));
182
+ const texts: string[] = [];
183
+ const geometry: PageGeometry[] = [];
184
+ let hasText = false;
185
+ for (let number = 1; number <= document.numPages; number++) {
186
+ const page = await document.getPage(number);
187
+ const content = await page.getTextContent();
188
+ const items = (content.items as unknown[]).filter((item): item is PdfTextItem => typeof (item as PdfTextItem).str === "string");
189
+ const transform = page.getViewport({ scale: 1 }).transform as number[];
190
+ let text = "";
191
+ let found: LayoutBox[] = [];
192
+ if (tables) {
193
+ try {
194
+ ({ text, tables: found } = layoutPage(items, transform));
195
+ } catch {
196
+ // Unusual geometry must never lose a page: fall back to the plain order.
197
+ text = plainPageText(items);
198
+ }
199
+ } else {
200
+ text = plainPageText(items);
201
+ }
202
+ text = text.trim();
203
+ if (text) hasText = true;
204
+ texts.push(text);
205
+ geometry.push({ view: page.view, transform, tables: found });
206
+ page.cleanup();
207
+ }
208
+ if (!hasText) {
209
+ // A scan has nothing to search, but a short one can be read by looking at its pages, when the
210
+ // caller says that they can be shown. Every page then says that it has no text.
211
+ const most = input?.scannedPages ?? 0;
212
+ if (most <= 0) throw new Error("This PDF has no text layer (it may be scanned). It needs OCR before it can be searched.");
213
+ if (document.numPages > most) {
214
+ throw new Error(`This PDF has no text layer (it may be scanned) and ${document.numPages} pages. Without text it can only be read by looking at its pages, which works for up to ${most} pages. It needs OCR first.`);
215
+ }
216
+ }
217
+ // Which pages show a picture. Undefined when that could not be found out: then none is marked.
218
+ const pictured = pictures ? await findPicturePages(bytes, geometry) : undefined;
219
+ const pages = texts.map((text, index) => `--- Page ${index + 1} ---\n${pictured?.[index] ? `${PICTURE_ON_PAGE}\n` : ""}${text || PAGE_WITHOUT_TEXT}`);
220
+ return { text: pages.join("\n\n"), pages: document.numPages };
221
+ };
222
+ }
223
+
143
224
  export const defaultExtractors: Record<DocumentFormat, Extractor> = {
144
225
  text: plainText,
145
226
  markdown: plainText,
146
227
  log: plainText,
147
228
  json: plainText,
148
229
  csv: plainText,
149
- pdf,
230
+ pdf: createPdfExtractor(),
150
231
  docx,
151
232
  pptx,
152
233
  };
153
234
 
154
235
  export async function extractText(
155
236
  bytes: Uint8Array,
156
- input: { name: string; mimeType: string; format: DocumentFormat },
237
+ input: ExtractInput,
157
238
  extractors: Partial<Record<DocumentFormat, Extractor>> = {},
158
239
  ): Promise<ExtractedText> {
159
240
  const extractor = extractors[input.format] ?? defaultExtractors[input.format];