@anusornneal/chat-relay 1.8.0 → 1.9.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/README.md CHANGED
@@ -278,3 +278,57 @@ The decision boundary is deliberate:
278
278
  Project aliases are account-scoped mappings stored in the Learning Durable Object. Use **My Learn → Merge projects** to join workspace names (for example `buddy-android` → `buddy2`) once, while retaining memory IDs, feedback, and timestamps; the source becomes a permanent alias for future Learn reads/writes across machines. Aliases are never inferred from similar names, and project resolution occurs only during Learn requests—not on ordinary tool calls. Merges run transactionally; conflicting keys with distinct content are renamed instead of discarded.\n\nRouting hints are explicit memories. A global `project_context` memory with key `project-root:<projectKey>` stores the concrete project root. A `preferred-agent` memory may exist in project scope (preferred) or global scope (fallback). `learn_prepare` can also take explicit `projectKey` and `agentId` values when Chat already knows them.
279
279
 
280
280
  `learn_prepare` is intentionally one-shot and stateless at the Worker level. There is no warm session cache or durable Learn session state to maintain. This prevents Learn from becoming an implicit per-tool CPU/subrequest tax while still allowing relevance-aware context preparation when it is actually useful.
281
+
282
+ ## Efficient tool usage (agent and MCP must support the new capabilities)
283
+
284
+ - For multiple independent file edits/creates use **edit_files** (write permission).
285
+ The operation list supports a missing-file create or 1-20 exact replacements per
286
+ file. At most 20 files, 100 replacements and 48 KiB encoded arguments per batch.
287
+ Existing parents are required. Each result identifies its original index and
288
+ success/error; inspect results and retry only failed entries after re-reading.
289
+ UTF-8 is validated; uniform CRLF and BOM are preserved for existing files.
290
+ Updates publish atomically per file and recheck the original bytes before
291
+ replacement; this is not a cross-file transaction or an OS compare-and-swap
292
+ against other programs writing concurrently. Create uses no-clobber publication
293
+ on filesystems supporting hard links.
294
+ - **read_multiple_files**, **fs_batch**, and **edit_files** accept an optional
295
+ absolute basePath. With it, paths must be relative and stay beneath that
296
+ canonical directory and allowedRoots, including junction/symlink checks.
297
+ Without it existing path behavior is retained.
298
+ - **fs_batch** with deduplicatePreviews=true packs overlapping identical search
299
+ context into sharedPreviews. A match's preview.ref refers to sharedPreviews.id;
300
+ reconstruct the original content by slicing the shared content's lines from
301
+ preview.offset - shared.offset for preview.length lines. Matches, individual
302
+ metadata and search sessions/pagination are preserved. This saves response
303
+ bytes, not repeated search scans.
304
+ - **terminal_exec**, **terminal_read** and **terminal_batch_read** default to
305
+ full output. Optional outputMode=summary, tail, or errors limits displayed
306
+ text (outputChars defaults to 2048, range 256-8192). Summary keeps failure
307
+ diagnostics; errors is a heuristic, not a compiler parser. Compact exec
308
+ returns rawOutputId if text was omitted; read it with terminal_read and the
309
+ normal nextSeq cursor. Up to 16 short-command captures for 10 minutes in RAM.
310
+ For compact session reads replay full mode with rawAfterSeq while the session
311
+ buffer is retained. For batches replay full mode with jobIndex. Original
312
+ capture/time/size limits still apply; use terminal_start for verbose/long
313
+ commands. Neither compact output nor a replay executes the command again.
314
+ - **get_recent_tool_calls** keeps its legacy array response (up to 100 entries).
315
+ Use view=history with limit and nextCursor to page up to 1000 process-local
316
+ calls; cursor expires on process restart. Use view=stats with days=1..30 for
317
+ UTC-day totals, per-tool calls/failures/durations/bytes, batch item counts,
318
+ observed batch-read share and estimated saved read calls. Saved calls assume
319
+ one separate read per successful read operation; continuation and missed batch
320
+ opportunities are not measured. Terminal-based reads are not classified.
321
+ Only numerical daily aggregates are persisted per agent under the local
322
+ Chat Relay config directory's usage/ folder. No paths, commands, content,
323
+ credentials or screenshots are persisted by this feature. A dirty snapshot
324
+ flushes at most once per 30 seconds and at graceful exit; abrupt termination
325
+ can lose recent counters. Recent detailed entries and compact raw output
326
+ are RAM-only. Each agent's statistics start after it upgrades; no historical
327
+ backfill. Set CHAT_RELAY_USAGE_DISABLED=1 for memory-only aggregates.
328
+ - New optional behaviors use distinct agent actions so older agents fail
329
+ explicitly rather than interpreting relative paths or compact requests
330
+ incorrectly. Existing calls remain unchanged. Upgrade the local agent and
331
+ refresh the MCP catalog before using the new features.
332
+
333
+ No new Cloudflare storage, dependencies or additional routine relay round trips
334
+ are needed for these improvements.
@@ -116,7 +116,7 @@ export class CapabilityScheduler {
116
116
  const value = String(action || "unknown");
117
117
  if (value.startsWith("fs.")) return this.lanes.get("filesystem");
118
118
  if (value.startsWith("process.")) return this.lanes.get("process");
119
- if (value === "terminal.exec") return this.lanes.get("terminalExec");
119
+ if (value === "terminal.exec" || value === "terminal.exec.compact") return this.lanes.get("terminalExec");
120
120
  if (value === "terminal.read.wait") return this.lanes.get("terminalWait");
121
121
  if (value.startsWith("terminal.")) return this.lanes.get("terminalControl");
122
122
  if (["desktop.screenshot", "desktop.clipboard.read", "desktop.window.list"].includes(value)) {
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
+ import { deduplicateSearchPreviews } from "./fs-batch-preview.mjs";
4
5
 
5
6
  const MAX_READ_BYTES = 256 * 1024;
6
7
  const DEFAULT_READ_RESPONSE_BYTES = 32 * 1024;
@@ -8,6 +9,8 @@ const DEFAULT_MULTI_READ_RESPONSE_BYTES = 48 * 1024;
8
9
  const DEFAULT_BATCH_RESPONSE_BYTES = 48 * 1024;
9
10
  const MAX_BATCH_OPERATIONS = 20;
10
11
  const MAX_BATCH_SEARCHES = 8;
12
+ const MAX_BATCH_EDIT_BYTES = 48 * 1024;
13
+ const MAX_BATCH_EDITS = 100;
11
14
  const MAX_ARTIFACT_BYTES = 40 * 1024;
12
15
  const ARTIFACT_MIME_TYPES = new Map([
13
16
  [".txt", "text/plain; charset=utf-8"],
@@ -93,10 +96,24 @@ function normalizeReadRequest(input) {
93
96
  return typeof input === "string" ? { path: input } : { ...(input || {}) };
94
97
  }
95
98
 
99
+ function utf8Bytes(text, max) {
100
+ if (typeof text !== "string" || !text.isWellFormed() || text.includes("\0")) throw new Error("invalid_utf8");
101
+ const bytes = Buffer.from(text, "utf8");
102
+ if (bytes.length > max) throw new Error("file_too_large");
103
+ return bytes;
104
+ }
105
+
106
+ function editError(error) {
107
+ // Return a compact stable error, not paths or an arbitrary OS exception string.
108
+ const code = typeof error?.code === "string" ? error.code : error?.message;
109
+ return typeof code === "string" && /^[a-zA-Z0-9_:-]{1,100}$/.test(code) ? code : "batch_edit_failed";
110
+ }
111
+
96
112
  export class FileManager {
97
113
  constructor(rootSpec) {
98
114
  this.roots = splitRoots(rootSpec);
99
115
  this.searches = new Map();
116
+ this.editBatchTail = Promise.resolve();
100
117
  }
101
118
 
102
119
  getRoots() {
@@ -123,6 +140,35 @@ export class FileManager {
123
140
  throw new Error("path_not_allowed");
124
141
  }
125
142
 
143
+ async #resolveBatchBase(basePath) {
144
+ if (basePath === undefined || basePath === null) return null;
145
+ if (typeof basePath !== "string" || !path.isAbsolute(basePath)) throw new Error("invalid_base_path");
146
+ const base = await this.#resolveExisting(basePath);
147
+ if (!(await fs.stat(base)).isDirectory()) throw new Error("base_not_directory");
148
+ return base;
149
+ }
150
+
151
+ async #batchPath(input, base, create = false) {
152
+ if (typeof input !== "string" || !input || input.includes("\0")) throw new Error("invalid_path");
153
+ if (process.platform === "win32" && input.replace(/^[a-z]:/i, "").includes(":")) {
154
+ throw new Error("invalid_path");
155
+ }
156
+ if (!base && !create) return input;
157
+ if (base && (path.isAbsolute(input) || path.win32.isAbsolute(input) || /^[a-z]:/i.test(input))) {
158
+ throw new Error("relative_path_required");
159
+ }
160
+ const target = path.resolve(base || process.cwd(), input);
161
+ if (base && !within(base, target)) throw new Error("path_outside_base");
162
+ if (create) {
163
+ const parent = await this.#resolveExisting(path.dirname(target));
164
+ if (base && !within(base, parent)) throw new Error("path_outside_base");
165
+ return path.join(parent, path.basename(target));
166
+ }
167
+ const canonical = await this.#resolveExisting(target);
168
+ if (base && !within(base, canonical)) throw new Error("path_outside_base");
169
+ return canonical;
170
+ }
171
+
126
172
  async stat(input) {
127
173
  const target = await this.#resolveExisting(input);
128
174
  const info = await fs.stat(target);
@@ -221,11 +267,12 @@ export class FileManager {
221
267
  };
222
268
  }
223
269
 
224
- async readMany(paths, maxTotalBytes = DEFAULT_MULTI_READ_RESPONSE_BYTES) {
270
+ async readMany(paths, maxTotalBytes = DEFAULT_MULTI_READ_RESPONSE_BYTES, basePath) {
225
271
  if (!Array.isArray(paths) || paths.length === 0 || paths.length > 20) {
226
272
  throw new Error("invalid_paths");
227
273
  }
228
274
 
275
+ const base = basePath == null ? null : await this.#resolveBatchBase(basePath);
229
276
  const requests = paths.map(normalizeReadRequest);
230
277
  if (requests.some((entry) => typeof entry.path !== "string" || entry.path.length === 0)) {
231
278
  throw new Error("invalid_paths");
@@ -247,8 +294,9 @@ export class FileManager {
247
294
  let candidate;
248
295
 
249
296
  try {
297
+ const target = base ? await this.#batchPath(request.path, base) : request.path;
250
298
  for (let attempt = 0; attempt < 8; attempt++) {
251
- const result = await this.read(request.path, start, length, fileBudget);
299
+ const result = await this.read(target, start, length, fileBudget);
252
300
  candidate = { ok: true, ...result };
253
301
  const projected = {
254
302
  files: [...files, candidate],
@@ -301,17 +349,24 @@ export class FileManager {
301
349
  }
302
350
 
303
351
 
304
- async batch(operations, maxTotalBytes = DEFAULT_BATCH_RESPONSE_BYTES) {
352
+ async batch(operations, maxTotalBytes = DEFAULT_BATCH_RESPONSE_BYTES, options = {}) {
305
353
  if (!Array.isArray(operations) || operations.length === 0 || operations.length > MAX_BATCH_OPERATIONS) {
306
354
  throw new Error("invalid_batch");
307
355
  }
308
-
309
356
  if (operations.filter((item) => item?.op === "search").length > MAX_BATCH_SEARCHES) {
310
357
  throw new Error("too_many_batch_searches");
311
358
  }
359
+ const batchBase = options.basePath == null ? null : await this.#resolveBatchBase(options.basePath);
312
360
  const totalBudget = boundedReadBytes(maxTotalBytes, DEFAULT_BATCH_RESPONSE_BYTES, 4 * 1024);
313
361
  const results = [];
314
362
  let nextIndex = null;
363
+ const payloadFor = (rows, next, truncated = false) => ({
364
+ ...(options.deduplicatePreviews === true ? deduplicateSearchPreviews(rows) : { results: rows }),
365
+ totalOperations: operations.length,
366
+ nextIndex: next,
367
+ truncated,
368
+ maxTotalBytes: totalBudget,
369
+ });
315
370
 
316
371
  for (let index = 0; index < operations.length; index++) {
317
372
  const operation = operations[index] || {};
@@ -322,106 +377,157 @@ export class FileManager {
322
377
  op,
323
378
  ...(typeof operation.path === "string" ? { path: operation.path } : {}),
324
379
  };
380
+ const next = index + 1 < operations.length ? index + 1 : null;
381
+ const fits = candidate => byteSize(payloadFor([...results, candidate], next)) <= totalBudget;
325
382
  const minimumBudget = op === "list" ? 4 * 1024 : MIN_READ_RESPONSE_BYTES;
326
383
  const fallbackBudget = op === "list" ? DEFAULT_LIST_RESPONSE_BYTES : DEFAULT_READ_RESPONSE_BYTES;
327
384
  let operationBudget = boundedReadBytes(operation.maxBytes, fallbackBudget, minimumBudget);
328
385
  let candidate;
329
-
330
386
  try {
331
- if (typeof operation.path !== "string" || operation.path.length === 0) {
332
- throw new Error("invalid_path");
333
- }
334
-
387
+ if (typeof operation.path !== "string" || !operation.path) throw new Error("invalid_path");
388
+ const target = batchBase ? await this.#batchPath(operation.path, batchBase) : operation.path;
335
389
  for (let attempt = 0; attempt < 8; attempt++) {
336
390
  let result;
337
- if (op === "stat") {
338
- result = await this.stat(operation.path);
339
- } else if (op === "read") {
340
- result = await this.read(operation.path, operation.offset, operation.length, operationBudget);
341
- } else if (op === "list") {
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);
345
- } else {
346
- throw new Error("invalid_batch_operation");
347
- }
391
+ if (op === "stat") result = await this.stat(target);
392
+ else if (op === "read") result = await this.read(target, operation.offset, operation.length, operationBudget);
393
+ else if (op === "list") result = await this.list(target, operation.depth, operation.offset, operation.limit, operationBudget);
394
+ else if (op === "search") result = await this.startSearch(target, operation.pattern, operation.searchType, operation.maxResults ?? 10, operation.previewLines);
395
+ else throw new Error("invalid_batch_operation");
348
396
 
349
397
  candidate = { ...base, ok: true, result };
350
- const projected = {
351
- results: [...results, candidate],
352
- totalOperations: operations.length,
353
- nextIndex: index + 1 < operations.length ? index + 1 : null,
354
- truncated: false,
355
- maxTotalBytes: totalBudget,
356
- };
357
- if (byteSize(projected) <= totalBudget) break;
398
+ if (fits(candidate)) break;
399
+ candidate = undefined;
358
400
  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;
401
+ // Do not repeat a scan just to fit its initial response page.
363
402
  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
- };
403
+ const page = { ...result, results: result.results.slice(0, keep),
404
+ nextOffset: keep < result.totalResults ? keep : null };
369
405
  const reduced = { ...base, ok: true, result: page };
370
- if (byteSize({ ...projected, results: [...results, reduced] }) <= totalBudget) {
371
- candidate = reduced;
372
- break;
373
- }
406
+ if (fits(reduced)) { candidate = reduced; break; }
374
407
  }
375
408
  break;
376
409
  }
377
- if (op === "stat") {
378
- candidate = undefined;
379
- break;
380
- }
381
-
410
+ if (op === "stat") break;
382
411
  operationBudget = Math.floor(operationBudget * 0.65);
383
- candidate = undefined;
384
412
  if (operationBudget < minimumBudget) break;
385
413
  }
386
414
  } catch (error) {
387
- candidate = {
388
- ...base,
389
- ok: false,
390
- error: error instanceof Error ? error.message : "batch_operation_failed",
391
- };
392
- }
393
-
394
- if (!candidate) {
395
- nextIndex = index;
396
- break;
397
- }
398
-
399
- const projected = {
400
- results: [...results, candidate],
401
- totalOperations: operations.length,
402
- nextIndex: index + 1 < operations.length ? index + 1 : null,
403
- truncated: false,
404
- maxTotalBytes: totalBudget,
405
- };
406
- if (byteSize(projected) > totalBudget) {
407
- nextIndex = index;
408
- break;
415
+ candidate = { ...base, ok: false, error: error instanceof Error ? error.message : "batch_operation_failed" };
409
416
  }
417
+ if (!candidate || !fits(candidate)) { nextIndex = index; break; }
410
418
  results.push(candidate);
411
419
  }
412
420
 
413
- const nestedTruncated = results.some((entry) => entry.ok && (
421
+ const nestedTruncated = results.some(entry => entry.ok && (
414
422
  entry.result?.truncated === true || (entry.op === "search" && entry.result?.nextOffset !== null)
415
423
  ));
416
- return {
417
- results,
418
- totalOperations: operations.length,
419
- nextIndex,
420
- truncated: nextIndex !== null || nestedTruncated,
421
- maxTotalBytes: totalBudget,
422
- };
424
+ return payloadFor(results, nextIndex, nextIndex !== null || nestedTruncated);
425
+ }
426
+
427
+ // One entry per file, multiple exact replacements per entry. Separate from read-only batch.
428
+ editMany(operations, basePath) {
429
+ const run = this.editBatchTail.then(() => this.#editMany(operations, basePath));
430
+ this.editBatchTail = run.catch(() => {});
431
+ return run;
432
+ }
433
+
434
+ async #editMany(operations, basePath) {
435
+ if (!Array.isArray(operations) || !operations.length || operations.length > MAX_BATCH_OPERATIONS) {
436
+ throw new Error("invalid_edit_batch");
437
+ }
438
+ if (byteSize({ operations, basePath }) > MAX_BATCH_EDIT_BYTES) throw new Error("edit_batch_too_large");
439
+ const count = operations.reduce((sum, op) => sum + (Array.isArray(op?.edits) ? op.edits.length : 0), 0);
440
+ if (count > MAX_BATCH_EDITS) throw new Error("too_many_batch_edits");
441
+ const base = await this.#resolveBatchBase(basePath);
442
+ const resolved = [];
443
+ const targets = new Map();
444
+ for (const [index, operation] of operations.entries()) {
445
+ const input = typeof operation?.path === "string" ? operation.path : "";
446
+ const row = { index, path: input.slice(0, 512), ...(input.length > 512 ? { pathTruncated: true } : {}) };
447
+ try {
448
+ if (!["create", "edit"].includes(operation?.op)) throw new Error("invalid_edit_batch_operation");
449
+ const create = operation.op === "create";
450
+ const selected = await this.#batchPath(input, base, create);
451
+ const target = create ? selected : await this.#resolveExisting(selected);
452
+ const key = process.platform === "win32" ? target.toLowerCase() : target;
453
+ resolved.push({ row, operation, target, key });
454
+ targets.set(key, (targets.get(key) || 0) + 1);
455
+ } catch (error) {
456
+ resolved.push({ row: { ...row, ok: false, error: editError(error) } });
457
+ }
458
+ }
459
+
460
+ const results = [];
461
+ for (const entry of resolved) {
462
+ if (!entry.target) { results.push(entry.row); continue; }
463
+ const { row, operation, target, key } = entry;
464
+ try {
465
+ if (targets.get(key) > 1) throw new Error("duplicate_batch_target");
466
+ const create = operation.op === "create";
467
+ let original = null, mode, updated, replacements = 0;
468
+ if (create) {
469
+ updated = utf8Bytes(operation.content, MAX_WRITE_BYTES);
470
+ } else {
471
+ const info = await fs.lstat(target);
472
+ if (!info.isFile() || info.isSymbolicLink()) throw new Error("not_a_file");
473
+ if (info.size > MAX_WRITE_BYTES * 8) throw new Error("file_too_large");
474
+ original = await fs.readFile(target);
475
+ if (original.length > MAX_WRITE_BYTES * 8) throw new Error("file_too_large");
476
+ if (original.includes(0)) throw new Error("invalid_utf8");
477
+ let text;
478
+ try { text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(original); }
479
+ catch { throw new Error("invalid_utf8"); }
480
+ mode = info.mode & 0o777;
481
+ if (!Array.isArray(operation.edits) || !operation.edits.length || operation.edits.length > 20) throw new Error("invalid_edit");
482
+ const crlf = text.includes("\r\n") && !text.replace(/\r\n/g, "").includes("\n");
483
+ const eol = value => crlf ? value.replace(/\r?\n/g, "\r\n") : value;
484
+ for (const edit of operation.edits) {
485
+ if (typeof edit?.oldText !== "string" || !edit.oldText || typeof edit.newText !== "string" ||
486
+ !edit.oldText.isWellFormed() || !edit.newText.isWellFormed()) throw new Error("invalid_edit");
487
+ const expected = edit.expectedReplacements ?? 1;
488
+ if (!Number.isInteger(expected) || expected < 1 || expected > 100) throw new Error("invalid_edit");
489
+ const parts = text.split(eol(edit.oldText));
490
+ const matches = parts.length - 1;
491
+ if (matches !== expected) throw new Error("replacement_count_mismatch:" + matches);
492
+ text = parts.join(eol(edit.newText));
493
+ replacements += matches;
494
+ }
495
+ updated = utf8Bytes(text, MAX_WRITE_BYTES * 8);
496
+ }
497
+ await this.#commitBatchFile(target, original, updated, mode, base);
498
+ results.push({ ...row, ok: true, op: operation.op, bytes: updated.length, ...(create ? {} : { replacements }) });
499
+ } catch (error) {
500
+ results.push({ ...row, ok: false, op: operation.op, error: editError(error) });
501
+ }
502
+ }
503
+ const succeeded = results.filter(row => row.ok).length;
504
+ return { ok: succeeded === results.length, requested: results.length, succeeded, failed: results.length - succeeded,
505
+ ...(succeeded === results.length ? {} : { error: "batch_edit_partial_failure" }), results };
423
506
  }
424
507
 
508
+ async #commitBatchFile(target, original, updated, mode, base) {
509
+ const parent = await this.#resolveExisting(path.dirname(target));
510
+ if (base && !within(base, parent)) throw new Error("path_outside_base");
511
+ if (path.relative(parent, path.dirname(target)) !== "") throw new Error("target_changed");
512
+ const temporary = path.join(parent, ".chat-relay-" + randomUUID() + ".tmp");
513
+ try {
514
+ await fs.writeFile(temporary, updated, { flag: "wx", ...(mode === undefined ? {} : { mode }) });
515
+ const currentParent = await this.#resolveExisting(parent);
516
+ if (path.relative(parent, currentParent) !== "") throw new Error("target_changed");
517
+ if (original === null) {
518
+ // Same-directory link is an atomic no-clobber publish, even if another creator wins.
519
+ await fs.link(temporary, target);
520
+ } else {
521
+ const info = await fs.lstat(target);
522
+ if (!info.isFile() || info.isSymbolicLink() || info.size !== original.length ||
523
+ !(await fs.readFile(target)).equals(original)) throw new Error("target_changed");
524
+ // Atomic replacement per file, not a transaction across files or an OS-level CAS.
525
+ await fs.rename(temporary, target);
526
+ }
527
+ } finally {
528
+ await fs.unlink(temporary).catch(() => {});
529
+ }
530
+ }
425
531
 
426
532
  async exportArtifact(input, maxBytes = MAX_ARTIFACT_BYTES) {
427
533
  const target = await this.#resolveExisting(input);
@@ -0,0 +1,70 @@
1
+ // Opt-in response packing only: preserve each match and its original preview range.
2
+ const size = value => Buffer.byteLength(JSON.stringify(value), "utf8");
3
+
4
+ export function deduplicateSearchPreviews(results) {
5
+ const byPath = new Map();
6
+ for (const [rowIndex, row] of results.entries()) {
7
+ if (!row.ok || row.op !== "search" || !Array.isArray(row.result?.results)) continue;
8
+ for (const [matchIndex, match] of row.result.results.entries()) {
9
+ const preview = match.preview;
10
+ if (!match.path || !preview || typeof preview.content !== "string" ||
11
+ !Number.isInteger(preview.offset) || !Number.isInteger(preview.length) || preview.length < 1) continue;
12
+ const lines = preview.content.split("\n");
13
+ if (lines.length !== preview.length) continue;
14
+ const group = byPath.get(match.path) || [];
15
+ group.push({ rowIndex, matchIndex, preview, lines });
16
+ byPath.set(match.path, group);
17
+ }
18
+ }
19
+
20
+ const sharedPreviews = [];
21
+ const references = new Map();
22
+ for (const [filePath, previews] of byPath) {
23
+ if (previews.length < 2) continue;
24
+ previews.sort((a, b) => a.preview.offset - b.preview.offset);
25
+ let group = null;
26
+ const emit = () => {
27
+ if (!group || group.members.length < 2) return;
28
+ const id = "p" + (sharedPreviews.length + 1);
29
+ const shared = { id, path: filePath, offset: group.offset, length: group.lines.length,
30
+ content: group.lines.join("\n") };
31
+ const replacements = group.members.map(member => {
32
+ const { content, ...metadata } = member.preview;
33
+ return { member, preview: { ...metadata, ref: id } };
34
+ });
35
+ // Short previews can cost more as references. Keep them inline in that case.
36
+ if (size(shared) + size(replacements.map(x => x.preview)) >=
37
+ size(group.members.map(x => x.preview))) return;
38
+ sharedPreviews.push(shared);
39
+ for (const { member, preview } of replacements) {
40
+ references.set(member.rowIndex + ":" + member.matchIndex, preview);
41
+ }
42
+ };
43
+ for (const item of previews) {
44
+ const offset = item.preview.offset;
45
+ const start = group ? offset - group.offset : 0;
46
+ const overlap = group ? Math.min(group.lines.length - start, item.lines.length) : 0;
47
+ // Never combine inconsistent snapshots (e.g. a file changed during the batch).
48
+ const compatible = group && overlap > 0 && item.preview.totalLines === group.totalLines &&
49
+ item.lines.slice(0, overlap).every((line, index) => line === group.lines[start + index]);
50
+ if (compatible) {
51
+ if (start + item.lines.length > group.lines.length) group.lines.push(...item.lines.slice(overlap));
52
+ group.members.push(item);
53
+ } else {
54
+ emit();
55
+ group = { offset, lines: [...item.lines], totalLines: item.preview.totalLines, members: [item] };
56
+ }
57
+ }
58
+ emit();
59
+ }
60
+ if (!sharedPreviews.length) return { results };
61
+ const packed = results.map((row, rowIndex) => {
62
+ if (!row.ok || row.op !== "search") return row;
63
+ return { ...row, result: { ...row.result, results: row.result.results.map((match, matchIndex) => {
64
+ const preview = references.get(rowIndex + ":" + matchIndex);
65
+ return preview ? { ...match, preview } : match;
66
+ }) } };
67
+ });
68
+ const candidate = { results: packed, sharedPreviews };
69
+ return size(candidate) < size({ results }) ? candidate : { results };
70
+ }
@@ -2,6 +2,8 @@ const ALLOWED_WHILE_DRAINING = new Set([
2
2
  "ping",
3
3
  "agent.config",
4
4
  "agent.recentCalls",
5
+ "agent.recentCalls.page",
6
+ "agent.usageStats",
5
7
  "agent.lifecycle.status",
6
8
  "agent.lifecycle.drain",
7
9
  "agent.lifecycle.resume",
@@ -11,7 +13,9 @@ const ALLOWED_WHILE_DRAINING = new Set([
11
13
  "fs.list",
12
14
  "fs.read",
13
15
  "fs.readMany",
16
+ "fs.readMany.relative",
14
17
  "fs.batch",
18
+ "fs.batch.compact",
15
19
  "fs.artifact",
16
20
  "fs.search.start",
17
21
  "fs.search.results",
@@ -22,8 +26,10 @@ const ALLOWED_WHILE_DRAINING = new Set([
22
26
  "desktop.window.list",
23
27
  "terminal.batch.status",
24
28
  "terminal.batch.read",
29
+ "terminal.batch.read.compact",
25
30
  "terminal.batch.cancel",
26
31
  "terminal.read",
32
+ "terminal.read.compact",
27
33
  "terminal.write",
28
34
  "terminal.kill",
29
35
  "terminal.list",