@floydous/pi-agent-kernel 0.5.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENT_KERNEL_SYS_PROMPT.md +20 -6
- package/CHANGELOG.md +69 -0
- package/README.md +23 -20
- package/config.example.toml +1 -0
- package/docs/configuration.md +1 -1
- package/docs/editing-and-verification.md +20 -5
- package/docs/podman-linux-checks.md +24 -0
- package/docs/release-discipline.md +10 -0
- package/docs/retrieval.md +14 -11
- package/grammars/tree-sitter-html.wasm +0 -0
- package/package.json +2 -2
- package/src/config/agent_kernel_command.ts +60 -593
- package/src/config/kernel_config.ts +46 -2
- package/src/editing/patch.ts +48 -21
- package/src/editing/post_edit_verification.ts +8 -4
- package/src/editing/smart_anchor.ts +2 -1
- package/src/editing/syntax-verify.ts +73 -220
- package/src/index.ts +105 -203
- package/src/retrieval/html_chunker.ts +526 -0
- package/src/retrieval/search_bm25.ts +36 -27
- package/src/retrieval/search_chunker.ts +68 -6
- package/src/retrieval/search_config.ts +17 -34
- package/src/retrieval/search_embedder.ts +11 -29
- package/src/retrieval/search_index.ts +307 -145
- package/src/retrieval/search_modal.ts +1247 -222
- package/src/retrieval/tag_extractor.ts +1 -1
- package/src/retrieval/tree_sitter_engine.ts +103 -4
- package/src/retrieval/workspace_walker.ts +72 -0
- package/src/safety/host_environment.ts +190 -0
- package/src/safety/output_clamper.ts +83 -19
- package/src/tools/code_search_output.ts +9 -1
- package/src/tools/code_search_tool.ts +51 -14
- package/src/tools/context.ts +15 -0
- package/src/tools/edit_tool.ts +306 -79
- package/src/tools/read_tool.ts +248 -39
- package/src/tools/stream_reader.ts +206 -0
- package/src/ui/tui_utils.ts +70 -12
package/src/tools/read_tool.ts
CHANGED
|
@@ -8,19 +8,23 @@ import {
|
|
|
8
8
|
globalEpistemicGuard,
|
|
9
9
|
resolveUserPath,
|
|
10
10
|
} from "../safety/epistemic_guard";
|
|
11
|
-
import type
|
|
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
|
-
|
|
23
|
-
|
|
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.
|
|
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 (when enabled) or bash (rg, find) instead.";
|
|
102
106
|
switch (benchmarkMethod) {
|
|
103
107
|
case "line-range":
|
|
104
108
|
readToolDescription = "Read source with line numbers for numeric line-range edits.";
|
|
@@ -131,17 +135,19 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
131
135
|
),
|
|
132
136
|
offset: Type.Optional(
|
|
133
137
|
Type.Number({
|
|
138
|
+
minimum: 1,
|
|
134
139
|
description: "1-based starting line number for windowed reads (best when examining code around an exact line coordinate from grep or test failures)",
|
|
135
140
|
}),
|
|
136
141
|
),
|
|
137
142
|
limit: Type.Optional(
|
|
138
143
|
Type.Number({
|
|
144
|
+
minimum: 1,
|
|
139
145
|
description: "Maximum number of lines to read starting from 'offset' (default: 250 for unconstrained reads; keep <= 60 for narrow inspection)",
|
|
140
146
|
}),
|
|
141
147
|
),
|
|
142
148
|
anchors: Type.Optional(
|
|
143
149
|
Type.Boolean({
|
|
144
|
-
description: "
|
|
150
|
+
description: "Emit LINE#HASH│ prefixes on narrow ranges (<100 lines) for positional line disambiguation (default: false, plain text)",
|
|
145
151
|
}),
|
|
146
152
|
),
|
|
147
153
|
raw: Type.Optional(
|
|
@@ -170,6 +176,32 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
170
176
|
}
|
|
171
177
|
}
|
|
172
178
|
|
|
179
|
+
// Detect tool confusion (caller passed shell command to read tool)
|
|
180
|
+
if (params && typeof params === "object" && typeof params.command === "string" && params.command.trim().length > 0) {
|
|
181
|
+
if (targetPaths.length > 0) {
|
|
182
|
+
return {
|
|
183
|
+
content: [
|
|
184
|
+
{
|
|
185
|
+
type: "text",
|
|
186
|
+
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'.`,
|
|
187
|
+
},
|
|
188
|
+
],
|
|
189
|
+
details: { error: "ambiguous_parameters", command: params.command.trim(), paths: targetPaths },
|
|
190
|
+
isError: true,
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
return {
|
|
194
|
+
content: [
|
|
195
|
+
{
|
|
196
|
+
type: "text",
|
|
197
|
+
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" }.`,
|
|
198
|
+
},
|
|
199
|
+
],
|
|
200
|
+
details: { error: "tool_confusion_command", command: params.command.trim() },
|
|
201
|
+
isError: true,
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
|
|
173
205
|
if (targetPaths.length === 0) {
|
|
174
206
|
return {
|
|
175
207
|
content: [
|
|
@@ -203,48 +235,101 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
203
235
|
continue;
|
|
204
236
|
}
|
|
205
237
|
try {
|
|
206
|
-
const
|
|
238
|
+
const isSpill = isSpilloverFilePath(resolvedPath, ctx.cwd);
|
|
239
|
+
const isWindowed = params?.offset !== undefined || params?.limit !== undefined;
|
|
240
|
+
const isStreamable = isSpill || isWindowed;
|
|
241
|
+
const readLimitError = validateReadableFile(resolvedPath, isStreamable);
|
|
207
242
|
if (readLimitError) {
|
|
208
243
|
results.push(`=== file: ${relPath} ===\nRead rejected: ${readLimitError}`);
|
|
209
244
|
continue;
|
|
210
245
|
}
|
|
211
|
-
|
|
212
|
-
const
|
|
213
|
-
const
|
|
246
|
+
|
|
247
|
+
const stat = fs.statSync(resolvedPath);
|
|
248
|
+
const needsStreaming = isSpill || stat.size > MAX_READ_FILE_BYTES;
|
|
214
249
|
const fileOffset = params.offset && params.offset > 0 ? params.offset : 1;
|
|
215
250
|
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
251
|
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
252
|
+
let outputLines: string[];
|
|
253
|
+
let totalLines: number;
|
|
254
|
+
let shownCount: number;
|
|
255
|
+
let isTruncated: boolean;
|
|
256
|
+
|
|
257
|
+
if (needsStreaming) {
|
|
258
|
+
const fd = fs.openSync(resolvedPath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
|
|
259
|
+
let streamRes: ReturnType<typeof readStreamLineRangeFromFd>;
|
|
260
|
+
try {
|
|
261
|
+
streamRes = readStreamLineRangeFromFd(fd, {
|
|
262
|
+
offset: fileOffset,
|
|
263
|
+
limit: fileLimit,
|
|
264
|
+
maxBytes: Math.min(MAX_READ_BYTES, Math.max(1024, MAX_BATCH_BYTES - cumulativeBytes)),
|
|
265
|
+
});
|
|
266
|
+
} finally {
|
|
267
|
+
fs.closeSync(fd);
|
|
268
|
+
}
|
|
269
|
+
if (streamRes.isBinary) {
|
|
270
|
+
results.push(`=== file: ${relPath} ===\nRead rejected: Binary file cannot be displayed as text`);
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
outputLines = streamRes.lines;
|
|
274
|
+
totalLines = streamRes.endLine;
|
|
275
|
+
shownCount = streamRes.totalLinesRead;
|
|
276
|
+
isTruncated = streamRes.hasMore || streamRes.startLine > 1;
|
|
277
|
+
if (isTruncated) {
|
|
278
|
+
outputLines.push(`[truncated: ${relPath}, returned lines ${streamRes.startLine}-${streamRes.endLine}. Continue with read(path, offset=${streamRes.endLine + 1})]`);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
globalEpistemicGuard.recordFileRead(
|
|
282
|
+
resolvedPath,
|
|
283
|
+
deps.getSessionId(ctx),
|
|
284
|
+
ctx.cwd,
|
|
285
|
+
streamRes.lines.join("\n"),
|
|
286
|
+
{
|
|
287
|
+
coverage: {
|
|
288
|
+
complete: !streamRes.hasMore && streamRes.startLine === 1,
|
|
289
|
+
ranges: [{ startLine: streamRes.startLine, endLine: streamRes.endLine }],
|
|
290
|
+
totalLines,
|
|
291
|
+
},
|
|
292
|
+
provenance: "read",
|
|
239
293
|
},
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
294
|
+
);
|
|
295
|
+
} else {
|
|
296
|
+
const content = fs.readFileSync(resolvedPath, "utf-8");
|
|
297
|
+
const lines = content.split("\n");
|
|
298
|
+
totalLines = lines.length;
|
|
299
|
+
const startIdx = Math.max(0, fileOffset - 1);
|
|
300
|
+
const endIdx = Math.min(totalLines, startIdx + fileLimit);
|
|
301
|
+
|
|
302
|
+
const numberWidth = String(totalLines).length;
|
|
303
|
+
// Batch reads are always plain text to protect token budgets
|
|
304
|
+
const formatLine = (index: number) => formatReadLine(lines, index, false, numberWidth, benchmarkMethod);
|
|
305
|
+
const visibleIndexes = selectReadLineIndexes(lines, startIdx, endIdx, formatLine);
|
|
306
|
+
outputLines = visibleIndexes.map(formatLine);
|
|
307
|
+
shownCount = visibleIndexes.length;
|
|
308
|
+
isTruncated = (startIdx + visibleIndexes.length) < totalLines || startIdx > 0;
|
|
309
|
+
if (isTruncated) {
|
|
310
|
+
outputLines.push(`[truncated: ${relPath}, returned lines ${startIdx + 1}-${startIdx + visibleIndexes.length} of ${totalLines}. Continue with read(path, offset=${startIdx + visibleIndexes.length + 1})]`);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
globalEpistemicGuard.recordFileRead(
|
|
314
|
+
resolvedPath,
|
|
315
|
+
deps.getSessionId(ctx),
|
|
316
|
+
ctx.cwd,
|
|
317
|
+
content,
|
|
318
|
+
{
|
|
319
|
+
coverage: {
|
|
320
|
+
complete: !isTruncated && startIdx === 0 && endIdx === totalLines,
|
|
321
|
+
ranges: lineRanges(visibleIndexes),
|
|
322
|
+
totalLines,
|
|
323
|
+
},
|
|
324
|
+
provenance: "read",
|
|
325
|
+
},
|
|
326
|
+
);
|
|
327
|
+
}
|
|
243
328
|
|
|
244
329
|
const formattedOutput = `=== file: ${relPath} (${totalLines} lines) ===\n${outputLines.join("\n")}`;
|
|
245
330
|
cumulativeBytes += Buffer.byteLength(formattedOutput, "utf8");
|
|
246
331
|
results.push(formattedOutput);
|
|
247
|
-
detailsList.push({ path: filePath, totalLines, shownLines:
|
|
332
|
+
detailsList.push({ path: filePath, totalLines, shownLines: shownCount, truncated: isTruncated });
|
|
248
333
|
hasAnySuccess = true;
|
|
249
334
|
|
|
250
335
|
if (cumulativeBytes >= MAX_BATCH_BYTES && i < pathsToRead.length - 1) {
|
|
@@ -279,11 +364,14 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
279
364
|
|
|
280
365
|
// Single file read
|
|
281
366
|
try {
|
|
282
|
-
const
|
|
367
|
+
const isSpill = isSpilloverFilePath(resolvedPath, ctx.cwd);
|
|
368
|
+
const isWindowed = params?.offset !== undefined || params?.limit !== undefined;
|
|
369
|
+
const isStreamable = isSpill || isWindowed;
|
|
370
|
+
const readLimitError = validateReadableFile(resolvedPath, isStreamable);
|
|
283
371
|
if (readLimitError) {
|
|
284
372
|
return {
|
|
285
373
|
content: [{ type: "text", text: `[READ ERROR] ${readLimitError}: ${params.path}` }],
|
|
286
|
-
details: { error: "read_limit", maxBytes: MAX_READ_FILE_BYTES },
|
|
374
|
+
details: { error: "read_limit", maxBytes: isStreamable ? MAX_STREAM_FILE_BYTES : MAX_READ_FILE_BYTES },
|
|
287
375
|
isError: true,
|
|
288
376
|
};
|
|
289
377
|
}
|
|
@@ -340,6 +428,127 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
340
428
|
};
|
|
341
429
|
}
|
|
342
430
|
|
|
431
|
+
// Validate pagination parameters explicitly before I/O
|
|
432
|
+
if (
|
|
433
|
+
params.offset !== undefined &&
|
|
434
|
+
(!Number.isFinite(params.offset) || params.offset < 1)
|
|
435
|
+
) {
|
|
436
|
+
return {
|
|
437
|
+
content: [
|
|
438
|
+
{
|
|
439
|
+
type: "text",
|
|
440
|
+
text: `[READ ERROR] Invalid offset=${params.offset}. 'offset' must be a number >= 1 (1-based line number).`,
|
|
441
|
+
},
|
|
442
|
+
],
|
|
443
|
+
details: { offset: params.offset },
|
|
444
|
+
isError: true,
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
if (
|
|
448
|
+
params.limit !== undefined &&
|
|
449
|
+
(!Number.isFinite(params.limit) || params.limit < 1)
|
|
450
|
+
) {
|
|
451
|
+
return {
|
|
452
|
+
content: [
|
|
453
|
+
{
|
|
454
|
+
type: "text",
|
|
455
|
+
text: `[READ ERROR] Invalid limit=${params.limit}. 'limit' must be a number >= 1.`,
|
|
456
|
+
},
|
|
457
|
+
],
|
|
458
|
+
details: { limit: params.limit },
|
|
459
|
+
isError: true,
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
const stat = fs.statSync(resolvedPath);
|
|
464
|
+
const needsStreaming = isSpill || stat.size > MAX_READ_FILE_BYTES;
|
|
465
|
+
|
|
466
|
+
if (needsStreaming) {
|
|
467
|
+
let fd: number;
|
|
468
|
+
try {
|
|
469
|
+
fd = fs.openSync(resolvedPath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
|
|
470
|
+
} catch (openErr: any) {
|
|
471
|
+
return {
|
|
472
|
+
content: [{ type: "text", text: `[READ ERROR] Failed opening ${params.path}: ${openErr?.message || String(openErr)}` }],
|
|
473
|
+
isError: true,
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
let streamRes: ReturnType<typeof readStreamLineRangeFromFd>;
|
|
478
|
+
try {
|
|
479
|
+
const fstat = fs.fstatSync(fd);
|
|
480
|
+
if (!fstat.isFile()) {
|
|
481
|
+
return { content: [{ type: "text", text: `[READ ERROR] Path is not a regular file: ${params.path}` }], isError: true };
|
|
482
|
+
}
|
|
483
|
+
if (fstat.size > MAX_STREAM_FILE_BYTES) {
|
|
484
|
+
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 };
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
const offset = params.offset && params.offset > 0 ? params.offset : 1;
|
|
488
|
+
const limit = params.limit ? Math.min(params.limit, MAX_READ_LINES) : DEFAULT_UNCONSTRAINED_LINES;
|
|
489
|
+
|
|
490
|
+
streamRes = readStreamLineRangeFromFd(fd, { offset, limit, maxBytes: MAX_READ_BYTES });
|
|
491
|
+
} finally {
|
|
492
|
+
fs.closeSync(fd);
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
if (streamRes.isBinary) {
|
|
496
|
+
return {
|
|
497
|
+
content: [{ type: "text", text: `[READ ERROR] Binary file cannot be displayed as text: ${params.path}` }],
|
|
498
|
+
isError: true,
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
const relPath = (path.relative(ctx.cwd, resolvedPath) || params.path).replace(/\\/g, "/");
|
|
503
|
+
const numberWidth = String(streamRes.endLine || 1).length;
|
|
504
|
+
const config = deps.getConfig?.(ctx.cwd);
|
|
505
|
+
const defaultAnchors = config?.editing?.default_anchors ?? true;
|
|
506
|
+
const configuredReadMode = readMode ?? config?.editing?.read_mode ?? "auto";
|
|
507
|
+
const useAnchors = shouldUseAnchors(params, benchmarkMethod, configuredReadMode, defaultAnchors, false);
|
|
508
|
+
|
|
509
|
+
const formattedLines = streamRes.lines.map((line, idx) => {
|
|
510
|
+
const lineNum = streamRes.startLine + idx;
|
|
511
|
+
if (useAnchors) {
|
|
512
|
+
return `${String(lineNum).padStart(numberWidth, " ")}#${computeLineHash(streamRes.lines, idx)}│${line}`;
|
|
513
|
+
}
|
|
514
|
+
if (benchmarkMethod === "line-range" || benchmarkMethod === "adaptive") {
|
|
515
|
+
return `${String(lineNum).padStart(numberWidth, " ")}│${line}`;
|
|
516
|
+
}
|
|
517
|
+
return line;
|
|
518
|
+
});
|
|
519
|
+
|
|
520
|
+
if (streamRes.singleLineTruncated) {
|
|
521
|
+
formattedLines.push("[Line 1 truncated at 50 KB: no newline found in the initial 50 KB of text. File is a single continuous line.]");
|
|
522
|
+
} else if (streamRes.hasMore) {
|
|
523
|
+
formattedLines.push(`[truncated: ${relPath}, returned lines ${streamRes.startLine}-${streamRes.endLine}. Continue with read(path, offset=${streamRes.endLine + 1})]`);
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
globalEpistemicGuard.recordFileRead(
|
|
527
|
+
resolvedPath,
|
|
528
|
+
deps.getSessionId(ctx),
|
|
529
|
+
ctx.cwd,
|
|
530
|
+
streamRes.lines.join("\n"),
|
|
531
|
+
{
|
|
532
|
+
coverage: {
|
|
533
|
+
complete: !streamRes.hasMore && streamRes.startLine === 1,
|
|
534
|
+
ranges: [{ startLine: streamRes.startLine, endLine: streamRes.endLine }],
|
|
535
|
+
},
|
|
536
|
+
provenance: "read",
|
|
537
|
+
},
|
|
538
|
+
);
|
|
539
|
+
|
|
540
|
+
return {
|
|
541
|
+
content: [{ type: "text", text: formattedLines.join("\n") }],
|
|
542
|
+
details: {
|
|
543
|
+
offset: streamRes.startLine,
|
|
544
|
+
limit: streamRes.totalLinesRead,
|
|
545
|
+
hasMore: streamRes.hasMore,
|
|
546
|
+
streamed: true,
|
|
547
|
+
singleLineTruncated: streamRes.singleLineTruncated,
|
|
548
|
+
},
|
|
549
|
+
};
|
|
550
|
+
}
|
|
551
|
+
|
|
343
552
|
const content = fs.readFileSync(resolvedPath, "utf-8");
|
|
344
553
|
const lines = content.split("\n");
|
|
345
554
|
const totalLines = lines.length;
|
|
@@ -505,5 +714,5 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
505
714
|
},
|
|
506
715
|
};
|
|
507
716
|
|
|
508
|
-
pi.registerTool(readToolDefinition);
|
|
717
|
+
pi.registerTool(markReturnedErrors(readToolDefinition));
|
|
509
718
|
}
|
|
@@ -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
|
+
}
|
package/src/ui/tui_utils.ts
CHANGED
|
@@ -245,33 +245,91 @@ export class Text {
|
|
|
245
245
|
}
|
|
246
246
|
}
|
|
247
247
|
|
|
248
|
+
function matchesKittyUnmodified(data: string, codepoints: number[]): boolean {
|
|
249
|
+
const match = /^\x1b\[(\d+)(?::\d+)?(?:;(\d+)(?::(\d+))?)?u$/.exec(data);
|
|
250
|
+
if (!match) return false;
|
|
251
|
+
const cp = Number(match[1]);
|
|
252
|
+
if (!codepoints.includes(cp)) return false;
|
|
253
|
+
const mod = match[2] ? Number(match[2]) : 1;
|
|
254
|
+
const eventType = match[3] ? Number(match[3]) : 1;
|
|
255
|
+
return mod === 1 && eventType !== 3;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function matchesKittyCtrl(data: string, codepoint: number): boolean {
|
|
259
|
+
const match = /^\x1b\[(\d+)(?::\d+)?;(\d+)(?::(\d+))?u$/.exec(data);
|
|
260
|
+
if (!match) return false;
|
|
261
|
+
const cp = Number(match[1]);
|
|
262
|
+
const mod = Number(match[2]);
|
|
263
|
+
const eventType = match[3] ? Number(match[3]) : 1;
|
|
264
|
+
return cp === codepoint && mod === 5 && eventType !== 3;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function matchesModifyOtherKeys(data: string, codepoint: number, modifier = 1): boolean {
|
|
268
|
+
const match = /^\x1b\[27;(\d+);(\d+)~$/.exec(data);
|
|
269
|
+
if (!match) return false;
|
|
270
|
+
return Number(match[1]) === modifier && Number(match[2]) === codepoint;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function matchesArrow(data: string, letter: "A" | "B" | "C" | "D"): boolean {
|
|
274
|
+
if (data === `\x1b[${letter}` || data === `\x1bO${letter}`) return true;
|
|
275
|
+
const match = new RegExp(`^\\x1b\\[1;1(?::([12]))?${letter}$`).exec(data);
|
|
276
|
+
return Boolean(match);
|
|
277
|
+
}
|
|
278
|
+
|
|
248
279
|
export function matchesKey(data: string, key: string): boolean {
|
|
249
280
|
switch (key.toLowerCase()) {
|
|
250
281
|
case "escape":
|
|
251
|
-
return
|
|
282
|
+
return (
|
|
283
|
+
data === "\x1b" ||
|
|
284
|
+
data === "\x1b\x1b" ||
|
|
285
|
+
matchesKittyUnmodified(data, [27]) ||
|
|
286
|
+
matchesModifyOtherKeys(data, 27)
|
|
287
|
+
);
|
|
252
288
|
case "q":
|
|
253
|
-
return data === "q" || data === "Q";
|
|
289
|
+
return data === "q" || data === "Q" || matchesKittyUnmodified(data, [113, 81]);
|
|
254
290
|
case "ctrl+c":
|
|
255
|
-
return
|
|
291
|
+
return (
|
|
292
|
+
data === "\x03" ||
|
|
293
|
+
matchesKittyCtrl(data, 99) ||
|
|
294
|
+
matchesModifyOtherKeys(data, 99, 5)
|
|
295
|
+
);
|
|
256
296
|
case "up":
|
|
257
|
-
return data
|
|
297
|
+
return matchesArrow(data, "A");
|
|
258
298
|
case "down":
|
|
259
|
-
return data
|
|
299
|
+
return matchesArrow(data, "B");
|
|
260
300
|
case "left":
|
|
261
|
-
return data
|
|
301
|
+
return matchesArrow(data, "D");
|
|
262
302
|
case "right":
|
|
263
|
-
return data
|
|
303
|
+
return matchesArrow(data, "C");
|
|
264
304
|
case "k":
|
|
265
|
-
return data === "k" || data === "K";
|
|
305
|
+
return data === "k" || data === "K" || matchesKittyUnmodified(data, [107, 75]);
|
|
266
306
|
case "j":
|
|
267
|
-
return data === "j" || data === "J";
|
|
307
|
+
return data === "j" || data === "J" || matchesKittyUnmodified(data, [106, 74]);
|
|
308
|
+
case "h":
|
|
309
|
+
return data === "h" || data === "H" || matchesKittyUnmodified(data, [104, 72]);
|
|
310
|
+
case "l":
|
|
311
|
+
return data === "l" || data === "L" || matchesKittyUnmodified(data, [108, 76]);
|
|
268
312
|
case "return":
|
|
269
313
|
case "enter":
|
|
270
|
-
return
|
|
314
|
+
return (
|
|
315
|
+
data === "\r" ||
|
|
316
|
+
data === "\n" ||
|
|
317
|
+
data === "\x1bOM" ||
|
|
318
|
+
matchesKittyUnmodified(data, [13, 57414]) ||
|
|
319
|
+
matchesModifyOtherKeys(data, 13)
|
|
320
|
+
);
|
|
271
321
|
case "space":
|
|
272
|
-
return
|
|
322
|
+
return (
|
|
323
|
+
data === " " ||
|
|
324
|
+
matchesKittyUnmodified(data, [32]) ||
|
|
325
|
+
matchesModifyOtherKeys(data, 32)
|
|
326
|
+
);
|
|
273
327
|
case "tab":
|
|
274
|
-
return
|
|
328
|
+
return (
|
|
329
|
+
data === "\t" ||
|
|
330
|
+
matchesKittyUnmodified(data, [9]) ||
|
|
331
|
+
matchesModifyOtherKeys(data, 9)
|
|
332
|
+
);
|
|
275
333
|
default:
|
|
276
334
|
return data === key;
|
|
277
335
|
}
|