@floydous/pi-agent-kernel 0.5.0 → 0.6.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 (36) hide show
  1. package/AGENT_KERNEL_SYS_PROMPT.md +15 -6
  2. package/CHANGELOG.md +51 -0
  3. package/README.md +2 -3
  4. package/config.example.toml +1 -0
  5. package/docs/configuration.md +1 -1
  6. package/docs/editing-and-verification.md +20 -5
  7. package/docs/podman-linux-checks.md +24 -0
  8. package/docs/release-discipline.md +10 -0
  9. package/docs/retrieval.md +14 -11
  10. package/grammars/tree-sitter-html.wasm +0 -0
  11. package/package.json +2 -2
  12. package/src/config/agent_kernel_command.ts +59 -593
  13. package/src/config/kernel_config.ts +24 -2
  14. package/src/editing/patch.ts +48 -21
  15. package/src/editing/post_edit_verification.ts +8 -4
  16. package/src/editing/smart_anchor.ts +2 -1
  17. package/src/editing/syntax-verify.ts +73 -220
  18. package/src/index.ts +21 -196
  19. package/src/retrieval/html_chunker.ts +526 -0
  20. package/src/retrieval/search_bm25.ts +36 -27
  21. package/src/retrieval/search_chunker.ts +68 -6
  22. package/src/retrieval/search_config.ts +17 -34
  23. package/src/retrieval/search_embedder.ts +11 -29
  24. package/src/retrieval/search_index.ts +307 -145
  25. package/src/retrieval/search_modal.ts +1209 -222
  26. package/src/retrieval/tag_extractor.ts +1 -1
  27. package/src/retrieval/tree_sitter_engine.ts +103 -4
  28. package/src/retrieval/workspace_walker.ts +72 -0
  29. package/src/safety/host_environment.ts +180 -0
  30. package/src/safety/output_clamper.ts +83 -19
  31. package/src/tools/code_search_output.ts +9 -1
  32. package/src/tools/code_search_tool.ts +25 -10
  33. package/src/tools/context.ts +15 -0
  34. package/src/tools/edit_tool.ts +182 -60
  35. package/src/tools/read_tool.ts +245 -38
  36. package/src/tools/stream_reader.ts +206 -0
@@ -8,19 +8,23 @@ import {
8
8
  globalEpistemicGuard,
9
9
  resolveUserPath,
10
10
  } from "../safety/epistemic_guard";
11
- import type { SessionDeps } from "./context";
11
+ import { markReturnedErrors, type SessionDeps } from "./context";
12
+ import { isSpilloverFilePath, DEFAULT_SPILL_BYTES } from "../safety/output_clamper";
13
+ import { readStreamLineRangeFromFd } from "./stream_reader";
12
14
 
13
15
  const MAX_READ_LINES = 2_000;
14
16
  const MAX_READ_BYTES = 50 * 1024;
15
17
  const MAX_READ_FILE_BYTES = 5 * 1024 * 1024;
18
+ const MAX_STREAM_FILE_BYTES = DEFAULT_SPILL_BYTES;
16
19
  const DEFAULT_UNCONSTRAINED_LINES = 250;
17
20
 
