Add limit for files Cline reads into context (#2199)
* Revert "Merge pull request #1964 from cline/ocasta181/ENG-209" This reverts commitca17a06618, reversing changes made to6b9c2a1a45. * Set hard 300kb limit on file size cline reads into context * Add changeset
This commit is contained in:
1 parent
ca17a06618
commit
9aa04a376f
10 files changed
+64
-391
No files matched your search
@@ -1,67 +0,0 @@
|
||||
import { expect } from "chai"
|
||||
import { extractTextFromFile } from "./extract-text"
|
||||
import fs from "fs/promises"
|
||||
import path from "path"
|
||||
import os from "os"
|
||||
import { ContentTooLargeError } from "../../shared/errors"
|
||||
|
||||
const CONTEXT_LIMIT = 1000 // Context limit of 1000 tokens means max allowed size is 500 tokens
|
||||
|
||||
describe("extract-text", () => {
|
||||
let tempFilePath: string
|
||||
|
||||
beforeEach(async () => {
|
||||
tempFilePath = path.join(os.tmpdir(), "test-file.txt")
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await fs.unlink(tempFilePath).catch(() => {})
|
||||
})
|
||||
|
||||
it("throws error for non-existent file", async () => {
|
||||
const nonExistentPath = path.join(os.tmpdir(), "non-existent.txt")
|
||||
try {
|
||||
await extractTextFromFile(nonExistentPath, CONTEXT_LIMIT)
|
||||
throw new Error("Should have thrown error")
|
||||
} catch (error) {
|
||||
expect(error.message).to.include("File not found")
|
||||
}
|
||||
})
|
||||
|
||||
it("throws ContentTooLargeError when file would exceed max allowed size", async () => {
|
||||
// Create content that would exceed max allowed size (37k tokens)
|
||||
const largeContent = "x".repeat(148000) // 37k tokens
|
||||
await fs.writeFile(tempFilePath, largeContent)
|
||||
|
||||
try {
|
||||
await extractTextFromFile(tempFilePath, 37_000) // Pass pre-processed maxAllowedSize
|
||||
throw new Error("Should have thrown error")
|
||||
} catch (error) {
|
||||
expect(error).to.be.instanceOf(ContentTooLargeError)
|
||||
expect(error.details.type).to.equal("file")
|
||||
expect(error.details.path).to.equal(tempFilePath)
|
||||
expect(error.details.size.wouldExceedLimit).to.equal(true)
|
||||
}
|
||||
})
|
||||
|
||||
it("reads text file content when within size limit", async () => {
|
||||
const content = "Hello world"
|
||||
await fs.writeFile(tempFilePath, content)
|
||||
|
||||
const result = await extractTextFromFile(tempFilePath, CONTEXT_LIMIT)
|
||||
expect(result).to.equal(content)
|
||||
})
|
||||
|
||||
it("throws error for binary files", async () => {
|
||||
// Create a simple binary file
|
||||
const buffer = new Uint8Array([0x89, 0x50, 0x4e, 0x47]) // PNG file header
|
||||
await fs.writeFile(tempFilePath, buffer, { encoding: "binary" })
|
||||
|
||||
try {
|
||||
await extractTextFromFile(tempFilePath, CONTEXT_LIMIT)
|
||||
throw new Error("Should have thrown error")
|
||||
} catch (error) {
|
||||
expect(error.message).to.include("Cannot read text for file type")
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -4,102 +4,35 @@ import pdf from "pdf-parse/lib/pdf-parse"
|
||||
import mammoth from "mammoth"
|
||||
import fs from "fs/promises"
|
||||
import { isBinaryFile } from "isbinaryfile"
|
||||
import { estimateContentSize, estimateFileSize, wouldExceedSizeLimit, getMaxAllowedSize } from "../../utils/content-size"
|
||||
import { ContentTooLargeError } from "../../shared/errors"
|
||||
import { getFileSizeInKB } from "../../utils/fs"
|
||||
|
||||
/**
|
||||
* Checks if terminal output would exceed size limits and returns the content if safe
|
||||
* @param content The terminal output content to check
|
||||
* @param contextWindow Context window limit in tokens
|
||||
* @param command The command that generated this output (for error reporting)
|
||||
* @returns The validated content
|
||||
* @throws ContentTooLargeError if content exceeds size limit
|
||||
*/
|
||||
export async function extractTextFromTerminal(content: string | Buffer, contextWindow: number, command: string): Promise<string> {
|
||||
console.debug(`[TERMINAL_SIZE_CHECK] Checking size for command output: ${command}`)
|
||||
|
||||
// Convert to string but don't trim yet
|
||||
const rawContent = content.toString()
|
||||
console.debug(`[TERMINAL_SIZE_CHECK] Raw content length: ${rawContent.length}`)
|
||||
|
||||
// Check size before trimming
|
||||
const sizeEstimate = estimateContentSize(rawContent, contextWindow)
|
||||
console.debug(`[TERMINAL_SIZE_CHECK] Content size: ${sizeEstimate.bytes} bytes`)
|
||||
console.debug(`[TERMINAL_SIZE_CHECK] Estimated tokens: ${sizeEstimate.estimatedTokens}`)
|
||||
console.debug(`[TERMINAL_SIZE_CHECK] Context window: ${contextWindow}`)
|
||||
|
||||
if (sizeEstimate.wouldExceedLimit) {
|
||||
console.debug(`[TERMINAL_SIZE_CHECK] Output exceeds size limit`)
|
||||
throw new ContentTooLargeError({
|
||||
type: "terminal",
|
||||
command,
|
||||
size: sizeEstimate,
|
||||
})
|
||||
}
|
||||
|
||||
// Only trim after size check passes
|
||||
const cleanContent = rawContent.trim()
|
||||
console.debug(`[TERMINAL_SIZE_CHECK] Clean content length: ${cleanContent.length}`)
|
||||
console.debug(`[TERMINAL_SIZE_CHECK] Size check passed`)
|
||||
return cleanContent
|
||||
}
|
||||
|
||||
export async function extractTextFromFile(
|
||||
filePath: string,
|
||||
contextWindow: number = 64_000 /* minimum context (Deepseek) */,
|
||||
): Promise<string> {
|
||||
export async function extractTextFromFile(filePath: string): Promise<string> {
|
||||
try {
|
||||
await fs.access(filePath)
|
||||
} catch (error) {
|
||||
throw new Error(`File not found: ${filePath}`)
|
||||
}
|
||||
|
||||
console.debug(`[FILE_READ_CHECK] Checking size for file: ${filePath}`)
|
||||
|
||||
// Get file stats to check size
|
||||
const stats = await fs.stat(filePath)
|
||||
console.debug(`[FILE_SIZE_CHECK] File size: ${stats.size} bytes`)
|
||||
|
||||
// Calculate max allowed size from context window
|
||||
const maxAllowedSize = getMaxAllowedSize(contextWindow)
|
||||
console.debug(`[FILE_SIZE_CHECK] Max allowed size: ${maxAllowedSize} tokens`)
|
||||
|
||||
// Check if file size would exceed limit before attempting to read
|
||||
// This is more efficient than creating a full SizeEstimate object when we just need a boolean check
|
||||
if (wouldExceedSizeLimit(stats.size, contextWindow)) {
|
||||
console.debug(`[FILE_SIZE_CHECK] File exceeds size limit`)
|
||||
// Only create the full size estimate when we need it for the error
|
||||
const sizeEstimate = await estimateFileSize(filePath, maxAllowedSize)
|
||||
throw new ContentTooLargeError({
|
||||
type: "file",
|
||||
path: filePath,
|
||||
size: sizeEstimate,
|
||||
})
|
||||
}
|
||||
console.debug(`[FILE_SIZE_CHECK] File size check passed`)
|
||||
const fileExtension = path.extname(filePath).toLowerCase()
|
||||
console.debug(`[FILE_READ] Reading file: ${filePath}`)
|
||||
let content: string
|
||||
switch (fileExtension) {
|
||||
case ".pdf":
|
||||
content = await extractTextFromPDF(filePath)
|
||||
break
|
||||
return extractTextFromPDF(filePath)
|
||||
case ".docx":
|
||||
content = await extractTextFromDOCX(filePath)
|
||||
break
|
||||
return extractTextFromDOCX(filePath)
|
||||
case ".ipynb":
|
||||
content = await extractTextFromIPYNB(filePath)
|
||||
break
|
||||
return extractTextFromIPYNB(filePath)
|
||||
default:
|
||||
const isBinary = await isBinaryFile(filePath).catch(() => false)
|
||||
if (!isBinary) {
|
||||
content = await fs.readFile(filePath, "utf8")
|
||||
// If file is over 300KB, throw an error
|
||||
const fileSizeInKB = await getFileSizeInKB(filePath)
|
||||
if (fileSizeInKB > 300) {
|
||||
throw new Error(`File is too large to read into context.`)
|
||||
}
|
||||
return await fs.readFile(filePath, "utf8")
|
||||
} else {
|
||||
throw new Error(`Cannot read text for file type: ${fileExtension}`)
|
||||
}
|
||||
}
|
||||
console.debug(`[FILE_READ_COMPLETE] File read complete. Content length: ${content.length} chars`)
|
||||
return content
|
||||
}
|
||||
|
||||
async function extractTextFromPDF(filePath: string): Promise<string> {
|
||||
|
||||
Reference in new issue
Block a user