@anusornneal/chat-relay 1.4.0 → 1.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.
@@ -7,6 +7,7 @@ const DEFAULT_READ_RESPONSE_BYTES = 32 * 1024;
7
7
  const DEFAULT_MULTI_READ_RESPONSE_BYTES = 48 * 1024;
8
8
  const DEFAULT_BATCH_RESPONSE_BYTES = 48 * 1024;
9
9
  const MAX_BATCH_OPERATIONS = 20;
10
+ const MAX_BATCH_SEARCHES = 8;
10
11
  const MAX_ARTIFACT_BYTES = 40 * 1024;
11
12
  const ARTIFACT_MIME_TYPES = new Map([
12
13
  [".txt", "text/plain; charset=utf-8"],
@@ -46,6 +47,23 @@ function skipSearchDirectory(name) {
46
47
  return skipWalkDirectory(name) || GENERATED_SEARCH_DIRS.has(name.toLowerCase());
47
48
  }
48
49
 
50
+ const SEARCH_CONTENT_CONCURRENCY = 8;
51
+
52
+ async function matchSearchContent(fullPath, needle) {
53
+ const info = await fs.stat(fullPath).catch(() => null);
54
+ if (!info || info.size > 1024 * 1024) return null;
55
+ const bytes = await fs.readFile(fullPath).catch(() => null);
56
+ if (!bytes || bytes.subarray(0, 1024).includes(0)) return null;
57
+ const content = bytes.toString("utf8");
58
+ const index = content.toLowerCase().indexOf(needle);
59
+ if (index < 0) return null;
60
+ return {
61
+ path: fullPath,
62
+ line: content.slice(0, index).split(/\r?\n/).length,
63
+ preview: content.slice(index, index + 240),
64
+ };
65
+ }
66
+
49
67
  function splitRoots(spec) {
50
68
  if (!spec) return [process.cwd()];
51
69
  return spec.split(";").map((value) => value.trim()).filter(Boolean).map((value) => path.resolve(value));
@@ -288,6 +306,9 @@ export class FileManager {
288
306
  throw new Error("invalid_batch");
289
307
  }
290
308
 
309
+ if (operations.filter((item) => item?.op === "search").length > MAX_BATCH_SEARCHES) {
310
+ throw new Error("too_many_batch_searches");
311
+ }
291
312
  const totalBudget = boundedReadBytes(maxTotalBytes, DEFAULT_BATCH_RESPONSE_BYTES, 4 * 1024);
292
313
  const results = [];
293
314
  let nextIndex = null;
@@ -319,6 +340,8 @@ export class FileManager {
319
340
  result = await this.read(operation.path, operation.offset, operation.length, operationBudget);
320
341
  } else if (op === "list") {
321
342
  result = await this.list(operation.path, operation.depth, operation.offset, operation.limit, operationBudget);
343
+ } else if (op === "search") {
344
+ result = await this.startSearch(operation.path, operation.pattern, operation.searchType, operation.maxResults ?? 10, operation.previewLines);
322
345
  } else {
323
346
  throw new Error("invalid_batch_operation");
324
347
  }
@@ -332,6 +355,25 @@ export class FileManager {
332
355
  maxTotalBytes: totalBudget,
333
356
  };
334
357
  if (byteSize(projected) <= totalBudget) break;
358
+ if (op === "search") {
359
+ // Keep the session usable even when first-page previews exceed
360
+ // the aggregate response budget. The caller can continue from
361
+ // sessionId + nextOffset without repeating the scan.
362
+ candidate = undefined;
363
+ for (let keep = result.results.length - 1; keep >= 0; keep--) {
364
+ const page = {
365
+ ...result,
366
+ results: result.results.slice(0, keep),
367
+ nextOffset: keep < result.totalResults ? keep : null,
368
+ };
369
+ const reduced = { ...base, ok: true, result: page };
370
+ if (byteSize({ ...projected, results: [...results, reduced] }) <= totalBudget) {
371
+ candidate = reduced;
372
+ break;
373
+ }
374
+ }
375
+ break;
376
+ }
335
377
  if (op === "stat") {
336
378
  candidate = undefined;
337
379
  break;
@@ -368,7 +410,9 @@ export class FileManager {
368
410
  results.push(candidate);
369
411
  }
370
412
 
371
- const nestedTruncated = results.some((entry) => entry.ok && entry.result?.truncated === true);
413
+ const nestedTruncated = results.some((entry) => entry.ok && (
414
+ entry.result?.truncated === true || (entry.op === "search" && entry.result?.nextOffset !== null)
415
+ ));
372
416
  return {
373
417
  results,
374
418
  totalOperations: operations.length,
@@ -466,7 +510,7 @@ export class FileManager {
466
510
  }
467
511
  }
468
512
 
469
- async startSearch(input, pattern, searchType = "files", maxResults = 100) {
513
+ async startSearch(input, pattern, searchType = "files", maxResults = 100, previewLines = 0) {
470
514
  const target = await this.#resolveExisting(input);
471
515
  if (typeof pattern !== "string" || pattern.length === 0 || pattern.length > 300) {
472
516
  throw new Error("invalid_pattern");
@@ -494,35 +538,37 @@ export class FileManager {
494
538
  const current = queue.shift();
495
539
  const items = await fs.readdir(current, { withFileTypes: true }).catch(() => []);
496
540
  items.sort((a, b) => a.name.localeCompare(b.name));
497
- for (const item of items) {
498
- if (session.results.length >= limit || session.scanned >= MAX_SEARCH_FILES) {
499
- session.incomplete = true;
500
- session.stopReason = session.results.length >= limit ? "result_limit" : "scan_limit";
501
- break;
502
- }
503
- if (item.isDirectory() && skipSearchDirectory(item.name)) continue;
504
- const fullPath = path.join(current, item.name);
505
- session.scanned++;
506
-
507
- if (searchType === "files" && item.name.toLowerCase().includes(needle)) {
508
- session.results.push({ path: fullPath, name: item.name, type: item.isDirectory() ? "directory" : "file" });
509
- } else if (searchType === "content" && item.isFile()
510
- && !SEARCH_BINARY_EXTENSIONS.has(path.extname(item.name).toLowerCase())) {
511
- const info = await fs.stat(fullPath).catch(() => null);
512
- if (info && info.size <= 1024 * 1024) {
513
- const bytes = await fs.readFile(fullPath).catch(() => null);
514
- if (bytes && !bytes.subarray(0, 1024).includes(0)) {
515
- const text = bytes.toString("utf8");
516
- const index = text.toLowerCase().indexOf(needle);
517
- if (index >= 0) {
518
- const before = text.slice(0, index);
519
- const line = before.split(/\r?\n/).length;
520
- session.results.push({ path: fullPath, line, preview: text.slice(index, index + 240) });
521
- }
522
- }
541
+ // Prefetch up to eight independent file reads without changing BFS result order.
542
+ // Speculative reads may exceed the logical result cap by at most one small window.
543
+ const windowSize = searchType === "content" ? SEARCH_CONTENT_CONCURRENCY : Math.max(items.length, 1);
544
+ for (let offset = 0; offset < items.length; offset += windowSize) {
545
+ const group = items.slice(offset, offset + windowSize);
546
+ const contentMatches = searchType === "content"
547
+ ? await Promise.all(group.map((item) =>
548
+ item.isFile() && !SEARCH_BINARY_EXTENSIONS.has(path.extname(item.name).toLowerCase())
549
+ ? matchSearchContent(path.join(current, item.name), needle)
550
+ : null))
551
+ : null;
552
+
553
+ for (let index = 0; index < group.length; index++) {
554
+ if (session.results.length >= limit || session.scanned >= MAX_SEARCH_FILES) {
555
+ session.incomplete = true;
556
+ session.stopReason = session.results.length >= limit ? "result_limit" : "scan_limit";
557
+ break;
558
+ }
559
+ const item = group[index];
560
+ if (item.isDirectory() && skipSearchDirectory(item.name)) continue;
561
+ const fullPath = path.join(current, item.name);
562
+ session.scanned++;
563
+
564
+ if (searchType === "files" && item.name.toLowerCase().includes(needle)) {
565
+ session.results.push({ path: fullPath, name: item.name, type: item.isDirectory() ? "directory" : "file" });
566
+ } else if (contentMatches?.[index]) {
567
+ session.results.push(contentMatches[index]);
523
568
  }
569
+ if (item.isDirectory()) queue.push(fullPath);
524
570
  }
525
- if (item.isDirectory()) queue.push(fullPath);
571
+ if (session.incomplete) break;
526
572
  }
527
573
  if (!session.incomplete && queue.length > 0
528
574
  && (session.results.length >= limit || session.scanned >= MAX_SEARCH_FILES)) {
@@ -549,9 +595,10 @@ export class FileManager {
549
595
  for (const item of session.results.slice(0, MAX_SEARCH_FIRST_PAGE_RESULTS)) {
550
596
  const size = byteSize(item);
551
597
  if (firstPage.length > 0 && pageBytes + size > MAX_SEARCH_FIRST_PAGE_BYTES) break;
552
- firstPage.push(item);
598
+ firstPage.push({ ...item });
553
599
  pageBytes += size;
554
600
  }
601
+ await this.#addSearchPreviews(firstPage, previewLines);
555
602
  return {
556
603
  sessionId,
557
604
  status: session.status,
@@ -566,6 +613,39 @@ export class FileManager {
566
613
  };
567
614
  }
568
615
 
616
+ // A page of matches can be expanded without repeating the original search.
617
+ async getSearchResultsWithPreview(sessionId, offset = 0, length = 50, previewLines = 0) {
618
+ const requested = Number(previewLines) > 0 ? Math.min(Math.max(Number(length) || 50, 1), 20) : length;
619
+ const page = this.getSearchResults(sessionId, offset, requested);
620
+ page.results = page.results.map((item) => ({ ...item }));
621
+ await this.#addSearchPreviews(page.results, previewLines);
622
+ return page;
623
+ }
624
+
625
+ async #addSearchPreviews(results, requestedLines) {
626
+ const count = Math.min(60, Math.max(0, Math.trunc(Number(requestedLines) || 0)));
627
+ if (count === 0) return;
628
+ let remaining = 16 * 1024;
629
+ for (const item of results) {
630
+ if (remaining < 1024) break;
631
+ if (!item.path || item.type === "directory") continue;
632
+ const matchSnippet = typeof item.preview === "string" ? item.preview : undefined;
633
+ const start = Number.isInteger(item.line)
634
+ ? Math.max(0, item.line - 1 - Math.floor(count / 2)) : 0;
635
+ try {
636
+ const read = await this.read(item.path, start, count, Math.min(4096, remaining));
637
+ const context = { offset: read.offset, length: read.length, totalLines: read.totalLines,
638
+ content: read.content, truncated: read.truncated, nextOffset: read.nextOffset };
639
+ if (matchSnippet && read.offset + read.length < item.line) context.matchSnippet = matchSnippet;
640
+ if (byteSize(context) > remaining) break;
641
+ item.preview = context;
642
+ remaining -= byteSize(context);
643
+ } catch {
644
+ item.preview = { unavailable: true, ...(matchSnippet ? { matchSnippet } : {}) };
645
+ }
646
+ }
647
+ }
648
+
569
649
  getSearchResults(sessionId, offset = 0, length = 50) {
570
650
  this.#pruneSearchSessions();
571
651
  const key = String(sessionId);
@@ -236,9 +236,9 @@ async function handlePayload(payload) {
236
236
  case "fs.delete":
237
237
  return files.remove(payload.path, payload.recursive);
238
238
  case "fs.search.start":
239
- return files.startSearch(payload.path, payload.pattern, payload.searchType, payload.maxResults);
239
+ return files.startSearch(payload.path, payload.pattern, payload.searchType, payload.maxResults, payload.previewLines);
240
240
  case "fs.search.results":
241
- return files.getSearchResults(payload.sessionId, payload.offset, payload.length);
241
+ return files.getSearchResultsWithPreview(payload.sessionId, payload.offset, payload.length, payload.previewLines);
242
242
 
243
243
  case "git.worktree.cleanup":
244
244
  return gitWorktrees.cleanup(payload.repoPath, payload.worktreePath);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anusornneal/chat-relay",
3
- "version": "1.4.0",
3
+ "version": "1.6.0",
4
4
  "description": "Zero-checkout remote MCP agent for ChatGPT with terminal, filesystem, process, multi-user, and multi-agent support.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -59,8 +59,11 @@
59
59
  "test:self-update": "node --test test/self-update.test.mjs test/agent-lifecycle-upgrade.test.mjs",
60
60
  "test:budget": "node --test test/relay-health.test.mjs test/usage-budget.test.mjs",
61
61
  "test:soak": "node test/soak-smoke.mjs",
62
- "test:file-search": "node --test test/file-search.test.mjs",
63
- "test:hardening": "npm run test:file-search && npm run test:tool-guidance && npm run test:tui && npm run test:config-security && npm run test:self-update && npm run test:budget && npm run test:worker-hotpath && node --test test/connection-generation.test.mjs && npm run test:agent-state && node test/heartbeat-ack-watchdog.test.mjs && npm run test:no-quota && npm run test:usage-storage && npm run test:learn && npm run test:learn-bootstrap && npm run test:soak",
62
+ "test:file-search": "node --test test/file-search.test.mjs test/search-preview.test.mjs test/adaptive-tools.test.mjs",
63
+ "bench:search-preview:e2e": "node test/search-preview-e2e-benchmark.mjs",
64
+ "test:hardening": "npm run test:file-search && npm run test:batch-contract && npm run test:terminal-perf && npm run test:tool-guidance && npm run test:tui && npm run test:config-security && npm run test:self-update && npm run test:budget && npm run test:worker-hotpath && node --test test/connection-generation.test.mjs && npm run test:agent-state && node test/heartbeat-ack-watchdog.test.mjs && npm run test:no-quota && npm run test:usage-storage && npm run test:learn && npm run test:learn-bootstrap && npm run test:soak",
65
+ "test:batch-contract": "node --test test/tool-contract-batch.test.mjs",
66
+ "test:terminal-perf": "node --test test/terminal-perf.test.mjs",
64
67
  "test:tool-guidance": "node --test test/tool-error-guidance.test.mjs",
65
68
  "verify:review": "node scripts/verify-review-artifacts.mjs",
66
69
  "test:learn": "node test/learning-smoke.mjs && node test/project-alias-sqlite.test.mjs && node test/project-merge-mcp.test.mjs && node --test test/shared-learn.test.mjs test/shared-learn-ui.test.mjs && npm run test:learn-usage",