18
- function validateReadableFile(filePath: string): string | null {
21
+ function validateReadableFile(filePath: string, isStreamable = false): string | null {
19
22
  try {
20
23
  const stat = fs.statSync(filePath);
21
24
  if (!stat.isFile()) return "Path is not a regular file";
22
- if (stat.size > MAX_READ_FILE_BYTES) {
23
- return `File is ${stat.size} bytes; maximum in-memory source size is ${MAX_READ_FILE_BYTES} bytes`;
25
+ const maxAllowed = isStreamable ? MAX_STREAM_FILE_BYTES : MAX_READ_FILE_BYTES;
26
+ if (stat.size > maxAllowed) {
27
+ return `File is ${stat.size} bytes; maximum ${isStreamable ? "streamable" : "in-memory source"} size is ${maxAllowed} bytes`;
24
28
  }
25
29
  return null;
26
30
  } catch (error: any) {
@@ -98,7 +102,7 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
98
102
  const benchmarkMethod = ["line-range", "search-replace", "hash-anchor", "adaptive"].includes(editMethod || "") ? editMethod : undefined;
99
103
  const readMode = process.env.PI_READ_MODE?.toLowerCase();
100
104
  let readToolDescription =
101
- "Read file contents with 50KB / 2,000-line caps. Supports bounded line-range inspection via 'offset' and 'limit', or batch inspection across multiple files via 'paths'.";
105
+ "Read file contents with 50KB / 2,000-line caps. Use when inspecting code around known line coordinates, reviewing exact file contents, or reading multiple files via 'paths'. Defaults to 250 lines when limit is omitted. Do NOT use read for finding files or symbols; use code_search or bash (find, rg) instead.";
102
106
  switch (benchmarkMethod) {
103
107
  case "line-range":
104
108
  readToolDescription = "Read source with line numbers for numeric line-range edits.";
@@ -170,6 +174,32 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
170
174
  }
171
175
  }
172
176
 
177
+ // Detect tool confusion (caller passed shell command to read tool)
178
+ if (params && typeof params === "object" && typeof params.command === "string" && params.command.trim().length > 0) {
179
+ if (targetPaths.length > 0) {
180
+ return {
181
+ content: [
182
+ {
183
+ type: "text",
184
+ text: `[READ ERROR] Ambiguous parameters: received both shell 'command' and file 'path'/'paths'. To execute commands, use 'bash'. To read files, use 'read' without 'command'.`,
185
+ },
186
+ ],
187
+ details: { error: "ambiguous_parameters", command: params.command.trim(), paths: targetPaths },
188
+ isError: true,
189
+ };
190
+ }
191
+ return {
192
+ content: [
193
+ {
194
+ type: "text",
195
+ text: `[READ ERROR] Received shell command in 'read' tool. To execute shell commands, invoke the 'bash' tool instead with { command: ${JSON.stringify(params.command.trim())} }. The 'read' tool is for inspecting file contents and requires { path: "path/to/file" }.`,
196
+ },
197
+ ],
198
+ details: { error: "tool_confusion_command", command: params.command.trim() },
199
+ isError: true,
200
+ };
201
+ }
202
+
173
203
  if (targetPaths.length === 0) {
174
204
  return {
175
205
  content: [
@@ -203,48 +233,101 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
203
233
  continue;
204
234
  }
205
235
  try {
206
- const readLimitError = validateReadableFile(resolvedPath);
236
+ const isSpill = isSpilloverFilePath(resolvedPath, ctx.cwd);
237
+ const isWindowed = params?.offset !== undefined || params?.limit !== undefined;
238
+ const isStreamable = isSpill || isWindowed;
239
+ const readLimitError = validateReadableFile(resolvedPath, isStreamable);
207
240
  if (readLimitError) {
208
241
  results.push(`=== file: ${relPath} ===\nRead rejected: ${readLimitError}`);
209
242
  continue;
210
243
  }
211
- const content = fs.readFileSync(resolvedPath, "utf-8");
212
- const lines = content.split("\n");
213
- const totalLines = lines.length;
244
+
245
+ const stat = fs.statSync(resolvedPath);
246
+ const needsStreaming = isSpill || stat.size > MAX_READ_FILE_BYTES;
214
247
  const fileOffset = params.offset && params.offset > 0 ? params.offset : 1;
215
248
  const fileLimit = params.limit ? Math.min(params.limit, MAX_BATCH_FILE_LINES) : MAX_BATCH_FILE_LINES;
216
- const startIdx = Math.max(0, fileOffset - 1);
217
- const endIdx = Math.min(totalLines, startIdx + fileLimit);
218
-
219
- const numberWidth = String(totalLines).length;
220
- // Batch reads are always plain text to protect token budgets
221
- const formatLine = (index: number) => formatReadLine(lines, index, false, numberWidth, benchmarkMethod);
222
- const visibleIndexes = selectReadLineIndexes(lines, startIdx, endIdx, formatLine);
223
- const outputLines = visibleIndexes.map(formatLine);
224
- const isTruncated = (startIdx + visibleIndexes.length) < totalLines || startIdx > 0;
225
- if (isTruncated) {
226
- outputLines.push(`[truncated: ${relPath}, returned lines ${startIdx + 1}-${startIdx + visibleIndexes.length} of ${totalLines}. Continue with read(path, offset=${startIdx + visibleIndexes.length + 1})]`);
227
- }
228
249
 
229
- globalEpistemicGuard.recordFileRead(
230
- resolvedPath,
231
- deps.getSessionId(ctx),
232
- ctx.cwd,
233
- content,
234
- {
235
- coverage: {
236
- complete: !isTruncated,
237
- ranges: lineRanges(visibleIndexes),
238
- totalLines,
250
+ let outputLines: string[];
251
+ let totalLines: number;
252
+ let shownCount: number;
253
+ let isTruncated: boolean;
254
+
255
+ if (needsStreaming) {
256
+ const fd = fs.openSync(resolvedPath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
257
+ let streamRes: ReturnType<typeof readStreamLineRangeFromFd>;
258
+ try {
259
+ streamRes = readStreamLineRangeFromFd(fd, {
260
+ offset: fileOffset,
261
+ limit: fileLimit,
262
+ maxBytes: Math.min(MAX_READ_BYTES, Math.max(1024, MAX_BATCH_BYTES - cumulativeBytes)),
263
+ });
264
+ } finally {
265
+ fs.closeSync(fd);
266
+ }
267
+ if (streamRes.isBinary) {
268
+ results.push(`=== file: ${relPath} ===\nRead rejected: Binary file cannot be displayed as text`);
269
+ continue;
270
+ }
271
+ outputLines = streamRes.lines;
272
+ totalLines = streamRes.endLine;
273
+ shownCount = streamRes.totalLinesRead;
274
+ isTruncated = streamRes.hasMore || streamRes.startLine > 1;
275
+ if (isTruncated) {
276
+ outputLines.push(`[truncated: ${relPath}, returned lines ${streamRes.startLine}-${streamRes.endLine}. Continue with read(path, offset=${streamRes.endLine + 1})]`);
277
+ }
278
+
279
+ globalEpistemicGuard.recordFileRead(
280
+ resolvedPath,
281
+ deps.getSessionId(ctx),
282
+ ctx.cwd,
283
+ streamRes.lines.join("\n"),
284
+ {
285
+ coverage: {
286
+ complete: !streamRes.hasMore && streamRes.startLine === 1,
287
+ ranges: [{ startLine: streamRes.startLine, endLine: streamRes.endLine }],
288
+ totalLines,
289
+ },
290
+ provenance: "read",
239
291
  },
240
- provenance: "read",
241
- },
242
- );
292
+ );
293
+ } else {
294
+ const content = fs.readFileSync(resolvedPath, "utf-8");
295
+ const lines = content.split("\n");
296
+ totalLines = lines.length;
297
+ const startIdx = Math.max(0, fileOffset - 1);
298
+ const endIdx = Math.min(totalLines, startIdx + fileLimit);
299
+
300
+ const numberWidth = String(totalLines).length;
301
+ // Batch reads are always plain text to protect token budgets
302
+ const formatLine = (index: number) => formatReadLine(lines, index, false, numberWidth, benchmarkMethod);
303
+ const visibleIndexes = selectReadLineIndexes(lines, startIdx, endIdx, formatLine);
304
+ outputLines = visibleIndexes.map(formatLine);
305
+ shownCount = visibleIndexes.length;
306
+ isTruncated = (startIdx + visibleIndexes.length) < totalLines || startIdx > 0;
307
+ if (isTruncated) {
308
+ outputLines.push(`[truncated: ${relPath}, returned lines ${startIdx + 1}-${startIdx + visibleIndexes.length} of ${totalLines}. Continue with read(path, offset=${startIdx + visibleIndexes.length + 1})]`);
309
+ }
310
+
311
+ globalEpistemicGuard.recordFileRead(
312
+ resolvedPath,
313
+ deps.getSessionId(ctx),
314
+ ctx.cwd,
315
+ content,
316
+ {
317
+ coverage: {
318
+ complete: !isTruncated && startIdx === 0 && endIdx === totalLines,
319
+ ranges: lineRanges(visibleIndexes),
320
+ totalLines,
321
+ },
322
+ provenance: "read",
323
+ },
324
+ );
325
+ }
243
326
 
244
327
  const formattedOutput = `=== file: ${relPath} (${totalLines} lines) ===\n${outputLines.join("\n")}`;
245
328
  cumulativeBytes += Buffer.byteLength(formattedOutput, "utf8");
246
329
  results.push(formattedOutput);
247
- detailsList.push({ path: filePath, totalLines, shownLines: visibleIndexes.length, truncated: isTruncated });
330
+ detailsList.push({ path: filePath, totalLines, shownLines: shownCount, truncated: isTruncated });
248
331
  hasAnySuccess = true;
249
332
 
250
333
  if (cumulativeBytes >= MAX_BATCH_BYTES && i < pathsToRead.length - 1) {
@@ -279,11 +362,14 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
279
362
 
280
363
  // Single file read
281
364
  try {
282
- const readLimitError = validateReadableFile(resolvedPath);
365
+ const isSpill = isSpilloverFilePath(resolvedPath, ctx.cwd);
366
+ const isWindowed = params?.offset !== undefined || params?.limit !== undefined;
367
+ const isStreamable = isSpill || isWindowed;
368
+ const readLimitError = validateReadableFile(resolvedPath, isStreamable);
283
369
  if (readLimitError) {
284
370
  return {
285
371
  content: [{ type: "text", text: `[READ ERROR] ${readLimitError}: ${params.path}` }],
286
- details: { error: "read_limit", maxBytes: MAX_READ_FILE_BYTES },
372
+ details: { error: "read_limit", maxBytes: isStreamable ? MAX_STREAM_FILE_BYTES : MAX_READ_FILE_BYTES },
287
373
  isError: true,
288
374
  };
289
375
  }
@@ -340,6 +426,127 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
340
426
  };
341
427
  }
342
428
 
429
+ // Validate pagination parameters explicitly before I/O
430
+ if (
431
+ params.offset !== undefined &&
432
+ (!Number.isFinite(params.offset) || params.offset < 1)
433
+ ) {
434
+ return {
435
+ content: [
436
+ {
437
+ type: "text",
438
+ text: `[READ ERROR] Invalid offset=${params.offset}. 'offset' must be a number >= 1 (1-based line number).`,
439
+ },
440
+ ],
441
+ details: { offset: params.offset },
442
+ isError: true,
443
+ };
444
+ }
445
+ if (
446
+ params.limit !== undefined &&
447
+ (!Number.isFinite(params.limit) || params.limit < 1)
448
+ ) {
449
+ return {
450
+ content: [
451
+ {
452
+ type: "text",
453
+ text: `[READ ERROR] Invalid limit=${params.limit}. 'limit' must be a number >= 1.`,
454
+ },
455
+ ],
456
+ details: { limit: params.limit },
457
+ isError: true,
458
+ };
459
+ }
460
+
461
+ const stat = fs.statSync(resolvedPath);
462
+ const needsStreaming = isSpill || stat.size > MAX_READ_FILE_BYTES;
463
+
464
+ if (needsStreaming) {
465
+ let fd: number;
466
+ try {
467
+ fd = fs.openSync(resolvedPath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
468
+ } catch (openErr: any) {
469
+ return {
470
+ content: [{ type: "text", text: `[READ ERROR] Failed opening ${params.path}: ${openErr?.message || String(openErr)}` }],
471
+ isError: true,
472
+ };
473
+ }
474
+
475
+ let streamRes: ReturnType<typeof readStreamLineRangeFromFd>;
476
+ try {
477
+ const fstat = fs.fstatSync(fd);
478
+ if (!fstat.isFile()) {
479
+ return { content: [{ type: "text", text: `[READ ERROR] Path is not a regular file: ${params.path}` }], isError: true };
480
+ }
481
+ if (fstat.size > MAX_STREAM_FILE_BYTES) {
482
+ return { content: [{ type: "text", text: `[READ ERROR] File is ${fstat.size} bytes; maximum streamable size is ${MAX_STREAM_FILE_BYTES} bytes: ${params.path}` }], isError: true };
483
+ }
484
+
485
+ const offset = params.offset && params.offset > 0 ? params.offset : 1;
486
+ const limit = params.limit ? Math.min(params.limit, MAX_READ_LINES) : DEFAULT_UNCONSTRAINED_LINES;
487
+
488
+ streamRes = readStreamLineRangeFromFd(fd, { offset, limit, maxBytes: MAX_READ_BYTES });
489
+ } finally {
490
+ fs.closeSync(fd);
491
+ }
492
+
493
+ if (streamRes.isBinary) {
494
+ return {
495
+ content: [{ type: "text", text: `[READ ERROR] Binary file cannot be displayed as text: ${params.path}` }],
496
+ isError: true,
497
+ };
498
+ }
499
+
500
+ const relPath = (path.relative(ctx.cwd, resolvedPath) || params.path).replace(/\\/g, "/");
501
+ const numberWidth = String(streamRes.endLine || 1).length;
502
+ const config = deps.getConfig?.(ctx.cwd);
503
+ const defaultAnchors = config?.editing?.default_anchors ?? true;
504
+ const configuredReadMode = readMode ?? config?.editing?.read_mode ?? "auto";
505
+ const useAnchors = shouldUseAnchors(params, benchmarkMethod, configuredReadMode, defaultAnchors, false);
506
+
507
+ const formattedLines = streamRes.lines.map((line, idx) => {
508
+ const lineNum = streamRes.startLine + idx;
509
+ if (useAnchors) {
510
+ return `${String(lineNum).padStart(numberWidth, " ")}#${computeLineHash(streamRes.lines, idx)}│${line}`;
511
+ }
512
+ if (benchmarkMethod === "line-range" || benchmarkMethod === "adaptive") {
513
+ return `${String(lineNum).padStart(numberWidth, " ")}│${line}`;
514
+ }
515
+ return line;
516
+ });
517
+
518
+ if (streamRes.singleLineTruncated) {
519
+ formattedLines.push("[Line 1 truncated at 50 KB: no newline found in the initial 50 KB of text. File is a single continuous line.]");
520
+ } else if (streamRes.hasMore) {
521
+ formattedLines.push(`[truncated: ${relPath}, returned lines ${streamRes.startLine}-${streamRes.endLine}. Continue with read(path, offset=${streamRes.endLine + 1})]`);
522
+ }
523
+
524
+ globalEpistemicGuard.recordFileRead(
525
+ resolvedPath,
526
+ deps.getSessionId(ctx),
527
+ ctx.cwd,
528
+ streamRes.lines.join("\n"),
529
+ {
530
+ coverage: {
531
+ complete: !streamRes.hasMore && streamRes.startLine === 1,
532
+ ranges: [{ startLine: streamRes.startLine, endLine: streamRes.endLine }],
533
+ },
534
+ provenance: "read",
535
+ },
536
+ );
537
+
538
+ return {
539
+ content: [{ type: "text", text: formattedLines.join("\n") }],
540
+ details: {
541
+ offset: streamRes.startLine,
542
+ limit: streamRes.totalLinesRead,
543
+ hasMore: streamRes.hasMore,
544
+ streamed: true,
545
+ singleLineTruncated: streamRes.singleLineTruncated,
546
+ },
547
+ };
548
+ }
549
+
343
550
  const content = fs.readFileSync(resolvedPath, "utf-8");
344
551
  const lines = content.split("\n");
345
552
  const totalLines = lines.length;
@@ -505,5 +712,5 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
505
712
  },
506
713
  };
507
714
 
508
- pi.registerTool(readToolDefinition);
715
+ pi.registerTool(markReturnedErrors(readToolDefinition));
509
716
  }
@@ -0,0 +1,206 @@
1
+ import * as fs from "node:fs";
2
+ import { StringDecoder } from "node:string_decoder";
3
+
4
+ export interface StreamedReadResult {
5
+ lines: string[];
6
+ startLine: number;
7
+ endLine: number;
8
+ totalLinesRead: number;
9
+ hasMore: boolean;
10
+ totalBytes: number;
11
+ truncatedByBytes: boolean;
12
+ singleLineTruncated: boolean;
13
+ isBinary: boolean;
14
+ }
15
+
16
+ const CHUNK_SIZE = 64 * 1024;
17
+ const MAX_READ_BYTES = 50 * 1024; // 50 KB output budget
18
+ const MAX_SINGLE_LINE_BYTES = 50 * 1024;
19
+
20
+ /**
21
+ * Hardened bounded streaming line reader.
22
+ * Operates directly on an open file descriptor to eliminate TOCTOU races.
23
+ * Uses StringDecoder to prevent multi-byte UTF-8 character corruption across 64 KB chunk boundaries.
24
+ * Strictly caps single-line accumulation at 50 KB with early I/O exit to prevent O(N) heap blowup on newline-free files.
25
+ * Memory is strictly O(1) (< 200 KB) regardless of file size.
26
+ */
27
+ export function readStreamLineRangeFromFd(
28
+ fd: number,
29
+ options: {
30
+ offset?: number;
31
+ limit?: number;
32
+ maxBytes?: number;
33
+ } = {},
34
+ ): StreamedReadResult {
35
+ const offset = Math.max(1, options.offset ?? 1);
36
+ const limit = Math.max(1, Math.min(options.limit ?? 250, 2000));
37
+ const maxBytes = options.maxBytes ?? MAX_READ_BYTES;
38
+
39
+ const buf = Buffer.allocUnsafe(CHUNK_SIZE);
40
+ let currentLine = 1;
41
+ const targetEndLine = offset + limit - 1;
42
+ const collectedLines: string[] = [];
43
+ let accumulatedBytes = 0;
44
+ let truncatedByBytes = false;
45
+ let singleLineTruncated = false;
46
+ let hasMore = false;
47
+ let isBinary = false;
48
+ let checkedBinary = false;
49
+
50
+ const lineDecoder = new StringDecoder("utf8");
51
+ let currentLineDecoded = "";
52
+ let currentLineAccumulatedBytes = 0;
53
+ let skippingExcessInLine = false;
54
+
55
+ try {
56
+ let bytesRead = 0;
57
+ while ((bytesRead = fs.readSync(fd, buf, 0, CHUNK_SIZE, null)) > 0) {
58
+ // Binary guard: check for 0x00 null byte in the initial 8 KB
59
+ if (!checkedBinary) {
60
+ checkedBinary = true;
61
+ const probeLength = Math.min(bytesRead, 8192);
62
+ if (buf.subarray(0, probeLength).includes(0)) {
63
+ isBinary = true;
64
+ break;
65
+ }
66
+ }
67
+
68
+ let lineStart = 0;
69
+ for (let i = 0; i < bytesRead; i++) {
70
+ if (buf[i] === 0x0a) { // '\n'
71
+ const lineSlice = buf.subarray(lineStart, i);
72
+
73
+ if (currentLine >= offset && currentLine <= targetEndLine) {
74
+ if (!skippingExcessInLine) {
75
+ currentLineDecoded += lineDecoder.write(lineSlice);
76
+ currentLineAccumulatedBytes += lineSlice.length;
77
+ }
78
+ // Flush any remaining characters in decoder for this line
79
+ currentLineDecoded += lineDecoder.end();
80
+ // Strip trailing '\r' safely across buffer boundaries
81
+ if (currentLineDecoded.endsWith("\r")) {
82
+ currentLineDecoded = currentLineDecoded.slice(0, -1);
83
+ }
84
+
85
+ const lineBytes = Buffer.byteLength(currentLineDecoded, "utf8");
86
+ if (accumulatedBytes + lineBytes + (collectedLines.length > 0 ? 1 : 0) > maxBytes) {
87
+ if (collectedLines.length === 0) {
88
+ const clipped = currentLineDecoded.slice(0, Math.max(10, maxBytes - 50)) + "... <line truncated>";
89
+ collectedLines.push(clipped);
90
+ accumulatedBytes = Buffer.byteLength(clipped, "utf8");
91
+ }
92
+ truncatedByBytes = true;
93
+ hasMore = true;
94
+ break;
95
+ }
96
+
97
+ collectedLines.push(currentLineDecoded);
98
+ accumulatedBytes += lineBytes + (collectedLines.length > 1 ? 1 : 0);
99
+ }
100
+
101
+ // Reset state for next line
102
+ currentLineDecoded = "";
103
+ currentLineAccumulatedBytes = 0;
104
+ skippingExcessInLine = false;
105
+ currentLine++;
106
+ lineStart = i + 1;
107
+
108
+ if (currentLine > targetEndLine) {
109
+ hasMore = true;
110
+ break;
111
+ }
112
+ } else {
113
+ // Byte within a line
114
+ if (currentLine >= offset && currentLine <= targetEndLine) {
115
+ if (!skippingExcessInLine) {
116
+ // Hard cap per line to prevent O(N) memory on newline-free files
117
+ if (currentLineAccumulatedBytes + (i - lineStart + 1) > MAX_SINGLE_LINE_BYTES) {
118
+ const safeSlice = buf.subarray(lineStart, i + 1);
119
+ currentLineDecoded += lineDecoder.write(safeSlice);
120
+ currentLineDecoded += lineDecoder.end();
121
+ currentLineDecoded += "... <line truncated: exceeds 50 KB>";
122
+ singleLineTruncated = true;
123
+ skippingExcessInLine = true;
124
+ // Early I/O exit: when line 1 hits the 50 KB budget, stop reading immediately
125
+ if (collectedLines.length === 0) {
126
+ collectedLines.push(currentLineDecoded);
127
+ accumulatedBytes = Buffer.byteLength(currentLineDecoded, "utf8");
128
+ truncatedByBytes = true;
129
+ hasMore = true;
130
+ break;
131
+ }
132
+ }
133
+ }
134
+ }
135
+ }
136
+ }
137
+
138
+ if (truncatedByBytes || currentLine > targetEndLine) {
139
+ break;
140
+ }
141
+
142
+ // Incomplete line remaining at end of chunk
143
+ if (lineStart < bytesRead && currentLine >= offset && currentLine <= targetEndLine) {
144
+ if (!skippingExcessInLine) {
145
+ const leftover = buf.subarray(lineStart, bytesRead);
146
+ currentLineDecoded += lineDecoder.write(leftover);
147
+ currentLineAccumulatedBytes += leftover.length;
148
+ if (currentLineAccumulatedBytes > MAX_SINGLE_LINE_BYTES) {
149
+ currentLineDecoded += lineDecoder.end();
150
+ currentLineDecoded += "... <line truncated: exceeds 50 KB>";
151
+ singleLineTruncated = true;
152
+ skippingExcessInLine = true;
153
+ if (collectedLines.length === 0) {
154
+ collectedLines.push(currentLineDecoded);
155
+ accumulatedBytes = Buffer.byteLength(currentLineDecoded, "utf8");
156
+ truncatedByBytes = true;
157
+ hasMore = true;
158
+ break;
159
+ }
160
+ }
161
+ }
162
+ }
163
+ }
164
+
165
+ // Trailing line without trailing newline
166
+ if (!isBinary && !truncatedByBytes && currentLine >= offset && currentLine <= targetEndLine) {
167
+ if (!skippingExcessInLine) {
168
+ currentLineDecoded += lineDecoder.end();
169
+ }
170
+ if (currentLineDecoded.length > 0) {
171
+ if (currentLineDecoded.endsWith("\r")) {
172
+ currentLineDecoded = currentLineDecoded.slice(0, -1);
173
+ }
174
+ const lineBytes = Buffer.byteLength(currentLineDecoded, "utf8");
175
+ if (accumulatedBytes + lineBytes <= maxBytes) {
176
+ collectedLines.push(currentLineDecoded);
177
+ accumulatedBytes += lineBytes;
178
+ } else if (collectedLines.length === 0) {
179
+ const clipped = currentLineDecoded.slice(0, Math.max(10, maxBytes - 50)) + "... <line truncated>";
180
+ collectedLines.push(clipped);
181
+ accumulatedBytes = Buffer.byteLength(clipped, "utf8");
182
+ truncatedByBytes = true;
183
+ hasMore = true;
184
+ } else {
185
+ truncatedByBytes = true;
186
+ hasMore = true;
187
+ }
188
+ }
189
+ }
190
+ } finally {
191
+ lineDecoder.end();
192
+ }
193
+
194
+ const endLine = offset + collectedLines.length - 1;
195
+ return {
196
+ lines: collectedLines,
197
+ startLine: collectedLines.length > 0 ? offset : 0,
198
+ endLine: collectedLines.length > 0 ? endLine : 0,
199
+ totalLinesRead: collectedLines.length,
200
+ hasMore,
201
+ totalBytes: accumulatedBytes,
202
+ truncatedByBytes,
203
+ singleLineTruncated,
204
+ isBinary,
205
+ };
206
+ }