dsh-better-edit 0.8.2 → 1.0.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/CHANGELOG.md +158 -99
- package/README.md +2 -2
- package/README.zh.md +3 -3
- package/cordis.patch.yml +1 -1
- package/lib/constants.js +19 -4
- package/lib/contract.js +136 -79
- package/lib/domain-errors.js +570 -0
- package/lib/edit-diff.js +33 -7
- package/lib/file-encoding-state.js +27 -7
- package/lib/file-view.js +305 -82
- package/lib/fs-bridge.js +23 -7
- package/lib/hash-store.js +404 -278
- package/lib/hashline/anchor-pipeline.js +586 -378
- package/lib/hashline/hash-assign.js +21 -22
- package/lib/hashline/hash.js +6 -6
- package/lib/hashline/index.js +1 -1
- package/lib/hashline/resolve.js +1 -1
- package/lib/hashline/served-guard.js +181 -0
- package/lib/index.js +1 -1
- package/lib/mutation/engine.js +392 -96
- package/lib/mutation.js +22 -130
- package/lib/noop-guard.js +20 -9
- package/lib/prompts.js +20 -18
- package/lib/read-and-serve.js +44 -20
- package/lib/sandbox.js +1 -1
- package/lib/session-view.js +57 -43
- package/lib/snapshot-store/index.js +97 -0
- package/lib/snapshot-store/lineage-store.js +400 -0
- package/lib/snapshot-store/migrate.js +80 -0
- package/lib/snapshot-store/pairing.js +412 -0
- package/lib/snapshot-store/txn.js +63 -0
- package/lib/snapshot-store/vacuum.js +243 -0
- package/lib/store-lifecycle.js +13 -1
- package/lib/store-retry.js +34 -0
- package/lib/tool-edit.js +90 -44
- package/lib/tool-read.js +29 -1
- package/lib/tool-str-replace-editor.js +26 -18
- package/lib/tool-undo.js +25 -8
- package/lib/types/constants.d.ts +5 -2
- package/lib/types/contract.d.ts +76 -71
- package/lib/types/domain-errors.d.ts +410 -0
- package/lib/types/edit-response.d.ts +1 -1
- package/lib/types/file-encoding-state.d.ts +1 -0
- package/lib/types/file-view.d.ts +35 -6
- package/lib/types/hash-store.d.ts +38 -19
- package/lib/types/hashline/anchor-pipeline.d.ts +117 -36
- package/lib/types/hashline/hash-assign.d.ts +5 -5
- package/lib/types/hashline/hash.d.ts +1 -1
- package/lib/types/hashline/index.d.ts +2 -2
- package/lib/types/hashline/served-guard.d.ts +100 -0
- package/lib/types/index.d.ts +2 -2
- package/lib/types/mutation/engine.d.ts +49 -30
- package/lib/types/mutation.d.ts +1 -39
- package/lib/types/noop-guard.d.ts +4 -4
- package/lib/types/prompts.d.ts +1 -1
- package/lib/types/read-and-serve.d.ts +6 -0
- package/lib/types/sandbox.d.ts +1 -1
- package/lib/types/session-view.d.ts +38 -9
- package/lib/types/snapshot-store/index.d.ts +28 -0
- package/lib/types/snapshot-store/lineage-store.d.ts +96 -0
- package/lib/types/snapshot-store/migrate.d.ts +16 -0
- package/lib/types/snapshot-store/pairing.d.ts +99 -0
- package/lib/types/snapshot-store/txn.d.ts +12 -0
- package/lib/types/snapshot-store/vacuum.d.ts +79 -0
- package/lib/types/store-lifecycle.d.ts +0 -1
- package/lib/types/store-retry.d.ts +6 -0
- package/lib/types/tool-edit.d.ts +2 -2
- package/lib/types/tool-str-replace-editor.d.ts +2 -2
- package/lib/types/utils.d.ts +5 -6
- package/lib/types/workspace-context.d.ts +0 -1
- package/lib/undo-edit.js +27 -11
- package/lib/utils.js +12 -12
- package/lib/workspace-context.js +4 -8
- package/lib/write-hook.js +13 -4
- package/package.json +9 -10
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
*/
|
|
17
17
|
import { detectBom, isValidUtf8, decodeBytes, normalizeEncoding, top3Candidates, chardetTop3Candidates, } from "./encoding.js";
|
|
18
18
|
import { detectEnding, restoreEndings, toLF } from "./edit-diff.js";
|
|
19
|
+
import { DomainError, formatError } from "./domain-errors.js";
|
|
19
20
|
const encodingMemo = new Map();
|
|
20
21
|
const autoGuessFooterMemo = new Map();
|
|
21
22
|
export function getEncodingState(targetKey) {
|
|
@@ -51,11 +52,18 @@ export function invalidateIfStale(targetKey, currentVersion) {
|
|
|
51
52
|
// ---------------------------------------------------------------------------
|
|
52
53
|
// Pure helpers — no IO
|
|
53
54
|
// ---------------------------------------------------------------------------
|
|
54
|
-
export function
|
|
55
|
+
export function buildTop3Description(candidates) {
|
|
55
56
|
const candStr = candidates
|
|
56
57
|
.map((c) => `${c.encoding}("${c.sample.slice(0, 20).replace(/"/g, "'")}")`)
|
|
57
58
|
.join(", ");
|
|
58
|
-
return `
|
|
59
|
+
return `not readable UTF-8 text — top guesses: ${candStr}; try read({encoding: "<encoding>"}) or set DSH_BETTER_EDIT_AUTO_GUESS_ENCODING=true to auto-decode`;
|
|
60
|
+
}
|
|
61
|
+
export function buildTop3ErrorMessage(displayPath, candidates) {
|
|
62
|
+
return formatError("E_UNSUPPORTED_FILE", {
|
|
63
|
+
path: displayPath,
|
|
64
|
+
kind: "binary",
|
|
65
|
+
description: buildTop3Description(candidates),
|
|
66
|
+
});
|
|
59
67
|
}
|
|
60
68
|
function buildAutoGuessFooterFromCandidates(candidates) {
|
|
61
69
|
// chardet path vs heuristic path share same footer shape, just score vs confidence
|
|
@@ -95,7 +103,7 @@ function isMidConfidenceHeuristic(best, second) {
|
|
|
95
103
|
export async function decodeForOpen(bytes, config, opts = {}) {
|
|
96
104
|
const hint = opts.encodingHint ? normalizeEncoding(opts.encodingHint) : undefined;
|
|
97
105
|
if (opts.encodingHint && !hint) {
|
|
98
|
-
throw new
|
|
106
|
+
throw new DomainError("E_BAD_PAYLOAD", { message: `Unknown encoding: ${opts.encodingHint}` });
|
|
99
107
|
}
|
|
100
108
|
// 1) Explicit hint (Reopen with Encoding) — caller already chose, no autoGuess
|
|
101
109
|
if (hint) {
|
|
@@ -116,7 +124,11 @@ export async function decodeForOpen(bytes, config, opts = {}) {
|
|
|
116
124
|
// already handled; for explicit hint we decode slice with hint.
|
|
117
125
|
decoded = decodeBytes(slice, hint);
|
|
118
126
|
if (decoded === undefined)
|
|
119
|
-
throw new
|
|
127
|
+
throw new DomainError("E_UNSUPPORTED_FILE", {
|
|
128
|
+
path: opts.displayPath ?? "(unknown path)",
|
|
129
|
+
kind: "binary",
|
|
130
|
+
description: `cannot decode bytes as ${hint}`,
|
|
131
|
+
});
|
|
120
132
|
return {
|
|
121
133
|
text: decoded,
|
|
122
134
|
encoding: hint,
|
|
@@ -127,7 +139,11 @@ export async function decodeForOpen(bytes, config, opts = {}) {
|
|
|
127
139
|
}
|
|
128
140
|
decoded = decodeBytes(slice, hint);
|
|
129
141
|
if (decoded === undefined)
|
|
130
|
-
throw new
|
|
142
|
+
throw new DomainError("E_UNSUPPORTED_FILE", {
|
|
143
|
+
path: opts.displayPath ?? "(unknown path)",
|
|
144
|
+
kind: "binary",
|
|
145
|
+
description: `cannot decode bytes as ${hint}`,
|
|
146
|
+
});
|
|
131
147
|
return {
|
|
132
148
|
text: decoded,
|
|
133
149
|
encoding: hint,
|
|
@@ -237,7 +253,11 @@ export async function decodeForOpen(bytes, config, opts = {}) {
|
|
|
237
253
|
candidates = top3Candidates(bytes, config.supportedEncodings);
|
|
238
254
|
}
|
|
239
255
|
const display = opts.displayPath ?? "(unknown path)";
|
|
240
|
-
throw new
|
|
256
|
+
throw new DomainError("E_UNSUPPORTED_FILE", {
|
|
257
|
+
path: display,
|
|
258
|
+
kind: "binary",
|
|
259
|
+
description: buildTop3Description(candidates),
|
|
260
|
+
});
|
|
241
261
|
}
|
|
242
262
|
// ---------------------------------------------------------------------------
|
|
243
263
|
// Recording helpers — caller supplies targetKey + version after decode
|
|
@@ -270,7 +290,7 @@ export function prepareForSave(content, existingState, opts = {}) {
|
|
|
270
290
|
if (opts.encodingHint) {
|
|
271
291
|
const norm = normalizeEncoding(opts.encodingHint);
|
|
272
292
|
if (!norm)
|
|
273
|
-
throw new
|
|
293
|
+
throw new DomainError("E_BAD_PAYLOAD", { message: `Unknown encoding: ${opts.encodingHint}` });
|
|
274
294
|
const hasBOM = norm === "utf8bom";
|
|
275
295
|
const lineEnding = existingState?.lineEnding ?? detectEnding(content);
|
|
276
296
|
// Caller will write `content` as UTF-8 string; record new state for next read.
|
package/lib/file-view.js
CHANGED
|
@@ -25,11 +25,16 @@ import { SNIFF_BYTES, MAX_BYTES, MAX_READ_LINE_BYTES, eLargeFileMsg } from "./co
|
|
|
25
25
|
import { lineHashes, fmtRegion, HASH_SEP } from "./hashline/index.js";
|
|
26
26
|
import { HASH_SPACE } from "./hashline/hash-assign.js";
|
|
27
27
|
import { visLines, abortIf, errCode } from "./utils.js";
|
|
28
|
+
import { DomainError } from "./domain-errors.js";
|
|
28
29
|
import { detectEnding, toLF, stripBOM } from "./edit-diff.js";
|
|
29
30
|
import { resolveTarget, toCwd } from "./paths.js";
|
|
30
31
|
export const MAX_HASH_LINES = HASH_SPACE;
|
|
31
32
|
export const DEFAULT_MAX_LINES = 2000;
|
|
32
33
|
export const DEFAULT_MAX_BYTES = 50 * 1024;
|
|
34
|
+
// WHY: a multi-window read is still ONE tool result, so the window count is bounded — otherwise
|
|
35
|
+
// WHY: `windows` would multiply the auto-read budget by N — and every window draws on the same
|
|
36
|
+
// WHY: budget (buildWindowedPreview below). Co-located here with the other read budgets.
|
|
37
|
+
export const MAX_READ_WINDOWS = 16;
|
|
33
38
|
function splitLinesForCounting(content) {
|
|
34
39
|
if (content.length === 0)
|
|
35
40
|
return [];
|
|
@@ -165,7 +170,7 @@ export async function loadFileKindAndText(filePath, options) {
|
|
|
165
170
|
const buffer = Buffer.alloc(SNIFF_BYTES);
|
|
166
171
|
const { bytesRead } = await fileHandle.read(buffer, 0, SNIFF_BYTES, 0);
|
|
167
172
|
if (bytesRead === 0) {
|
|
168
|
-
return { kind: "text", text: "" };
|
|
173
|
+
return { kind: "text", text: "", stats: pathStat };
|
|
169
174
|
}
|
|
170
175
|
const sample = buffer.subarray(0, bytesRead);
|
|
171
176
|
const textBom = detectTextBom(sample);
|
|
@@ -220,6 +225,7 @@ export async function loadFileKindAndText(filePath, options) {
|
|
|
220
225
|
return {
|
|
221
226
|
kind: "text",
|
|
222
227
|
text: parts.join(""),
|
|
228
|
+
stats: pathStat,
|
|
223
229
|
...(hadUtf8DecodeErrors ? { hadUtf8DecodeErrors: true } : {}),
|
|
224
230
|
};
|
|
225
231
|
}
|
|
@@ -235,35 +241,48 @@ export async function valAccess(absolutePath, path, accessMode = constants.R_OK)
|
|
|
235
241
|
catch (error) {
|
|
236
242
|
const code = errCode(error);
|
|
237
243
|
if (code === "ENOENT") {
|
|
238
|
-
throw new
|
|
244
|
+
throw new DomainError("E_NOT_FOUND", { path });
|
|
239
245
|
}
|
|
240
246
|
if (code === "EACCES" || code === "EPERM") {
|
|
241
|
-
|
|
242
|
-
|
|
247
|
+
throw new DomainError("E_ACCESS", {
|
|
248
|
+
path,
|
|
249
|
+
kind: "denied",
|
|
250
|
+
access: accessMode & constants.W_OK ? "write" : "read",
|
|
251
|
+
});
|
|
243
252
|
}
|
|
244
253
|
if (code === "ELOOP") {
|
|
245
|
-
throw new
|
|
254
|
+
throw new DomainError("E_ACCESS", { path, kind: "symlink-loop" });
|
|
246
255
|
}
|
|
247
|
-
throw new
|
|
256
|
+
throw new DomainError("E_ACCESS", { path, kind: "unreachable" });
|
|
248
257
|
}
|
|
249
258
|
}
|
|
250
259
|
export function valKind(file, path) {
|
|
251
260
|
if (file.kind === "directory") {
|
|
252
|
-
throw new
|
|
261
|
+
throw new DomainError("E_UNSUPPORTED_FILE", { path, kind: "directory" });
|
|
253
262
|
}
|
|
254
263
|
if (file.kind === "binary") {
|
|
255
|
-
throw new
|
|
264
|
+
throw new DomainError("E_UNSUPPORTED_FILE", {
|
|
265
|
+
path,
|
|
266
|
+
kind: "binary",
|
|
267
|
+
description: file.description,
|
|
268
|
+
});
|
|
256
269
|
}
|
|
257
270
|
if (file.kind === "image") {
|
|
258
|
-
throw new
|
|
271
|
+
throw new DomainError("E_UNSUPPORTED_FILE", { path, kind: "image" });
|
|
259
272
|
}
|
|
260
273
|
}
|
|
261
274
|
function fmtSnapId(canonicalPath, info) {
|
|
262
275
|
return `v2|${canonicalPath}|${info.ino}|${info.mtimeMs}|${info.ctimeMs}|${info.size}`;
|
|
263
276
|
}
|
|
264
|
-
export async function fileSnap(absolutePath) {
|
|
277
|
+
export async function fileSnap(absolutePath, preloadedStats) {
|
|
265
278
|
const canonicalPath = await resolveTarget(absolutePath);
|
|
266
|
-
|
|
279
|
+
// FU-6 (port of pi-better-edit@2334352, stat consolidation; upstream's `checksum` third
|
|
280
|
+
// parameter belongs to ADR-0013, which this tree does not carry — fmtSnapId has no checksum
|
|
281
|
+
// segment — so preloadedStats lands as the second argument):
|
|
282
|
+
// WHY: the load path stat'd this same canonical path to size the file and reject directories, so
|
|
283
|
+
// WHY: its `Stats` is authoritative for the snapshot id; re-stat'ing could only disagree with the
|
|
284
|
+
// WHY: bytes the caller has already read and hashed.
|
|
285
|
+
const stats = preloadedStats ?? (await fsStat(canonicalPath));
|
|
267
286
|
return {
|
|
268
287
|
snapshotId: fmtSnapId(canonicalPath, stats),
|
|
269
288
|
ino: stats.ino,
|
|
@@ -327,20 +346,260 @@ function normPosInt(value, name) {
|
|
|
327
346
|
if (value === undefined)
|
|
328
347
|
return undefined;
|
|
329
348
|
if (!Number.isInteger(value) || value < 1) {
|
|
330
|
-
throw new
|
|
349
|
+
throw new DomainError("E_BAD_PAYLOAD", {
|
|
350
|
+
message: `Read request field "${name}" must be a positive integer.`,
|
|
351
|
+
});
|
|
331
352
|
}
|
|
332
353
|
return value;
|
|
333
354
|
}
|
|
355
|
+
function normReqInt(value, name) {
|
|
356
|
+
const normalized = normPosInt(value, name);
|
|
357
|
+
if (normalized === undefined) {
|
|
358
|
+
throw new DomainError("E_BAD_PAYLOAD", {
|
|
359
|
+
message: `Read request field "${name}" must be a positive integer.`,
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
return normalized;
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* The windows rule, owned here so the preview and the serve-side full-read contract
|
|
366
|
+
* cannot disagree: `undefined` and `[]` both mean "no windows" — the caller falls back to the
|
|
367
|
+
* single-window `offset`/`limit` contract, so an empty array stays backward compatible.
|
|
368
|
+
*
|
|
369
|
+
* WHY (moved with the rule from read-and-serve): `windows: []` falls back to a
|
|
370
|
+
* full read in the preview, so the full-read contract has to follow the same rule — otherwise an
|
|
371
|
+
* empty array silently skips the drift clear that a full read owes. A non-empty multi-window
|
|
372
|
+
* read serves sparse rows, never the full file.
|
|
373
|
+
*/
|
|
374
|
+
export function hasRequestedWindows(windows) {
|
|
375
|
+
return windows !== undefined && windows.length > 0;
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Validates a `windows` request; the `undefined`/`[]` → no-windows mapping is owned by
|
|
379
|
+
* `hasRequestedWindows`.
|
|
380
|
+
*/
|
|
381
|
+
function normWindows(windows) {
|
|
382
|
+
if (!hasRequestedWindows(windows))
|
|
383
|
+
return undefined;
|
|
384
|
+
if (windows.length > MAX_READ_WINDOWS) {
|
|
385
|
+
throw new DomainError("E_BAD_PAYLOAD", {
|
|
386
|
+
message: `Read request accepts at most ${MAX_READ_WINDOWS} windows.`,
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
return windows.map((window, index) => {
|
|
390
|
+
if (window === null || typeof window !== "object") {
|
|
391
|
+
throw new DomainError("E_BAD_PAYLOAD", {
|
|
392
|
+
message: `Read request field "windows[${index}]" must be an object with offset and limit.`,
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
return {
|
|
396
|
+
offset: normReqInt(window.offset, `windows[${index}].offset`),
|
|
397
|
+
limit: normReqInt(window.limit, `windows[${index}].limit`),
|
|
398
|
+
};
|
|
399
|
+
});
|
|
400
|
+
}
|
|
334
401
|
export function formatPaginationHint(startLine, endLine, totalLines, nextOffset, byteLimit) {
|
|
335
402
|
const sizeSuffix = byteLimit !== undefined ? ` (${formatSize(byteLimit)} limit)` : "";
|
|
336
403
|
return `[Showing lines ${startLine}-${endLine} of ${totalLines}${sizeSuffix}. Use offset=${nextOffset} to continue.]`;
|
|
337
404
|
}
|
|
405
|
+
// FU-6 (port of pi-better-edit@2334352): the oversized and normal render paths were extracted
|
|
406
|
+
// from fmtReadPreview's body into the builders below — the multi-window sections must route
|
|
407
|
+
// through the SAME pipeline a single-window read uses, on ONE shared budget (same render arms,
|
|
408
|
+
// budget-relative measurement — see buildWindowSection). Single-window behavior is unchanged
|
|
409
|
+
// (pinned by read-preview tests).
|
|
410
|
+
function oversizedWarning(oversized) {
|
|
411
|
+
const lineLabel = oversized.length === 1
|
|
412
|
+
? `Line ${oversized[0].lineNumber}`
|
|
413
|
+
: `Lines ${oversized.map((row) => row.lineNumber).join(", ")}`;
|
|
414
|
+
const verb = oversized.length === 1 ? "exceeds" : "exceed";
|
|
415
|
+
const addresses = oversized.map((row) => `${row.lineNumber}p`).join(";");
|
|
416
|
+
return { lineLabel, verb, addresses };
|
|
417
|
+
}
|
|
418
|
+
function buildOversizedPreview(params) {
|
|
419
|
+
const { rowSizes, selected, selectedHashes, startLine, totalLines, maxBytes, maxTruncLines } = params;
|
|
420
|
+
const oversized = rowSizes.filter((row) => row.bytes > maxBytes);
|
|
421
|
+
const rows = rowSizes.map((row, index) => row.bytes > maxBytes
|
|
422
|
+
? `[Line ${row.lineNumber} is ${formatSize(row.bytes)}, exceeds ${formatSize(maxBytes)}; content not shown. Use bash: sed -n '${row.lineNumber}p' <path> | head -c ${maxBytes}]`
|
|
423
|
+
: fmtRegion([selectedHashes[index]], [selected[index]]));
|
|
424
|
+
const skippedTruncation = truncateHead(rows.join("\n"), { maxBytes, maxLines: maxTruncLines });
|
|
425
|
+
const shownRowCount = skippedTruncation.content === "" ? 0 : skippedTruncation.content.split("\n").length;
|
|
426
|
+
const lastShownLine = shownRowCount > 0 ? startLine + shownRowCount - 1 : startLine - 1;
|
|
427
|
+
const { lineLabel, verb, addresses } = oversizedWarning(oversized);
|
|
428
|
+
const warning = `[${lineLabel} ${verb} ${formatSize(maxBytes)}; content not shown because hashline anchors require full lines. Inspect with bash: sed -n '${addresses}' <path> | head -c ${maxBytes}]`;
|
|
429
|
+
let preview = skippedTruncation.content;
|
|
430
|
+
let nextOffset;
|
|
431
|
+
if (shownRowCount > 0 && skippedTruncation.truncated) {
|
|
432
|
+
nextOffset = lastShownLine + 1;
|
|
433
|
+
preview += `\n\n${warning}\n${formatPaginationHint(startLine, lastShownLine, totalLines, nextOffset, skippedTruncation.maxBytes)}`;
|
|
434
|
+
}
|
|
435
|
+
else if (shownRowCount > 0 && params.hintRemainder !== false && lastShownLine < totalLines) {
|
|
436
|
+
nextOffset = lastShownLine + 1;
|
|
437
|
+
preview += `\n\n${warning}\n${formatPaginationHint(startLine, lastShownLine, totalLines, nextOffset)}`;
|
|
438
|
+
}
|
|
439
|
+
else {
|
|
440
|
+
preview += `\n\n${warning}`;
|
|
441
|
+
}
|
|
442
|
+
const served = [];
|
|
443
|
+
for (let index = 0; index < shownRowCount; index++) {
|
|
444
|
+
if (rowSizes[index].bytes <= maxBytes) {
|
|
445
|
+
served.push({
|
|
446
|
+
position: startLine - 1 + index,
|
|
447
|
+
hash: selectedHashes[index],
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
return {
|
|
452
|
+
text: preview,
|
|
453
|
+
truncation: skippedTruncation.truncated ? skippedTruncation : undefined,
|
|
454
|
+
...(nextOffset !== undefined ? { nextOffset } : {}),
|
|
455
|
+
served,
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
function buildNormalPreview(params) {
|
|
459
|
+
const { formatted, startLine, endIdx, totalLines, maxBytes, maxTruncLines, selectedHashes } = params;
|
|
460
|
+
const truncation = truncateHead(formatted, { maxBytes, maxLines: maxTruncLines });
|
|
461
|
+
let preview = truncation.content;
|
|
462
|
+
let nextOffset;
|
|
463
|
+
if (truncation.truncated) {
|
|
464
|
+
const endLineDisplay = startLine + truncation.outputLines - 1;
|
|
465
|
+
nextOffset = endLineDisplay + 1;
|
|
466
|
+
if (truncation.truncatedBy === "lines") {
|
|
467
|
+
preview += `\n\n${formatPaginationHint(startLine, endLineDisplay, totalLines, nextOffset)}`;
|
|
468
|
+
}
|
|
469
|
+
else {
|
|
470
|
+
preview += `\n\n${formatPaginationHint(startLine, endLineDisplay, totalLines, nextOffset, truncation.maxBytes)}`;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
else if (params.hintRemainder !== false && endIdx < totalLines) {
|
|
474
|
+
nextOffset = endIdx + 1;
|
|
475
|
+
preview += `\n\n${formatPaginationHint(startLine, endIdx, totalLines, nextOffset)}`;
|
|
476
|
+
}
|
|
477
|
+
const served = [];
|
|
478
|
+
for (let index = 0; index < truncation.outputLines; index++) {
|
|
479
|
+
served.push({
|
|
480
|
+
position: startLine - 1 + index,
|
|
481
|
+
hash: selectedHashes[index],
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
return { preview, nextOffset, truncation, served };
|
|
485
|
+
}
|
|
486
|
+
function windowHeader(startLine, endLine, totalLines) {
|
|
487
|
+
return `=== Lines ${startLine}-${endLine} of ${totalLines} ===`;
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* Renders one window through the same oversized/truncation pipeline a single-window read uses, but
|
|
491
|
+
* against the shared budget actually LEFT to this window: `maxBytes`/`maxTruncLines` are the
|
|
492
|
+
* caller's remaining bytes/lines, not the single-read caps. The render arm is identical while the
|
|
493
|
+
* measurement is not — a 120KB line under a 200KB single-read cap is reported oversized as
|
|
494
|
+
* "exceeds 80KB" once earlier windows spent the shared budget down to 80KB. A window degrades like
|
|
495
|
+
* the same range read alone only while the shared budget is still unspent.
|
|
496
|
+
*/
|
|
497
|
+
function buildWindowSection(params) {
|
|
498
|
+
const { rowSizes, selected, selectedHashes, startLine, endIdx, totalLines, maxBytes, maxTruncLines, } = params;
|
|
499
|
+
if (rowSizes.some((row) => row.bytes > maxBytes)) {
|
|
500
|
+
return buildOversizedPreview({
|
|
501
|
+
rowSizes,
|
|
502
|
+
selected,
|
|
503
|
+
selectedHashes,
|
|
504
|
+
startLine,
|
|
505
|
+
totalLines,
|
|
506
|
+
maxBytes,
|
|
507
|
+
maxTruncLines,
|
|
508
|
+
hintRemainder: false,
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
const normal = buildNormalPreview({
|
|
512
|
+
formatted: fmtRegion(selectedHashes, selected),
|
|
513
|
+
startLine,
|
|
514
|
+
endIdx,
|
|
515
|
+
totalLines,
|
|
516
|
+
maxBytes,
|
|
517
|
+
maxTruncLines,
|
|
518
|
+
selectedHashes,
|
|
519
|
+
hintRemainder: false,
|
|
520
|
+
});
|
|
521
|
+
return {
|
|
522
|
+
text: normal.preview,
|
|
523
|
+
truncation: normal.truncation.truncated ? normal.truncation : undefined,
|
|
524
|
+
served: normal.served,
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* Multi-window read (one tool result, several disjoint ranges). Sections render in the caller's
|
|
529
|
+
* order — the order is part of the request, so it is never sorted — while every window draws on ONE
|
|
530
|
+
* shared byte/line budget so N windows cannot multiply the auto-read budget by N. Rows are served
|
|
531
|
+
* only for the lines actually shown, and overlapping windows collapse to one served row per line.
|
|
532
|
+
*/
|
|
533
|
+
function buildWindowedPreview(params) {
|
|
534
|
+
const { windows, allLines, allHashes, totalLines, maxBytes, maxTruncLines } = params;
|
|
535
|
+
const sections = [];
|
|
536
|
+
const hashByPosition = new Map();
|
|
537
|
+
let truncation;
|
|
538
|
+
let remainingBytes = maxBytes;
|
|
539
|
+
let remainingLines = maxTruncLines;
|
|
540
|
+
for (const window of windows) {
|
|
541
|
+
if (window.offset > totalLines) {
|
|
542
|
+
sections.push(`Offset ${window.offset} is beyond end of file (${totalLines} lines total). Use offset=1 to read from the start, or offset=${totalLines} to read the last line.`);
|
|
543
|
+
continue;
|
|
544
|
+
}
|
|
545
|
+
const endIdx = Math.min(window.offset - 1 + window.limit, totalLines);
|
|
546
|
+
const header = windowHeader(window.offset, endIdx, totalLines);
|
|
547
|
+
const selected = allLines.slice(window.offset - 1, endIdx);
|
|
548
|
+
const selectedHashes = allHashes.slice(window.offset - 1, endIdx);
|
|
549
|
+
if (remainingBytes <= 0 || remainingLines <= 0) {
|
|
550
|
+
sections.push(`${header}\n[Read budget exhausted; this window is not shown. Re-read it on its own.]`);
|
|
551
|
+
// WHY: `metrics.truncated` must be honest when the shared budget cut a window away, so the
|
|
552
|
+
// WHY: same function that reports truncation elsewhere derives it from the budget actually spent.
|
|
553
|
+
const skipped = truncateHead(fmtRegion(selectedHashes, selected), {
|
|
554
|
+
maxBytes: Math.max(0, remainingBytes),
|
|
555
|
+
maxLines: Math.max(0, remainingLines),
|
|
556
|
+
});
|
|
557
|
+
if (truncation === undefined && skipped.truncated)
|
|
558
|
+
truncation = skipped;
|
|
559
|
+
continue;
|
|
560
|
+
}
|
|
561
|
+
const rowSizes = selected.map((line, index) => ({
|
|
562
|
+
lineNumber: window.offset + index,
|
|
563
|
+
bytes: Buffer.byteLength(`${selectedHashes[index]}${HASH_SEP}${line}`, "utf-8"),
|
|
564
|
+
}));
|
|
565
|
+
const built = buildWindowSection({
|
|
566
|
+
rowSizes,
|
|
567
|
+
selected,
|
|
568
|
+
selectedHashes,
|
|
569
|
+
startLine: window.offset,
|
|
570
|
+
endIdx,
|
|
571
|
+
totalLines,
|
|
572
|
+
maxBytes: remainingBytes,
|
|
573
|
+
maxTruncLines: remainingLines,
|
|
574
|
+
});
|
|
575
|
+
sections.push(`${header}\n${built.text}`);
|
|
576
|
+
for (const row of built.served)
|
|
577
|
+
hashByPosition.set(row.position, row.hash);
|
|
578
|
+
remainingLines -= built.text === "" ? 0 : built.text.split("\n").length;
|
|
579
|
+
remainingBytes -= Buffer.byteLength(`${built.text}${header}`, "utf-8");
|
|
580
|
+
if (truncation === undefined && built.truncation)
|
|
581
|
+
truncation = built.truncation;
|
|
582
|
+
}
|
|
583
|
+
return {
|
|
584
|
+
text: sections.join("\n\n"),
|
|
585
|
+
...(truncation ? { truncation } : {}),
|
|
586
|
+
// WHY: a multi-window request is N discrete slices, not one stream, so the result carries no root
|
|
587
|
+
// WHY: `nextOffset`: a scalar would invite `offset = nextOffset` and silently re-read a window the
|
|
588
|
+
// WHY: caller never asked to continue. A truncated window says so in its own section text.
|
|
589
|
+
served: [...hashByPosition.entries()]
|
|
590
|
+
.sort((left, right) => left[0] - right[0])
|
|
591
|
+
.map(([position, hash]) => ({ position, hash })),
|
|
592
|
+
};
|
|
593
|
+
}
|
|
338
594
|
export async function fmtReadPreview(text, options, precomputedHashes, path, maxLineBytes = MAX_READ_LINE_BYTES, maxTruncLines = DEFAULT_MAX_LINES) {
|
|
339
595
|
const allLines = visLines(text);
|
|
340
596
|
const totalLines = allLines.length;
|
|
341
597
|
const startLine = normPosInt(options.offset, "offset") ?? 1;
|
|
598
|
+
const windows = normWindows(options.windows);
|
|
342
599
|
if (totalLines === 0) {
|
|
343
|
-
|
|
600
|
+
// FU-6 (2334352): an empty-file `windows` request reports the first window's offset.
|
|
601
|
+
const emptyStart = windows?.[0]?.offset ?? startLine;
|
|
602
|
+
if (emptyStart === 1) {
|
|
344
603
|
const allHashes = precomputedHashes ?? (await (path ? lineHashes(text, path) : lineHashes(text)));
|
|
345
604
|
const emptyLineHash = allHashes[0];
|
|
346
605
|
return {
|
|
@@ -349,10 +608,23 @@ export async function fmtReadPreview(text, options, precomputedHashes, path, max
|
|
|
349
608
|
};
|
|
350
609
|
}
|
|
351
610
|
return {
|
|
352
|
-
text: `Offset ${
|
|
611
|
+
text: `Offset ${emptyStart} is beyond end of file (0 lines total). The file is empty. Use edit to insert content.`,
|
|
353
612
|
served: [],
|
|
354
613
|
};
|
|
355
614
|
}
|
|
615
|
+
// FU-6 (2334352): `windows` wins when both are given — the dispatch runs before the
|
|
616
|
+
// single-window startLine validation, so a past-EOF offset in one window never fails the read.
|
|
617
|
+
if (windows) {
|
|
618
|
+
const allHashes = precomputedHashes ?? (await (path ? lineHashes(text, path) : lineHashes(text)));
|
|
619
|
+
return buildWindowedPreview({
|
|
620
|
+
windows,
|
|
621
|
+
allLines,
|
|
622
|
+
allHashes,
|
|
623
|
+
totalLines,
|
|
624
|
+
maxBytes: maxLineBytes,
|
|
625
|
+
maxTruncLines,
|
|
626
|
+
});
|
|
627
|
+
}
|
|
356
628
|
if (startLine > totalLines) {
|
|
357
629
|
return {
|
|
358
630
|
text: `Offset ${startLine} is beyond end of file (${totalLines} lines total). Use offset=1 to read from the start, or offset=${totalLines} to read the last line.`,
|
|
@@ -371,79 +643,30 @@ export async function fmtReadPreview(text, options, precomputedHashes, path, max
|
|
|
371
643
|
bytes: Buffer.byteLength(`${selectedHashes[index]}${HASH_SEP}${line}`, "utf-8"),
|
|
372
644
|
}));
|
|
373
645
|
if (rowSizes.some((row) => row.bytes > maxBytes)) {
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
646
|
+
return buildOversizedPreview({
|
|
647
|
+
rowSizes,
|
|
648
|
+
selected,
|
|
649
|
+
selectedHashes,
|
|
650
|
+
startLine,
|
|
651
|
+
totalLines,
|
|
379
652
|
maxBytes,
|
|
380
|
-
|
|
653
|
+
maxTruncLines,
|
|
381
654
|
});
|
|
382
|
-
const shownRowCount = skippedTruncation.content === "" ? 0 : skippedTruncation.content.split("\n").length;
|
|
383
|
-
const lastShownLine = shownRowCount > 0 ? startLine + shownRowCount - 1 : startLine - 1;
|
|
384
|
-
const lineLabel = oversized.length === 1
|
|
385
|
-
? `Line ${oversized[0].lineNumber}`
|
|
386
|
-
: `Lines ${oversized.map((row) => row.lineNumber).join(", ")}`;
|
|
387
|
-
const verb = oversized.length === 1 ? "exceeds" : "exceed";
|
|
388
|
-
const addresses = oversized.map((row) => `${row.lineNumber}p`).join(";");
|
|
389
|
-
const warning = `[${lineLabel} ${verb} ${formatSize(maxBytes)}; content not shown because hashline anchors require full lines. Inspect with bash: sed -n '${addresses}' <path> | head -c ${maxBytes}]`;
|
|
390
|
-
let preview = skippedTruncation.content;
|
|
391
|
-
let nextOffset;
|
|
392
|
-
if (shownRowCount > 0 && (skippedTruncation.truncated || lastShownLine < totalLines)) {
|
|
393
|
-
nextOffset = lastShownLine + 1;
|
|
394
|
-
preview += `\n\n${warning}\n${formatPaginationHint(startLine, lastShownLine, totalLines, nextOffset, skippedTruncation.truncated ? skippedTruncation.maxBytes : undefined)}`;
|
|
395
|
-
}
|
|
396
|
-
else {
|
|
397
|
-
preview += `\n\n${warning}`;
|
|
398
|
-
}
|
|
399
|
-
const served = [];
|
|
400
|
-
for (let index = 0; index < shownRowCount; index++) {
|
|
401
|
-
if (rowSizes[index].bytes <= maxBytes) {
|
|
402
|
-
served.push({
|
|
403
|
-
position: startLine - 1 + index,
|
|
404
|
-
hash: selectedHashes[index],
|
|
405
|
-
});
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
return {
|
|
409
|
-
text: preview,
|
|
410
|
-
truncation: skippedTruncation.truncated ? skippedTruncation : undefined,
|
|
411
|
-
...(nextOffset !== undefined ? { nextOffset } : {}),
|
|
412
|
-
served,
|
|
413
|
-
};
|
|
414
655
|
}
|
|
415
|
-
const
|
|
656
|
+
const normal = buildNormalPreview({
|
|
657
|
+
formatted,
|
|
658
|
+
startLine,
|
|
659
|
+
endIdx,
|
|
660
|
+
totalLines,
|
|
416
661
|
maxBytes,
|
|
417
|
-
|
|
662
|
+
maxTruncLines,
|
|
663
|
+
selectedHashes,
|
|
418
664
|
});
|
|
419
|
-
let preview = truncation.content;
|
|
420
|
-
let nextOffset;
|
|
421
|
-
if (truncation.truncated) {
|
|
422
|
-
const endLineDisplay = startLine + truncation.outputLines - 1;
|
|
423
|
-
nextOffset = endLineDisplay + 1;
|
|
424
|
-
if (truncation.truncatedBy === "lines") {
|
|
425
|
-
preview += `\n\n${formatPaginationHint(startLine, endLineDisplay, totalLines, nextOffset)}`;
|
|
426
|
-
}
|
|
427
|
-
else {
|
|
428
|
-
preview += `\n\n${formatPaginationHint(startLine, endLineDisplay, totalLines, nextOffset, truncation.maxBytes)}`;
|
|
429
|
-
}
|
|
430
|
-
}
|
|
431
|
-
else if (endIdx < totalLines) {
|
|
432
|
-
nextOffset = endIdx + 1;
|
|
433
|
-
preview += `\n\n${formatPaginationHint(startLine, endIdx, totalLines, nextOffset)}`;
|
|
434
|
-
}
|
|
435
|
-
const served = [];
|
|
436
|
-
for (let index = 0; index < truncation.outputLines; index++) {
|
|
437
|
-
served.push({
|
|
438
|
-
position: startLine - 1 + index,
|
|
439
|
-
hash: selectedHashes[index],
|
|
440
|
-
});
|
|
441
|
-
}
|
|
442
665
|
return {
|
|
443
|
-
text: preview,
|
|
444
|
-
truncation: truncation.truncated ? truncation : undefined,
|
|
445
|
-
...(nextOffset !== undefined ? { nextOffset } : {}),
|
|
446
|
-
served,
|
|
666
|
+
text: normal.preview,
|
|
667
|
+
truncation: normal.truncation.truncated ? normal.truncation : undefined,
|
|
668
|
+
...(normal.nextOffset !== undefined ? { nextOffset: normal.nextOffset } : {}),
|
|
669
|
+
served: normal.served,
|
|
447
670
|
};
|
|
448
671
|
}
|
|
449
672
|
export async function preview(content, hashes, opts = {}, absolutePath) {
|
|
@@ -463,7 +686,7 @@ export async function readView(io, path, cwd, opts = {}) {
|
|
|
463
686
|
retiredHashes: opts.retiredHashes,
|
|
464
687
|
previous: opts.previous,
|
|
465
688
|
});
|
|
466
|
-
const r = await fmtReadPreview(normalized, { offset: opts.offset, limit: opts.limit }, fileHashes, absolutePath);
|
|
689
|
+
const r = await fmtReadPreview(normalized, { offset: opts.offset, limit: opts.limit, windows: opts.windows }, fileHashes, absolutePath);
|
|
467
690
|
return {
|
|
468
691
|
text: r.text,
|
|
469
692
|
hashes: fileHashes,
|
package/lib/fs-bridge.js
CHANGED
|
@@ -21,6 +21,7 @@ import { fileSnap } from "./file-reader.js";
|
|
|
21
21
|
import { resolveTarget, toCwd } from "./paths.js";
|
|
22
22
|
import { decodeForOpen, recordOpenState, recordFooter, getEncodingState as _getEncodingState, setEncodingState as _setEncodingState, clearEncodingState as _clearEncodingState, getAutoGuessFooter as _getAutoGuessFooter, setAutoGuessFooter as _setAutoGuessFooter, clearAutoGuessFooter as _clearAutoGuessFooter, invalidateIfStale, prepareForSave, } from "./file-encoding-state.js";
|
|
23
23
|
import { codeOf } from "./utils.js";
|
|
24
|
+
import { DomainError } from "./domain-errors.js";
|
|
24
25
|
export { _getEncodingState as getEncodingState, _setEncodingState as setEncodingState, _clearEncodingState as clearEncodingState, _getAutoGuessFooter as getAutoGuessFooter, _setAutoGuessFooter as setAutoGuessFooter, _clearAutoGuessFooter as clearAutoGuessFooter, };
|
|
25
26
|
// Keep alias for tests that import getAutoGuessFooter via fs-bridge
|
|
26
27
|
export function getAutoGuessFooterCompat(k) {
|
|
@@ -37,25 +38,40 @@ export function mapFsError(error, displayPath) {
|
|
|
37
38
|
if (error instanceof Error && typeof error.code === "string") {
|
|
38
39
|
const code = error.code;
|
|
39
40
|
if (code === "FS_NOT_FOUND") {
|
|
40
|
-
throw new
|
|
41
|
+
throw new DomainError("E_NOT_FOUND", { path: displayPath });
|
|
41
42
|
}
|
|
42
43
|
if (code === "FS_PERMISSION_DENIED") {
|
|
43
|
-
throw new
|
|
44
|
+
throw new DomainError("E_ACCESS", { path: displayPath, kind: "denied" });
|
|
44
45
|
}
|
|
45
46
|
if (code === "FS_NOT_TEXT" || code === "FS_NOT_REGULAR_FILE") {
|
|
46
|
-
throw new
|
|
47
|
+
throw new DomainError("E_UNSUPPORTED_FILE", {
|
|
48
|
+
path: displayPath,
|
|
49
|
+
kind: "binary",
|
|
50
|
+
description: 'not a readable UTF-8 text file (try read({encoding: "gbk"}) or enable autoGuessEncoding)',
|
|
51
|
+
});
|
|
47
52
|
}
|
|
48
53
|
if (code === "FS_BAD_ENCODING") {
|
|
49
|
-
throw new
|
|
54
|
+
throw new DomainError("E_BAD_PAYLOAD", {
|
|
55
|
+
message: `Unknown encoding for ${displayPath}. Supported: utf8, gbk, big5, shift_jis, euc-kr, windows-1251, iso-8859-1`,
|
|
56
|
+
});
|
|
50
57
|
}
|
|
51
58
|
if (code === "FS_DECODE_FAILED") {
|
|
52
|
-
throw new
|
|
59
|
+
throw new DomainError("E_UNSUPPORTED_FILE", {
|
|
60
|
+
path: displayPath,
|
|
61
|
+
kind: "binary",
|
|
62
|
+
description: "bytes cannot be decoded with requested encoding",
|
|
63
|
+
});
|
|
53
64
|
}
|
|
54
65
|
if (code === "FS_STALE_VERSION") {
|
|
55
|
-
throw new
|
|
66
|
+
throw new DomainError("E_STALE_RANGE", {
|
|
67
|
+
headline: "The file changed on disk since it was read (version guard rejected the write). Call read() to get fresh anchors, then retry.",
|
|
68
|
+
servedRows: [],
|
|
69
|
+
servedBlock: "",
|
|
70
|
+
// F7: row-less and read-required — no `Current range:` section, no retry hint.
|
|
71
|
+
});
|
|
56
72
|
}
|
|
57
73
|
if (code === "FS_NOT_OBSERVED") {
|
|
58
|
-
throw new
|
|
74
|
+
throw new DomainError("E_BLIND_REPLACE", { path: displayPath, command: "write" });
|
|
59
75
|
}
|
|
60
76
|
if (code === "FS_ABORTED") {
|
|
61
77
|
throw new Error("Operation aborted");
|