@floydous/pi-agent-kernel 0.3.2 → 0.3.31

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.
@@ -97,17 +97,24 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
97
97
  : benchmarkMethod === "search-replace"
98
98
  ? "Read source text for exact search/replace edits."
99
99
  : benchmarkMethod === "adaptive"
100
- ? "Read bounded source with plain line numbers. Prefer unique search/replace; use numeric ranges when needed; request anchors only for uncertain targets."
101
- : "Read file contents (clean plain text by default) or extract a specific symbol via 'symbol'. Broad reads capped at 2,000 lines or 50KB. Use 'offset' and 'limit' to inspect specific line ranges.",
102
- promptSnippet: "Read file contents (clean plain text), inspect line ranges via offset/limit, or extract AST symbols via 'symbol'",
100
+ ? "Read source with line numbers. Prefer unique search/replace; use line ranges when needed."
101
+ : "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.",
102
+ promptSnippet: "Read file contents, inspect line ranges, extract symbols, or read multiple files via 'paths'",
103
103
  renderShell: "default",
104
104
  parameters: Type.Object({
105
- path: Type.String({
106
- description: "File path (relative or absolute)",
107
- }),
105
+ path: Type.Optional(
106
+ Type.String({
107
+ description: "File path (relative or absolute). For multiple files, use 'paths'",
108
+ }),
109
+ ),
110
+ paths: Type.Optional(
111
+ Type.Array(Type.String(), {
112
+ description: "Read multiple files in one turn",
113
+ }),
114
+ ),
108
115
  symbol: Type.Optional(
109
116
  Type.String({
110
- description: "Top-level function, class, or type name to extract (omit for plain files or object keys)",
117
+ description: "Function, class, or type to extract",
111
118
  }),
112
119
  ),
113
120
  offset: Type.Optional(
@@ -122,17 +129,17 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
122
129
  ),
123
130
  surrounding_lines: Type.Optional(
124
131
  Type.Number({
125
- description: "Extra surrounding context lines for symbol (default: 0)",
132
+ description: "Extra surrounding context lines for symbol",
126
133
  }),
127
134
  ),
128
135
  anchors: Type.Optional(
129
136
  Type.Boolean({
130
- description: "Optional: format lines with LINE#HASH│ anchors (default: false, plain text)",
137
+ description: "Narrow ranges (<100 lines) with LINE#HASH│ anchors (default: false, plain text)",
131
138
  }),
132
139
  ),
133
140
  raw: Type.Optional(
134
141
  Type.Boolean({
135
- description: "Output clean raw text without line numbers or anchors",
142
+ description: "Clean raw text without line numbers or anchors",
136
143
  }),
137
144
  ),
138
145
  }),
@@ -143,15 +150,113 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
143
150
  onUpdate: any,
144
151
  ctx: any,
