@floydous/pi-agent-kernel 0.4.3 → 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.
- package/AGENT_KERNEL_SYS_PROMPT.md +15 -12
- package/CHANGELOG.md +87 -0
- package/README.md +6 -54
- package/config.example.toml +1 -8
- package/docs/README.md +1 -2
- package/docs/architecture.md +2 -3
- package/docs/configuration.md +11 -10
- package/docs/editing-and-verification.md +21 -8
- package/docs/podman-linux-checks.md +24 -0
- package/docs/release-discipline.md +10 -0
- package/docs/retrieval.md +21 -23
- package/docs/testing.md +3 -3
- package/grammars/tree-sitter-html.wasm +0 -0
- package/package.json +5 -3
- package/src/config/agent_kernel_command.ts +60 -625
- package/src/config/kernel_config.ts +53 -69
- package/src/config/toml.ts +6 -1
- package/src/editing/auto_heal.ts +1 -1
- package/src/editing/patch.ts +75 -37
- package/src/editing/post_edit_verification.ts +20 -14
- package/src/editing/smart_anchor.ts +9 -6
- package/src/editing/syntax-verify.ts +79 -222
- package/src/index.ts +36 -453
- package/src/retrieval/html_chunker.ts +526 -0
- package/src/retrieval/search_bm25.ts +39 -28
- package/src/retrieval/search_chunker.ts +69 -7
- package/src/retrieval/search_config.ts +21 -40
- package/src/retrieval/search_embedder.ts +14 -31
- package/src/retrieval/search_index.ts +338 -129
- package/src/retrieval/search_modal.ts +1208 -222
- package/src/retrieval/{repomap.ts → tag_extractor.ts} +6 -293
- package/src/retrieval/tree_sitter_engine.ts +171 -36
- package/src/retrieval/workspace_walker.ts +78 -2
- package/src/safety/atomic_write.ts +1 -1
- package/src/safety/epistemic_guard.ts +105 -31
- package/src/safety/host_environment.ts +180 -0
- package/src/safety/output_clamper.ts +97 -27
- package/src/tools/code_search_output.ts +11 -2
- package/src/tools/code_search_tool.ts +25 -13
- package/src/tools/context.ts +11 -10
- package/src/tools/edit_tool.ts +243 -154
- package/src/tools/read_tool.ts +285 -214
- package/src/tools/stream_reader.ts +206 -0
- package/src/ui/footer.ts +7 -7
- package/docs/lsp.md +0 -31
- package/src/lsp/adapters/base.ts +0 -42
- package/src/lsp/adapters/index.ts +0 -21
- package/src/lsp/adapters/python.ts +0 -37
- package/src/lsp/adapters/rust.ts +0 -35
- package/src/lsp/adapters/typescript.ts +0 -40
- package/src/lsp/index.ts +0 -13
- package/src/lsp/lsp_client.ts +0 -765
- package/src/lsp/lsp_detector.ts +0 -52
- package/src/lsp/lsp_formatter.ts +0 -323
- package/src/lsp/lsp_installer.ts +0 -320
- package/src/lsp/lsp_manager.ts +0 -202
- package/src/lsp/lsp_modal.ts +0 -675
- package/src/lsp/lsp_registry.ts +0 -600
- package/src/lsp/lsp_types.ts +0 -143
- package/src/retrieval/ast_search.ts +0 -999
- package/src/retrieval/symbol_reader.ts +0 -228
- package/src/tools/ast_search_formatter.ts +0 -161
- package/src/tools/ast_search_tool.ts +0 -146
- package/src/tools/lsp_tool.ts +0 -794
- package/src/tools/repo_map_tool.ts +0 -56
package/src/tools/read_tool.ts
CHANGED
|
@@ -3,30 +3,28 @@ import { Type } from "typebox";
|
|
|
3
3
|
import { Text, makeOutputText } from "../ui/tui_utils";
|
|
4
4
|
import * as path from "node:path";
|
|
5
5
|
import * as fs from "node:fs";
|
|
6
|
-
import {
|
|
7
|
-
import { findSymbolSuggestions } from "../retrieval/ast_search";
|
|
8
|
-
import { computeLineHash, formatSmartAnchorLines } from "../editing/smart_anchor";
|
|
6
|
+
import { computeLineHash } from "../editing/smart_anchor";
|
|
9
7
|
import {
|
|
10
8
|
globalEpistemicGuard,
|
|
11
9
|
resolveUserPath,
|
|
12
10
|
} from "../safety/epistemic_guard";
|
|
13
|
-
import {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
return fs.readFileSync(filePath, "utf8").split("\n").length;
|
|
17
|
-
}
|
|
11
|
+
import { markReturnedErrors, type SessionDeps } from "./context";
|
|
12
|
+
import { isSpilloverFilePath, DEFAULT_SPILL_BYTES } from "../safety/output_clamper";
|
|
13
|
+
import { readStreamLineRangeFromFd } from "./stream_reader";
|
|
18
14
|
|
|
19
15
|
const MAX_READ_LINES = 2_000;
|
|
20
16
|
const MAX_READ_BYTES = 50 * 1024;
|
|
21
17
|
const MAX_READ_FILE_BYTES = 5 * 1024 * 1024;
|
|
18
|
+
const MAX_STREAM_FILE_BYTES = DEFAULT_SPILL_BYTES;
|
|
22
19
|
const DEFAULT_UNCONSTRAINED_LINES = 250;
|
|
23
20
|
|
|
24
|
-
function validateReadableFile(filePath: string): string | null {
|
|
21
|
+
function validateReadableFile(filePath: string, isStreamable = false): string | null {
|
|
25
22
|
try {
|
|
26
23
|
const stat = fs.statSync(filePath);
|
|
27
24
|
if (!stat.isFile()) return "Path is not a regular file";
|
|
28
|
-
|
|
29
|
-
|
|
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`;
|
|
30
28
|
}
|
|
31
29
|
return null;
|
|
32
30
|
} catch (error: any) {
|
|
@@ -58,7 +56,7 @@ function formatReadLine(
|
|
|
58
56
|
numberWidth: number,
|
|
59
57
|
benchmarkMethod: string | undefined,
|
|
60
58
|
): string {
|
|
61
|
-
const line = lines[index]
|
|
59
|
+
const line = lines[index] ?? "";
|
|
62
60
|
if (useAnchors) {
|
|
63
61
|
return `${String(index + 1).padStart(numberWidth, " ")}#${computeLineHash(lines, index)}│${line}`;
|
|
64
62
|
}
|
|
@@ -69,7 +67,7 @@ function formatReadLine(
|
|
|
69
67
|
}
|
|
70
68
|
|
|
71
69
|
function selectReadLineIndexes(
|
|
72
|
-
|
|
70
|
+
_lines: readonly string[],
|
|
73
71
|
startIdx: number,
|
|
74
72
|
endIdx: number,
|
|
75
73
|
formatLine: (index: number) => string,
|
|
@@ -99,52 +97,50 @@ function lineRanges(indexes: readonly number[]): Array<{ startLine: number; endL
|
|
|
99
97
|
|
|
100
98
|
/** Extracted from index.ts — registers the `read` tool. */
|
|
101
99
|
export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
102
|
-
// 6. Tool: `read` (
|
|
100
|
+
// 6. Tool: `read` (Bounded File Reader with Line-Windowing - Replaces stock read tool)
|
|
103
101
|
const editMethod = process.env.PI_EDIT_METHOD?.toLowerCase();
|
|
104
102
|
const benchmarkMethod = ["line-range", "search-replace", "hash-anchor", "adaptive"].includes(editMethod || "") ? editMethod : undefined;
|
|
105
103
|
const readMode = process.env.PI_READ_MODE?.toLowerCase();
|
|
104
|
+
let readToolDescription =
|
|
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.";
|
|
106
|
+
switch (benchmarkMethod) {
|
|
107
|
+
case "line-range":
|
|
108
|
+
readToolDescription = "Read source with line numbers for numeric line-range edits.";
|
|
109
|
+
break;
|
|
110
|
+
case "search-replace":
|
|
111
|
+
readToolDescription = "Read source text for exact search/replace edits.";
|
|
112
|
+
break;
|
|
113
|
+
case "adaptive":
|
|
114
|
+
readToolDescription = "Read source with line numbers. Prefer unique search/replace; use line ranges when needed.";
|
|
115
|
+
break;
|
|
116
|
+
default:
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
106
119
|
const readToolDefinition: any = {
|
|
107
120
|
name: "read",
|
|
108
|
-
label: "Read File
|
|
109
|
-
description:
|
|
110
|
-
|
|
111
|
-
? "Read source with line numbers for numeric line-range edits."
|
|
112
|
-
: benchmarkMethod === "search-replace"
|
|
113
|
-
? "Read source text for exact search/replace edits."
|
|
114
|
-
: benchmarkMethod === "adaptive"
|
|
115
|
-
? "Read source with line numbers. Prefer unique search/replace; use line ranges when needed."
|
|
116
|
-
: "Read file contents (plain text), extract a symbol via 'symbol', or read multiple files via 'paths'. Bounded at 2,000 lines or 50KB. Use 'offset'/'limit' for ranges.",
|
|
117
|
-
promptSnippet: "Read file contents, inspect line ranges, extract symbols, or read multiple files via 'paths'",
|
|
121
|
+
label: "Read File",
|
|
122
|
+
description: readToolDescription,
|
|
123
|
+
promptSnippet: "Read file contents, inspect line ranges, or read multiple files via 'paths'",
|
|
118
124
|
renderShell: "default",
|
|
119
125
|
parameters: Type.Object({
|
|
120
126
|
path: Type.Optional(
|
|
121
127
|
Type.String({
|
|
122
|
-
description: "
|
|
128
|
+
description: "Workspace-relative or absolute file path to inspect. For multiple files, use 'paths'",
|
|
123
129
|
}),
|
|
124
130
|
),
|
|
125
131
|
paths: Type.Optional(
|
|
126
132
|
Type.Array(Type.String(), {
|
|
127
|
-
description: "
|
|
128
|
-
}),
|
|
129
|
-
),
|
|
130
|
-
symbol: Type.Optional(
|
|
131
|
-
Type.String({
|
|
132
|
-
description: "Function, class, or type to extract",
|
|
133
|
+
description: "Array of file paths to read in a single batch (plain text only, bounded per file)",
|
|
133
134
|
}),
|
|
134
135
|
),
|
|
135
136
|
offset: Type.Optional(
|
|
136
137
|
Type.Number({
|
|
137
|
-
description: "
|
|
138
|
+
description: "1-based starting line number for windowed reads (best when examining code around an exact line coordinate from grep or test failures)",
|
|
138
139
|
}),
|
|
139
140
|
),
|
|
140
141
|
limit: Type.Optional(
|
|
141
142
|
Type.Number({
|
|
142
|
-
description: "Maximum lines to read",
|
|
143
|
-
}),
|
|
144
|
-
),
|
|
145
|
-
surrounding_lines: Type.Optional(
|
|
146
|
-
Type.Number({
|
|
147
|
-
description: "Extra surrounding context lines for symbol",
|
|
143
|
+
description: "Maximum number of lines to read starting from 'offset' (default: 250 for unconstrained reads; keep <= 60 for narrow inspection)",
|
|
148
144
|
}),
|
|
149
145
|
),
|
|
150
146
|
anchors: Type.Optional(
|
|
@@ -162,9 +158,9 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
162
158
|
_toolCallId: string,
|
|
163
159
|
params: any,
|
|
164
160
|
_signal: any,
|
|
165
|
-
|
|
161
|
+
_onUpdate: any,
|
|
166
162
|
ctx: any,
|
|
167
|
-
)
|
|
163
|
+
) {
|
|
168
164
|
let targetPaths: string[] = [];
|
|
169
165
|
if (params && typeof params === "object") {
|
|
170
166
|
if (Array.isArray(params.paths)) {
|
|
@@ -178,6 +174,32 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
178
174
|
}
|
|
179
175
|
}
|
|
180
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
|
+
|
|
181
203
|
if (targetPaths.length === 0) {
|
|
182
204
|
return {
|
|
183
205
|
content: [
|
|
@@ -211,48 +233,101 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
211
233
|
continue;
|
|
212
234
|
}
|
|
213
235
|
try {
|
|
214
|
-
const
|
|
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);
|
|
215
240
|
if (readLimitError) {
|
|
216
241
|
results.push(`=== file: ${relPath} ===\nRead rejected: ${readLimitError}`);
|
|
217
242
|
continue;
|
|
218
243
|
}
|
|
219
|
-
|
|
220
|
-
const
|
|
221
|
-
const
|
|
244
|
+
|
|
245
|
+
const stat = fs.statSync(resolvedPath);
|
|
246
|
+
const needsStreaming = isSpill || stat.size > MAX_READ_FILE_BYTES;
|
|
222
247
|
const fileOffset = params.offset && params.offset > 0 ? params.offset : 1;
|
|
223
248
|
const fileLimit = params.limit ? Math.min(params.limit, MAX_BATCH_FILE_LINES) : MAX_BATCH_FILE_LINES;
|
|
224
|
-
const startIdx = Math.max(0, fileOffset - 1);
|
|
225
|
-
const endIdx = Math.min(totalLines, startIdx + fileLimit);
|
|
226
|
-
|
|
227
|
-
const numberWidth = String(totalLines).length;
|
|
228
|
-
// Batch reads are always plain text to protect token budgets
|
|
229
|
-
const formatLine = (index: number) => formatReadLine(lines, index, false, numberWidth, benchmarkMethod);
|
|
230
|
-
const visibleIndexes = selectReadLineIndexes(lines, startIdx, endIdx, formatLine);
|
|
231
|
-
const outputLines = visibleIndexes.map(formatLine);
|
|
232
|
-
const isTruncated = (startIdx + visibleIndexes.length) < totalLines || startIdx > 0;
|
|
233
|
-
if (isTruncated) {
|
|
234
|
-
outputLines.push(`[truncated: ${relPath}, returned lines ${startIdx + 1}-${startIdx + visibleIndexes.length} of ${totalLines}. Continue with read(path, offset=${startIdx + visibleIndexes.length + 1})]`);
|
|
235
|
-
}
|
|
236
249
|
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
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",
|
|
247
291
|
},
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
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
|
+
}
|
|
251
326
|
|
|
252
327
|
const formattedOutput = `=== file: ${relPath} (${totalLines} lines) ===\n${outputLines.join("\n")}`;
|
|
253
328
|
cumulativeBytes += Buffer.byteLength(formattedOutput, "utf8");
|
|
254
329
|
results.push(formattedOutput);
|
|
255
|
-
detailsList.push({ path: filePath, totalLines, shownLines:
|
|
330
|
+
detailsList.push({ path: filePath, totalLines, shownLines: shownCount, truncated: isTruncated });
|
|
256
331
|
hasAnySuccess = true;
|
|
257
332
|
|
|
258
333
|
if (cumulativeBytes >= MAX_BATCH_BYTES && i < pathsToRead.length - 1) {
|
|
@@ -285,142 +360,16 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
285
360
|
};
|
|
286
361
|
}
|
|
287
362
|
|
|
288
|
-
|
|
289
|
-
if (readLimitError) {
|
|
290
|
-
return {
|
|
291
|
-
content: [{ type: "text", text: `[READ ERROR] ${readLimitError}: ${params.path}` }],
|
|
292
|
-
details: { error: "read_limit", maxBytes: MAX_READ_FILE_BYTES },
|
|
293
|
-
isError: true,
|
|
294
|
-
};
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
// Mode 1: Targeted AST symbol extraction
|
|
298
|
-
if (params.symbol && params.symbol.trim()) {
|
|
299
|
-
const sym = params.symbol.trim();
|
|
300
|
-
onUpdate?.({
|
|
301
|
-
content: [
|
|
302
|
-
{
|
|
303
|
-
type: "text",
|
|
304
|
-
text: `Extracting symbol '${sym}' from ${params.path}...`,
|
|
305
|
-
},
|
|
306
|
-
],
|
|
307
|
-
});
|
|
308
|
-
let symbolSnapshot: string;
|
|
309
|
-
try {
|
|
310
|
-
symbolSnapshot = fs.readFileSync(resolvedPath, "utf8");
|
|
311
|
-
} catch (error: any) {
|
|
312
|
-
return {
|
|
313
|
-
content: [
|
|
314
|
-
{ type: "text", text: `[READ ERROR] Unable to read ${params.path}: ${error.message}` },
|
|
315
|
-
],
|
|
316
|
-
isError: true,
|
|
317
|
-
};
|
|
318
|
-
}
|
|
319
|
-
const res = extractSymbolContent(
|
|
320
|
-
resolvedPath,
|
|
321
|
-
sym,
|
|
322
|
-
{ surroundingLines: params.surrounding_lines },
|
|
323
|
-
symbolSnapshot,
|
|
324
|
-
);
|
|
325
|
-
|
|
326
|
-
if (!res.found) {
|
|
327
|
-
const suggestions = findSymbolSuggestions(
|
|
328
|
-
ctx.cwd,
|
|
329
|
-
resolvedPath,
|
|
330
|
-
sym,
|
|
331
|
-
);
|
|
332
|
-
let errorText: string;
|
|
333
|
-
if (res.error) {
|
|
334
|
-
errorText = res.error;
|
|
335
|
-
} else if (suggestions.length > 0) {
|
|
336
|
-
const formattedSuggestions = suggestions
|
|
337
|
-
.map(
|
|
338
|
-
(s) =>
|
|
339
|
-
`- ${s.name} (${s.filePath}:${s.line}) [${s.kind}] ${s.signature}`,
|
|
340
|
-
)
|
|
341
|
-
.join("\n");
|
|
342
|
-
errorText = `Symbol '${sym}' not found in ${params.path}.\nDid you mean:\n${formattedSuggestions}`;
|
|
343
|
-
} else {
|
|
344
|
-
errorText = `Symbol '${sym}' not found in ${params.path}. ` +
|
|
345
|
-
(speculativeToolsEnabled(deps.getConfig, ctx.cwd)
|
|
346
|
-
? `Use 'ast_search' to locate symbols or 'rg' in bash to search text.`
|
|
347
|
-
: `Use 'code_search' to locate code or 'rg' in bash to search text.`);
|
|
348
|
-
}
|
|
349
|
-
return {
|
|
350
|
-
content: [{ type: "text", text: errorText }],
|
|
351
|
-
details: {
|
|
352
|
-
error: "symbol_not_found",
|
|
353
|
-
query: sym,
|
|
354
|
-
candidates: suggestions.map((s) => ({
|
|
355
|
-
name: s.name,
|
|
356
|
-
filePath: s.filePath,
|
|
357
|
-
line: s.line,
|
|
358
|
-
kind: s.kind,
|
|
359
|
-
})),
|
|
360
|
-
},
|
|
361
|
-
isError: true,
|
|
362
|
-
};
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
// Record the exact snapshot used for extraction only after a successful
|
|
366
|
-
// symbol result; failed extraction must not authorize a mutation.
|
|
367
|
-
globalEpistemicGuard.recordFileRead(
|
|
368
|
-
resolvedPath,
|
|
369
|
-
deps.getSessionId(ctx),
|
|
370
|
-
ctx.cwd,
|
|
371
|
-
symbolSnapshot,
|
|
372
|
-
{
|
|
373
|
-
coverage: {
|
|
374
|
-
complete: false,
|
|
375
|
-
ranges: res.symbols.map((symbol) => ({
|
|
376
|
-
startLine: symbol.startLine,
|
|
377
|
-
endLine: symbol.endLine,
|
|
378
|
-
})),
|
|
379
|
-
totalLines: countFileLines(resolvedPath),
|
|
380
|
-
},
|
|
381
|
-
provenance: "symbol",
|
|
382
|
-
query: sym,
|
|
383
|
-
},
|
|
384
|
-
);
|
|
385
|
-
|
|
386
|
-
const config = deps.getConfig?.(ctx.cwd);
|
|
387
|
-
const defaultAnchors = config?.editing?.default_anchors ?? true;
|
|
388
|
-
const configuredReadMode = readMode ?? config?.editing?.read_mode ?? "auto";
|
|
389
|
-
const useAnchors = shouldUseAnchors(params, benchmarkMethod, configuredReadMode, defaultAnchors, true);
|
|
390
|
-
|
|
391
|
-
const allFileLines = symbolSnapshot.split("\n");
|
|
392
|
-
const formatted = res.symbols
|
|
393
|
-
.map((s) => {
|
|
394
|
-
const header = `// ${(path.relative(ctx.cwd, s.filePath) || s.filePath).replace(/\\/g, "/")}:${s.startLine}-${s.endLine} [${s.kind}] ${s.name}`;
|
|
395
|
-
const body = useAnchors
|
|
396
|
-
? formatSmartAnchorLines(allFileLines, s.startLine, s.endLine)
|
|
397
|
-
: benchmarkMethod === "line-range"
|
|
398
|
-
? allFileLines.slice(s.startLine - 1, s.endLine).map((line, index) => `${String(s.startLine + index).padStart(String(s.endLine).length, " ")}│${line}`).join("\n")
|
|
399
|
-
: s.content;
|
|
400
|
-
return `${header}\n${body}`;
|
|
401
|
-
})
|
|
402
|
-
.join("\n\n");
|
|
403
|
-
|
|
404
|
-
return {
|
|
405
|
-
content: [{ type: "text", text: formatted }],
|
|
406
|
-
details: {
|
|
407
|
-
count: res.symbols.length,
|
|
408
|
-
symbols: res.symbols.map((s) => ({
|
|
409
|
-
name: s.name,
|
|
410
|
-
kind: s.kind,
|
|
411
|
-
lines: `${s.startLine}-${s.endLine}`,
|
|
412
|
-
})),
|
|
413
|
-
},
|
|
414
|
-
};
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
// Mode 2: Standard file reading
|
|
363
|
+
// Single file read
|
|
418
364
|
try {
|
|
419
|
-
const
|
|
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);
|
|
420
369
|
if (readLimitError) {
|
|
421
370
|
return {
|
|
422
371
|
content: [{ type: "text", text: `[READ ERROR] ${readLimitError}: ${params.path}` }],
|
|
423
|
-
details: { error: "read_limit", maxBytes: MAX_READ_FILE_BYTES },
|
|
372
|
+
details: { error: "read_limit", maxBytes: isStreamable ? MAX_STREAM_FILE_BYTES : MAX_READ_FILE_BYTES },
|
|
424
373
|
isError: true,
|
|
425
374
|
};
|
|
426
375
|
}
|
|
@@ -477,6 +426,127 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
477
426
|
};
|
|
478
427
|
}
|
|
479
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
|
+
|
|
480
550
|
const content = fs.readFileSync(resolvedPath, "utf-8");
|
|
481
551
|
const lines = content.split("\n");
|
|
482
552
|
const totalLines = lines.length;
|
|
@@ -568,8 +638,11 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
568
638
|
}
|
|
569
639
|
const isTruncated = oversizedFirstLine || hasMore || startIdx > 0;
|
|
570
640
|
if (isTruncated && hasMore && !oversizedFirstLine && hiddenLines === 0) {
|
|
571
|
-
const
|
|
572
|
-
|
|
641
|
+
const lastIdx = visibleIndexes[visibleIndexes.length - 1];
|
|
642
|
+
if (lastIdx !== undefined) {
|
|
643
|
+
const lastShown = lastIdx + 1;
|
|
644
|
+
outputLines.push(`\n[Showing ${visibleIndexes.length} of ${totalLines} lines. Use offset=${lastShown + 1} to continue.]`);
|
|
645
|
+
}
|
|
573
646
|
}
|
|
574
647
|
const coverageRanges = lineRanges(visibleIndexes);
|
|
575
648
|
|
|
@@ -609,19 +682,17 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
609
682
|
`${theme.fg("toolTitle", theme.bold("read"))} [${theme.fg("accent", pathsSummary)}]`,
|
|
610
683
|
);
|
|
611
684
|
}
|
|
612
|
-
const
|
|
685
|
+
const path0 = Array.isArray(args?.paths) ? args.paths[0] : "";
|
|
686
|
+
const rawPath = args?.path || path0 || "";
|
|
613
687
|
const relPath = rawPath
|
|
614
688
|
? (path.relative(context.cwd, rawPath) || rawPath).replace(/\\/g, "/")
|
|
615
689
|
: "";
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
690
|
+
let range = "";
|
|
691
|
+
if (args?.offset || args?.limit) {
|
|
692
|
+
const off = args.offset ?? 1;
|
|
693
|
+
const lim = args.limit ? `-${off + args.limit - 1}` : "";
|
|
694
|
+
range = `:${off}${lim}`;
|
|
620
695
|
}
|
|
621
|
-
const range =
|
|
622
|
-
args?.offset || args?.limit
|
|
623
|
-
? `:${args.offset ?? 1}${args.limit ? `-${(args.offset ?? 1) + args.limit - 1}` : ""}`
|
|
624
|
-
: "";
|
|
625
696
|
return makeOutputText(
|
|
626
697
|
`${theme.fg("toolTitle", theme.bold("read"))} ${theme.fg("accent", relPath)}${theme.fg("warning", range)}`,
|
|
627
698
|
);
|
|
@@ -641,5 +712,5 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
|
|
|
641
712
|
},
|
|
642
713
|
};
|
|
643
714
|
|
|
644
|
-
pi.registerTool(readToolDefinition);
|
|
715
|
+
pi.registerTool(markReturnedErrors(readToolDefinition));
|
|
645
716
|
}
|