145
152
  ): Promise<any> {
146
- if (!params || typeof params !== "object" || !params.path) {
153
+ let targetPaths: string[] = [];
154
+ if (params && typeof params === "object") {
155
+ if (Array.isArray(params.paths)) {
156
+ targetPaths = params.paths.filter((p: any) => typeof p === "string" && p.trim().length > 0);
157
+ } else if (typeof params.paths === "string" && params.paths.trim().length > 0) {
158
+ targetPaths = [params.paths.trim()];
159
+ } else if (Array.isArray(params.path)) {
160
+ targetPaths = params.path.filter((p: any) => typeof p === "string" && p.trim().length > 0);
161
+ } else if (typeof params.path === "string" && params.path.trim().length > 0) {
162
+ targetPaths = [params.path.trim()];
163
+ }
164
+ }
165
+
166
+ if (targetPaths.length === 0) {
147
167
  return {
148
168
  content: [
149
- { type: "text", text: "[READ ERROR] Missing required 'path' parameter." },
169
+ { type: "text", text: "[READ ERROR] Missing required 'path' or 'paths' parameter." },
150
170
  ],
151
171
  isError: true,
152
172
  };
153
173
  }
154
174
 
175
+ // Batch mode: multiple files in one turn
176
+ if (targetPaths.length > 1) {
177
+ const MAX_BATCH_PATHS = 20;
178
+ const MAX_BATCH_BYTES = 24 * 1024; // 24KB aggregate ceiling across batch
179
+ const MAX_BATCH_FILE_LINES = 150; // max 150 lines per file in batch mode
180
+ const pathsToRead = targetPaths.slice(0, MAX_BATCH_PATHS);
181
+ const results: string[] = [];
182
+ const detailsList: any[] = [];
183
+ let hasAnySuccess = false;
184
+ let cumulativeBytes = 0;
185
+
186
+ for (let i = 0; i < pathsToRead.length; i++) {
187
+ const filePath = pathsToRead[i];
188
+ if (cumulativeBytes >= MAX_BATCH_BYTES) {
189
+ results.push(`[...] Remaining ${pathsToRead.length - i} file(s) skipped: batch byte limit reached (24KB) [...]`);
190
+ break;
191
+ }
192
+ const resolvedPath = resolveUserPath(filePath, ctx.cwd);
193
+ const relPath = path.relative(ctx.cwd, resolvedPath) || filePath;
194
+ if (!fs.existsSync(resolvedPath)) {
195
+ results.push(`=== file: ${relPath} ===\nFile not found: ${filePath}`);
196
+ continue;
197
+ }
198
+ try {
199
+ const content = fs.readFileSync(resolvedPath, "utf-8");
200
+ const lines = content.split("\n");
201
+ const totalLines = lines.length;
202
+ const fileOffset = params.offset && params.offset > 0 ? params.offset : 1;
203
+ const fileLimit = params.limit ? Math.min(params.limit, MAX_BATCH_FILE_LINES) : MAX_BATCH_FILE_LINES;
204
+ const startIdx = Math.max(0, fileOffset - 1);
205
+ const endIdx = Math.min(totalLines, startIdx + fileLimit);
206
+
207
+ const numberWidth = String(totalLines).length;
208
+ // Batch reads are always plain text to protect token budgets
209
+ const formatLine = (index: number) => formatReadLine(lines, index, false, numberWidth, benchmarkMethod);
210
+ const visibleIndexes = selectReadLineIndexes(lines, startIdx, endIdx, formatLine);
211
+ const outputLines = visibleIndexes.map(formatLine);
212
+ const isTruncated = (startIdx + visibleIndexes.length) < totalLines || startIdx > 0;
213
+ if (isTruncated) {
214
+ outputLines.push(`[truncated: ${relPath}, returned lines ${startIdx + 1}-${startIdx + visibleIndexes.length} of ${totalLines}. Continue with read(path, offset=${startIdx + visibleIndexes.length + 1})]`);
215
+ }
216
+
217
+ globalEpistemicGuard.recordFileRead(
218
+ resolvedPath,
219
+ deps.getSessionId(ctx),
220
+ ctx.cwd,
221
+ content,
222
+ {
223
+ coverage: {
224
+ complete: !isTruncated,
225
+ ranges: lineRanges(visibleIndexes),
226
+ totalLines,
227
+ },
228
+ provenance: "read",
229
+ },
230
+ );
231
+
232
+ const formattedOutput = `=== file: ${relPath} (${totalLines} lines) ===\n${outputLines.join("\n")}`;
233
+ cumulativeBytes += Buffer.byteLength(formattedOutput, "utf8");
234
+ results.push(formattedOutput);
235
+ detailsList.push({ path: filePath, totalLines, shownLines: visibleIndexes.length, truncated: isTruncated });
236
+ hasAnySuccess = true;
237
+
238
+ if (cumulativeBytes >= MAX_BATCH_BYTES && i < pathsToRead.length - 1) {
239
+ results.push(`[...] Remaining ${pathsToRead.length - 1 - i} file(s) skipped: batch byte limit reached (24KB) [...]`);
240
+ break;
241
+ }
242
+ } catch (err: any) {
243
+ results.push(`=== file: ${relPath} ===\nError reading file: ${err.message}`);
244
+ }
245
+ }
246
+
247
+ if (targetPaths.length > MAX_BATCH_PATHS) {
248
+ results.push(`[...] Note: Truncated to first ${MAX_BATCH_PATHS} files (${targetPaths.length - MAX_BATCH_PATHS} omitted).`);
249
+ }
250
+
251
+ return {
252
+ content: [{ type: "text", text: results.join("\n\n") }],
253
+ details: { batch: true, count: pathsToRead.length, files: detailsList },
254
+ isError: !hasAnySuccess,
255
+ };
256
+ }
257
+
258
+ // Single file read
259
+ params.path = targetPaths[0];
155
260
  const resolvedPath = resolveUserPath(params.path, ctx.cwd);
156
261
  if (!fs.existsSync(resolvedPath)) {
157
262
  return {
@@ -389,11 +494,21 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
389
494
  isError: true,
390
495
  };
391
496
  }
392
- const endIdx = Math.min(totalLines, startIdx + limit);
393
497
  const config = deps.getConfig?.(ctx.cwd);
394
498
  const defaultAnchors = config?.editing?.default_anchors ?? true;
395
499
  const configuredReadMode = readMode ?? config?.editing?.read_mode ?? "auto";
396
500
  const useAnchors = shouldUseAnchors(params, benchmarkMethod, configuredReadMode, defaultAnchors, false);
501
+
502
+ // Guardrail against excessive anchored line bloat
503
+ const MAX_ANCHOR_LINES = 100;
504
+ let effectiveLimit = limit;
505
+ let anchorNotice = "";
506
+ if (useAnchors && effectiveLimit > MAX_ANCHOR_LINES) {
507
+ effectiveLimit = MAX_ANCHOR_LINES;
508
+ anchorNotice = `\n[Notice: Anchored read capped to 100 lines to prevent token bloat. For broader inspection, use plain read without 'anchors'.]`;
509
+ }
510
+ const endIdx = Math.min(totalLines, startIdx + effectiveLimit);
511
+
397
512
  const numberWidth = String(totalLines).length;
398
513
  const formatLine = (index: number) => formatReadLine(lines, index, useAnchors, numberWidth, benchmarkMethod);
399
514
  const firstLineBytes = Buffer.byteLength(formatLine(startIdx), "utf8");
@@ -407,6 +522,9 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
407
522
  if (hiddenLines > 0 && !oversizedFirstLine) {
408
523
  outputLines.push(`[...] ${hiddenLines} lines omitted [...]. Use offset=${startIdx + visibleIndexes.length + 1} to continue.`);
409
524
  }
525
+ if (anchorNotice) {
526
+ outputLines.push(anchorNotice);
527
+ }
410
528
  const isTruncated = oversizedFirstLine || hasMore || startIdx > 0;
411
529
  if (isTruncated && hasMore && !oversizedFirstLine && hiddenLines === 0) {
412
530
  const lastShown = visibleIndexes[visibleIndexes.length - 1]! + 1;
@@ -443,7 +561,14 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
443
561
  }
444
562
  },
445
563
  renderCall(args: any, theme: any, context: any) {
446
- const rawPath = args?.path || "";
564
+ const targetPaths = Array.isArray(args?.paths) ? args.paths : (Array.isArray(args?.path) ? args.path : []);
565
+ if (targetPaths.length > 1) {
566
+ const pathsSummary = targetPaths.map((p: string) => path.relative(context.cwd, p) || p).join(", ");
567
+ return makeOutputText(
568
+ `${theme.fg("toolTitle", theme.bold("read"))} [${theme.fg("accent", pathsSummary)}]`,
569
+ );
570
+ }
571
+ const rawPath = args?.path || (Array.isArray(args?.paths) ? args.paths[0] : "") || "";
447
572
  const relPath = rawPath
448
573
  ? path.relative(context.cwd, rawPath) || rawPath
449
574
  : "";