dsh-better-edit 0.1.9 → 0.2.1
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 +32 -0
- package/README.md +168 -52
- package/README.zh.md +122 -46
- package/assets/logo.svg +183 -18
- package/lib/contract.js +95 -0
- package/lib/drift.js +1 -1
- package/lib/edit-diff.js +2 -2
- package/lib/edit-engine.js +456 -0
- package/lib/edit-pipeline.js +41 -116
- package/lib/file-reader.js +1 -2
- package/lib/fs-bridge.js +2 -2
- package/lib/fs-write.js +3 -46
- package/lib/guidance.js +282 -0
- package/lib/hash-store.js +246 -13
- package/lib/hashline/apply.js +2 -2
- package/lib/hashline/hash.js +16 -206
- package/lib/hashline/index.js +4 -3
- package/lib/hashline/parse.js +1 -1
- package/lib/hashline/pure.js +213 -0
- package/lib/hashline/resolve.js +1 -5
- package/lib/hashline/served.js +2 -2
- package/lib/index.js +48 -32
- package/lib/paths.js +55 -1
- package/lib/prompts.js +53 -49
- package/lib/read-and-serve.js +46 -0
- package/lib/schema.js +1 -1
- package/lib/served-store.js +144 -183
- package/lib/tool-batch-edit.js +28 -280
- package/lib/tool-edit.js +37 -32
- package/lib/tool-read.js +8 -31
- package/lib/tool-undo.js +4 -13
- package/lib/types/contract.d.ts +39 -0
- package/lib/types/edit-engine.d.ts +179 -0
- package/lib/types/edit-pipeline.d.ts +10 -17
- package/lib/types/fs-write.d.ts +0 -1
- package/lib/types/guidance.d.ts +98 -0
- package/lib/types/hash-store.d.ts +73 -25
- package/lib/types/hashline/hash.d.ts +8 -13
- package/lib/types/hashline/index.d.ts +4 -3
- package/lib/types/hashline/pure.d.ts +26 -0
- package/lib/types/hashline/resolve.d.ts +0 -1
- package/lib/types/index.d.ts +4 -0
- package/lib/types/paths.d.ts +9 -0
- package/lib/types/prompts.d.ts +19 -9
- package/lib/types/read-and-serve.d.ts +39 -0
- package/lib/types/schema.d.ts +2 -16
- package/lib/types/served-store.d.ts +63 -32
- package/lib/types/tool-batch-edit.d.ts +4 -1
- package/lib/types/tool-undo.d.ts +1 -1
- package/lib/undo-edit.js +16 -1
- package/lib/write-hook.js +30 -50
- package/package.json +5 -3
- package/lib/served-state.js +0 -34
- package/lib/snapshot-store.js +0 -108
- package/lib/types/served-state.d.ts +0 -3
- package/lib/types/snapshot-store.d.ts +0 -14
- package/lib/types/undo-store.d.ts +0 -14
- package/lib/undo-store.js +0 -43
package/lib/tool-batch-edit.js
CHANGED
|
@@ -2,60 +2,22 @@
|
|
|
2
2
|
* The dsh `batch_edit` tool: several hash-anchored edits in one all-or-nothing
|
|
3
3
|
* call. Items targeting the same file are applied in order against the served
|
|
4
4
|
* state; any failing item rejects the whole batch with nothing written, and
|
|
5
|
-
* the failing item's current range is echoed as fresh serves.
|
|
5
|
+
* the failing item's current range is echoed as fresh serves. The per-file
|
|
6
|
+
* sequencing and the persist-undo → write → restore transaction live in the
|
|
7
|
+
* edit engine; this module owns request preparation and result rendering.
|
|
6
8
|
* @module dsh-better-edit/tool-batch-edit
|
|
7
9
|
*/
|
|
8
10
|
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import { scanDrift } from "./drift.js";
|
|
12
|
-
import { abortIf, isRec, normalizeFilePath, rejectUnknownFields, splitLines, } from "./utils.js";
|
|
11
|
+
import { abortIf, isRec, normalizeFilePath, splitLines, } from "./utils.js";
|
|
12
|
+
import { assertBatchEditRequest, } from "./contract.js";
|
|
13
13
|
import { normReq } from "./edit-normalize.js";
|
|
14
|
-
import {
|
|
15
|
-
import { AnchorMismatchError, ServedRejectionError, buildRangeEcho, fmtServedRows, recordEchoServes, } from "./hashline/served.js";
|
|
14
|
+
import { persistUndoAndWrite, resolveMissingPath, runFileEdits, } from "./edit-engine.js";
|
|
16
15
|
import { buildBatchResult } from "./edit-response.js";
|
|
17
|
-
import {
|
|
18
|
-
import { loadServed, recordServedTruncated } from "./served-store.js";
|
|
19
|
-
import { BATCH_EDIT_MAX_ITEMS, NOOP_LOOP_THRESHOLD } from "./constants.js";
|
|
20
|
-
import { collectRemovedHashes, countLineChanges, resolveMissingPath, } from "./edit-pipeline.js";
|
|
21
|
-
import { clearNoopLoop, noopPayloadKey, trackNoopPayload, } from "./noop-guard.js";
|
|
16
|
+
import { recordServedTruncated } from "./served-store.js";
|
|
22
17
|
import { BATCH_EDIT_DESCRIPTION } from "./prompts.js";
|
|
23
18
|
import { pathSchema, removeFromSchema, removeToSchema, replacementTextSchema, } from "./schema.js";
|
|
24
19
|
import { execCwd, execSessionKey } from "./dsh-context.js";
|
|
25
20
|
import { withWorkspace } from "./workspace.js";
|
|
26
|
-
const BATCH_ITEM_KS = new Set([
|
|
27
|
-
"path",
|
|
28
|
-
"remove_from",
|
|
29
|
-
"remove_to",
|
|
30
|
-
"replacement_text",
|
|
31
|
-
]);
|
|
32
|
-
function assertBatchReq(request) {
|
|
33
|
-
if (!isRec(request)) {
|
|
34
|
-
throw new Error('[E_BAD_SHAPE] batch_edit request must be an object with an "edits" array.');
|
|
35
|
-
}
|
|
36
|
-
rejectUnknownFields(request, new Set(["edits", "sandbox_permissions", "justification"]), "batch_edit request");
|
|
37
|
-
if (!Array.isArray(request.edits) || request.edits.length === 0) {
|
|
38
|
-
throw new Error('[E_BAD_SHAPE] batch_edit request requires a non-empty "edits" array.');
|
|
39
|
-
}
|
|
40
|
-
if (request.edits.length > BATCH_EDIT_MAX_ITEMS) {
|
|
41
|
-
throw new Error(`[E_BAD_SHAPE] batch_edit accepts at most ${BATCH_EDIT_MAX_ITEMS} edits; got ${request.edits.length}. Split the batch.`);
|
|
42
|
-
}
|
|
43
|
-
request.edits.forEach((item, index) => {
|
|
44
|
-
if (!isRec(item)) {
|
|
45
|
-
throw new Error(`[E_BAD_SHAPE] edits[${index}] must be an object with remove_from, remove_to, and replacement_text.`);
|
|
46
|
-
}
|
|
47
|
-
rejectUnknownFields(item, BATCH_ITEM_KS, `edits[${index}]`);
|
|
48
|
-
if (typeof item.remove_from !== "string" ||
|
|
49
|
-
typeof item.remove_to !== "string" ||
|
|
50
|
-
typeof item.replacement_text !== "string") {
|
|
51
|
-
throw new Error(`[E_BAD_SHAPE] edits[${index}] requires "remove_from", "remove_to", and "replacement_text" strings.`);
|
|
52
|
-
}
|
|
53
|
-
if (item.path !== undefined &&
|
|
54
|
-
(typeof item.path !== "string" || item.path.length === 0)) {
|
|
55
|
-
throw new Error(`[E_BAD_SHAPE] edits[${index}].path must be a non-empty string.`);
|
|
56
|
-
}
|
|
57
|
-
});
|
|
58
|
-
}
|
|
59
21
|
async function prepareItems(io, params, cwd, signal) {
|
|
60
22
|
const items = [];
|
|
61
23
|
for (let index = 0; index < params.edits.length; index++) {
|
|
@@ -106,191 +68,6 @@ function groupByPath(items) {
|
|
|
106
68
|
}
|
|
107
69
|
return groups;
|
|
108
70
|
}
|
|
109
|
-
function echoRowsForItem(edit, originalHashes) {
|
|
110
|
-
const startHash = edit.hash_bounds[0].hash;
|
|
111
|
-
const endHash = edit.hash_bounds[1].hash;
|
|
112
|
-
const s = originalHashes.indexOf(startHash);
|
|
113
|
-
const e = originalHashes.indexOf(endHash);
|
|
114
|
-
if (s < 0 || e < 0)
|
|
115
|
-
return undefined;
|
|
116
|
-
return buildRangeEcho(Math.min(s, e) + 1, Math.max(s, e) + 1, originalHashes);
|
|
117
|
-
}
|
|
118
|
-
async function processFile(io, items, _cwd, opts) {
|
|
119
|
-
const first = items[0];
|
|
120
|
-
abortIf(opts.signal);
|
|
121
|
-
const absolutePath = first.absolutePath;
|
|
122
|
-
const rawText = await io.readText(absolutePath, opts.signal);
|
|
123
|
-
const { normalized: originalNormalized, bom, originalEnding, fileHashes: originalHashes, hadUtf8DecodeErrors, } = await normFromText({
|
|
124
|
-
absolutePath,
|
|
125
|
-
rawText,
|
|
126
|
-
displayPath: first.path,
|
|
127
|
-
signal: opts.signal,
|
|
128
|
-
maxLines: MAX_HASH_LINES,
|
|
129
|
-
});
|
|
130
|
-
const served = await loadServed(opts.sessionKey, absolutePath);
|
|
131
|
-
const warnings = [];
|
|
132
|
-
let currentContent = originalNormalized;
|
|
133
|
-
let currentHashes = originalHashes;
|
|
134
|
-
let appliedCount = 0;
|
|
135
|
-
let noopCount = 0;
|
|
136
|
-
let totalAddedLines = 0;
|
|
137
|
-
let totalRemovedLines = 0;
|
|
138
|
-
let unionStartLine = Infinity;
|
|
139
|
-
let unionEndLine = -Infinity;
|
|
140
|
-
let unionStartHash = "";
|
|
141
|
-
let unionEndHash = "";
|
|
142
|
-
let lastApplied;
|
|
143
|
-
for (const item of items) {
|
|
144
|
-
abortIf(opts.signal);
|
|
145
|
-
let edit;
|
|
146
|
-
try {
|
|
147
|
-
edit = resEdit({
|
|
148
|
-
remove_from: item.remove_from,
|
|
149
|
-
remove_to: item.remove_to,
|
|
150
|
-
replacement_text: item.replacement_text,
|
|
151
|
-
}, warnings);
|
|
152
|
-
}
|
|
153
|
-
catch (error) {
|
|
154
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
155
|
-
throw new Error(`[E_BATCH_ABORT] edits[${item.index}] (${item.path}) failed: ${message}\n` +
|
|
156
|
-
"The whole batch was rejected and NOTHING was written — no file changed and earlier items in the batch were NOT applied.");
|
|
157
|
-
}
|
|
158
|
-
let anchorResult;
|
|
159
|
-
try {
|
|
160
|
-
anchorResult = applyEdit(currentContent, edit, opts.signal, currentHashes, item.path, served);
|
|
161
|
-
}
|
|
162
|
-
catch (error) {
|
|
163
|
-
if (error instanceof AnchorMismatchError ||
|
|
164
|
-
error instanceof ServedRejectionError) {
|
|
165
|
-
const originalLines = splitLines(originalNormalized);
|
|
166
|
-
const echoRows = error.servedRows.length > 0
|
|
167
|
-
? error.servedRows
|
|
168
|
-
: echoRowsForItem(edit, originalHashes);
|
|
169
|
-
if (echoRows) {
|
|
170
|
-
await recordEchoServes(opts.sessionKey, absolutePath, echoRows, "live", originalHashes.length);
|
|
171
|
-
}
|
|
172
|
-
const echoBlock = echoRows
|
|
173
|
-
? ` Current on-disk range for edits[${item.index}] (unchanged — nothing was written):\n${fmtServedRows(echoRows, originalLines)}`
|
|
174
|
-
: " Call read() to get fresh anchors.";
|
|
175
|
-
throw new Error(`[E_BATCH_ABORT] edits[${item.index}] (${item.path}) failed: ${error.message}${echoBlock}\n` +
|
|
176
|
-
"The whole batch was rejected and NOTHING was written — no file changed and earlier items in the batch were NOT applied. Fix the failing edit (and any later edit that depends on it), then resubmit the batch.");
|
|
177
|
-
}
|
|
178
|
-
throw error;
|
|
179
|
-
}
|
|
180
|
-
const nextContent = anchorResult.content;
|
|
181
|
-
const isNoop = nextContent === currentContent;
|
|
182
|
-
const range = anchorResult.range;
|
|
183
|
-
if (range.startLine < unionStartLine) {
|
|
184
|
-
unionStartLine = range.startLine;
|
|
185
|
-
unionStartHash = range.startHash;
|
|
186
|
-
}
|
|
187
|
-
if (range.endLine > unionEndLine) {
|
|
188
|
-
unionEndLine = range.endLine;
|
|
189
|
-
unionEndHash = range.endHash;
|
|
190
|
-
}
|
|
191
|
-
if (isNoop) {
|
|
192
|
-
noopCount += 1;
|
|
193
|
-
const payload = noopPayloadKey(absolutePath, item.remove_from, item.remove_to, item.replacement_text);
|
|
194
|
-
const count = trackNoopPayload(absolutePath, payload);
|
|
195
|
-
if (count >= NOOP_LOOP_THRESHOLD) {
|
|
196
|
-
const originalLines = splitLines(originalNormalized);
|
|
197
|
-
const echoRows = echoRowsForItem(edit, originalHashes);
|
|
198
|
-
if (echoRows) {
|
|
199
|
-
await recordEchoServes(opts.sessionKey, absolutePath, echoRows, "live", originalHashes.length);
|
|
200
|
-
}
|
|
201
|
-
throw new Error(`[E_NOOP_LOOP] edits[${item.index}] (${item.path}): this exact edit (anchors ${item.remove_from} to ${item.remove_to}) has been submitted ${count} times and produced no changes each time — the range already contains the replacement text. Do not resend it; it will never change the file. The whole batch was rejected and nothing was written.` +
|
|
202
|
-
(echoRows
|
|
203
|
-
? ` Current on-disk range:\n${fmtServedRows(echoRows, originalLines)}`
|
|
204
|
-
: ""));
|
|
205
|
-
}
|
|
206
|
-
if (count === 2) {
|
|
207
|
-
warnings.push(`[E_NOOP_LOOP] Notice: edits[${item.index}] (${item.path}) — this exact edit has produced no changes twice in a row; the range already contains the replacement text. Resending it again will reject the batch.`);
|
|
208
|
-
}
|
|
209
|
-
warnings.push(`edits[${item.index}] (${item.path}) was a noop: the range already contains the replacement text.`);
|
|
210
|
-
if (anchorResult.warnings?.length)
|
|
211
|
-
warnings.push(...anchorResult.warnings);
|
|
212
|
-
continue;
|
|
213
|
-
}
|
|
214
|
-
appliedCount += 1;
|
|
215
|
-
const removedHashes = collectRemovedHashes(edit, currentHashes);
|
|
216
|
-
const nextHashes = await lineHashes(nextContent, absolutePath, { content: currentContent, hashes: currentHashes, removedHashes }, undefined, false);
|
|
217
|
-
const { totalAddedLines: added, totalRemovedLines: removed } = countLineChanges(edit, originalHashes, false, anchorResult.autoFixes?.length ?? 0);
|
|
218
|
-
totalAddedLines += added;
|
|
219
|
-
totalRemovedLines += removed;
|
|
220
|
-
lastApplied = {
|
|
221
|
-
content: currentContent,
|
|
222
|
-
hashes: currentHashes,
|
|
223
|
-
removedHashes,
|
|
224
|
-
};
|
|
225
|
-
currentContent = nextContent;
|
|
226
|
-
currentHashes = nextHashes;
|
|
227
|
-
clearNoopLoop(absolutePath);
|
|
228
|
-
if (anchorResult.warnings?.length)
|
|
229
|
-
warnings.push(...anchorResult.warnings);
|
|
230
|
-
}
|
|
231
|
-
const result = currentContent;
|
|
232
|
-
let resultHashes = currentHashes;
|
|
233
|
-
if (appliedCount > 0 && lastApplied) {
|
|
234
|
-
resultHashes = await lineHashes(result, absolutePath, {
|
|
235
|
-
content: lastApplied.content,
|
|
236
|
-
hashes: lastApplied.hashes,
|
|
237
|
-
removedHashes: lastApplied.removedHashes,
|
|
238
|
-
}, undefined, true);
|
|
239
|
-
}
|
|
240
|
-
if (hadUtf8DecodeErrors) {
|
|
241
|
-
warnings.push("Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.");
|
|
242
|
-
}
|
|
243
|
-
if (first.pathWarning)
|
|
244
|
-
warnings.unshift(first.pathWarning);
|
|
245
|
-
let driftNotice;
|
|
246
|
-
if (appliedCount > 0 && unionStartLine !== Infinity) {
|
|
247
|
-
const resultLines = splitLines(result);
|
|
248
|
-
const originalLines = splitLines(originalNormalized);
|
|
249
|
-
try {
|
|
250
|
-
driftNotice = await scanDrift({
|
|
251
|
-
sessionKey: opts.sessionKey,
|
|
252
|
-
served,
|
|
253
|
-
resultHashes,
|
|
254
|
-
resultLines,
|
|
255
|
-
range: {
|
|
256
|
-
startLine: unionStartLine,
|
|
257
|
-
endLine: unionEndLine,
|
|
258
|
-
startHash: unionStartHash,
|
|
259
|
-
endHash: unionEndHash,
|
|
260
|
-
delta: resultLines.length - originalLines.length,
|
|
261
|
-
},
|
|
262
|
-
path: absolutePath,
|
|
263
|
-
});
|
|
264
|
-
}
|
|
265
|
-
catch (error) {
|
|
266
|
-
console.error("Failed to compute drift notice:", error);
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
return {
|
|
270
|
-
displayPath: first.path,
|
|
271
|
-
absolutePath,
|
|
272
|
-
originalNormalized,
|
|
273
|
-
result,
|
|
274
|
-
bom,
|
|
275
|
-
originalEnding,
|
|
276
|
-
hadUtf8DecodeErrors,
|
|
277
|
-
warnings,
|
|
278
|
-
originalHashes,
|
|
279
|
-
resultHashes,
|
|
280
|
-
appliedCount,
|
|
281
|
-
noopCount,
|
|
282
|
-
totalAddedLines,
|
|
283
|
-
totalRemovedLines,
|
|
284
|
-
driftNotice,
|
|
285
|
-
range: {
|
|
286
|
-
startLine: unionStartLine,
|
|
287
|
-
endLine: unionEndLine,
|
|
288
|
-
startHash: unionStartHash,
|
|
289
|
-
endHash: unionEndHash,
|
|
290
|
-
delta: splitLines(result).length - splitLines(originalNormalized).length,
|
|
291
|
-
},
|
|
292
|
-
};
|
|
293
|
-
}
|
|
294
71
|
function toSection(file) {
|
|
295
72
|
return {
|
|
296
73
|
path: file.displayPath,
|
|
@@ -311,6 +88,7 @@ function toSection(file) {
|
|
|
311
88
|
* @param _rootCtx - host context.
|
|
312
89
|
* @param agentCtx - the agent's scoped context (own scope layer).
|
|
313
90
|
* @param io - the filesystem bridge.
|
|
91
|
+
* @param sandbox - the sandbox-escalation controller.
|
|
314
92
|
* @returns the exact disposer that unregisters the tool.
|
|
315
93
|
*/
|
|
316
94
|
export function buildBatchEditTool(io, sandbox) {
|
|
@@ -356,68 +134,38 @@ export function buildBatchEditTool(io, sandbox) {
|
|
|
356
134
|
return cloned;
|
|
357
135
|
});
|
|
358
136
|
}
|
|
359
|
-
|
|
137
|
+
assertBatchEditRequest(canonical);
|
|
360
138
|
const sandboxPolicy = await sandbox.resolvePolicy("batch_edit", canonical, exec);
|
|
361
139
|
const items = await prepareItems(io, canonical, cwd, signal);
|
|
362
140
|
const groups = groupByPath(items);
|
|
363
141
|
const processed = [];
|
|
364
142
|
for (const groupItems of groups.values()) {
|
|
365
143
|
abortIf(signal);
|
|
366
|
-
processed.push(await
|
|
144
|
+
processed.push(await runFileEdits(io, groupItems, {
|
|
367
145
|
signal,
|
|
368
146
|
sessionKey,
|
|
369
147
|
}));
|
|
370
148
|
}
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
149
|
+
await persistUndoAndWrite({
|
|
150
|
+
io,
|
|
151
|
+
files: processed
|
|
152
|
+
.filter((file) => file.appliedCount > 0)
|
|
153
|
+
.map((file) => ({
|
|
154
|
+
absolutePath: file.absolutePath,
|
|
155
|
+
displayPath: file.displayPath,
|
|
156
|
+
originalNormalized: file.originalNormalized,
|
|
377
157
|
bom: file.bom,
|
|
378
158
|
originalEnding: file.originalEnding,
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
})
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
}
|
|
390
|
-
}
|
|
391
|
-
throw new Error("[E_UNDO_UNAVAILABLE] Cannot persist undo history to the hash store; the batch was NOT applied and no file was written. Retry the batch, or use write if the store cannot be recovered.");
|
|
392
|
-
}
|
|
393
|
-
undos.push({ file, restore: undo.restore });
|
|
394
|
-
}
|
|
395
|
-
const written = [];
|
|
396
|
-
try {
|
|
397
|
-
for (const u of undos) {
|
|
398
|
-
abortIf(signal);
|
|
399
|
-
await io.writeText(u.file.absolutePath, u.file.bom + restoreEndings(u.file.result, u.file.originalEnding), signal, exec, sandboxPolicy);
|
|
400
|
-
written.push(u);
|
|
401
|
-
}
|
|
402
|
-
}
|
|
403
|
-
catch (error) {
|
|
404
|
-
for (const w of written) {
|
|
405
|
-
try {
|
|
406
|
-
await io.writeText(w.file.absolutePath, w.file.bom +
|
|
407
|
-
restoreEndings(w.file.originalNormalized, w.file.originalEnding), undefined, exec, sandboxPolicy);
|
|
408
|
-
}
|
|
409
|
-
catch (restoreError) {
|
|
410
|
-
console.error("Failed to restore file after batch write failure:", restoreError);
|
|
411
|
-
}
|
|
412
|
-
try {
|
|
413
|
-
await w.restore();
|
|
414
|
-
}
|
|
415
|
-
catch (restoreError) {
|
|
416
|
-
console.error("Failed to restore undo entry after batch write failure:", restoreError);
|
|
417
|
-
}
|
|
418
|
-
}
|
|
419
|
-
throw sandbox.mapError(error, sandboxPolicy);
|
|
420
|
-
}
|
|
159
|
+
originalHashes: file.originalHashes,
|
|
160
|
+
result: file.result,
|
|
161
|
+
})),
|
|
162
|
+
exec,
|
|
163
|
+
sandbox,
|
|
164
|
+
sandboxPolicy,
|
|
165
|
+
signal,
|
|
166
|
+
undoUnavailableMessage: () => "[E_UNDO_UNAVAILABLE] Cannot persist undo history to the hash store; the batch was NOT applied and no file was written. Retry the batch, or use write if the store cannot be recovered.",
|
|
167
|
+
restoreUnwrittenUndos: false,
|
|
168
|
+
});
|
|
421
169
|
const result = buildBatchResult(processed.map(toSection));
|
|
422
170
|
if (result.details.servedRows && result.details.servedRows.length > 0) {
|
|
423
171
|
const byPath = result.details.servedByPath ?? [];
|
package/lib/tool-edit.js
CHANGED
|
@@ -6,16 +6,14 @@
|
|
|
6
6
|
* @module dsh-better-edit/tool-edit
|
|
7
7
|
*/
|
|
8
8
|
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
9
|
-
import { restoreEndings } from "./edit-diff.js";
|
|
10
9
|
import { normReq } from "./edit-normalize.js";
|
|
11
10
|
import { abortIf, isRec, splitLines } from "./utils.js";
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
11
|
+
import { assertEditRequest } from "./contract.js";
|
|
12
|
+
import { enforceNoopLoop, persistUndoAndWrite, resolveMissingPath, } from "./edit-engine.js";
|
|
13
|
+
import { execPipeline, snapshotIdFor, } from "./edit-pipeline.js";
|
|
15
14
|
import { clearNoopLoop, noopPayloadKey, trackNoopPayload, } from "./noop-guard.js";
|
|
16
15
|
import { buildNoop, buildChanged } from "./edit-response.js";
|
|
17
16
|
import { recordServedTruncated } from "./served-store.js";
|
|
18
|
-
import { NOOP_LOOP_THRESHOLD } from "./constants.js";
|
|
19
17
|
import { EDIT_DESCRIPTION } from "./prompts.js";
|
|
20
18
|
import { pathSchema, removeFromSchema, removeToSchema, replacementTextSchema, } from "./schema.js";
|
|
21
19
|
import { execCwd, execSessionKey } from "./dsh-context.js";
|
|
@@ -55,7 +53,7 @@ export function buildEditTool(io, sandbox) {
|
|
|
55
53
|
if (resolution && isRec(canonical)) {
|
|
56
54
|
canonical.path = resolution.path;
|
|
57
55
|
}
|
|
58
|
-
|
|
56
|
+
assertEditRequest(canonical);
|
|
59
57
|
const sandboxPolicy = await sandbox.resolvePolicy("edit", canonical, exec);
|
|
60
58
|
const normalizedParams = canonical;
|
|
61
59
|
const path = normalizedParams.path;
|
|
@@ -72,15 +70,20 @@ export function buildEditTool(io, sandbox) {
|
|
|
72
70
|
if (originalNormalized === result) {
|
|
73
71
|
const payload = noopPayloadKey(absolutePath, canonical.remove_from, canonical.remove_to, canonical.replacement_text);
|
|
74
72
|
const count = trackNoopPayload(absolutePath, payload);
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
73
|
+
const notice = await enforceNoopLoop({
|
|
74
|
+
absolutePath,
|
|
75
|
+
removeFrom: canonical.remove_from,
|
|
76
|
+
removeTo: canonical.remove_to,
|
|
77
|
+
replacementText: canonical.replacement_text,
|
|
78
|
+
displayPath: path,
|
|
79
|
+
count,
|
|
80
|
+
sessionKey,
|
|
81
|
+
originalHashes,
|
|
82
|
+
originalNormalized,
|
|
83
|
+
range,
|
|
84
|
+
});
|
|
85
|
+
if (notice)
|
|
86
|
+
warnings.push(notice);
|
|
84
87
|
const noopSnapshotId = await snapshotIdFor(io, absolutePath, signal);
|
|
85
88
|
const noopResult = buildNoop({
|
|
86
89
|
path,
|
|
@@ -102,24 +105,26 @@ export function buildEditTool(io, sandbox) {
|
|
|
102
105
|
warnings.push("Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.");
|
|
103
106
|
}
|
|
104
107
|
abortIf(signal);
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
108
|
+
await persistUndoAndWrite({
|
|
109
|
+
io,
|
|
110
|
+
files: [
|
|
111
|
+
{
|
|
112
|
+
absolutePath,
|
|
113
|
+
displayPath: path,
|
|
114
|
+
originalNormalized,
|
|
115
|
+
bom,
|
|
116
|
+
originalEnding,
|
|
117
|
+
originalHashes,
|
|
118
|
+
result,
|
|
119
|
+
},
|
|
120
|
+
],
|
|
121
|
+
exec,
|
|
122
|
+
sandbox,
|
|
123
|
+
sandboxPolicy,
|
|
124
|
+
signal,
|
|
125
|
+
undoUnavailableMessage: (displayPath) => `[E_UNDO_UNAVAILABLE] Cannot persist undo history to the hash store; the edit was NOT applied and ${displayPath} is unchanged. Retry the edit, or use write if the store cannot be recovered.`,
|
|
126
|
+
restoreUnwrittenUndos: true,
|
|
111
127
|
});
|
|
112
|
-
if (!undo.persisted) {
|
|
113
|
-
throw new Error(`[E_UNDO_UNAVAILABLE] Cannot persist undo history to the hash store; the edit was NOT applied and ${path} is unchanged. Retry the edit, or use write if the store cannot be recovered.`);
|
|
114
|
-
}
|
|
115
|
-
try {
|
|
116
|
-
abortIf(signal);
|
|
117
|
-
await io.writeText(absolutePath, bom + restoreEndings(result, originalEnding), signal, exec, sandboxPolicy);
|
|
118
|
-
}
|
|
119
|
-
catch (error) {
|
|
120
|
-
await undo.restore();
|
|
121
|
-
throw sandbox.mapError(error, sandboxPolicy);
|
|
122
|
-
}
|
|
123
128
|
const updatedSnapshotId = await snapshotIdFor(io, absolutePath, signal);
|
|
124
129
|
const editMeta = {
|
|
125
130
|
editsAttempted,
|
package/lib/tool-read.js
CHANGED
|
@@ -7,24 +7,12 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
9
9
|
import { normReq } from "./edit-normalize.js";
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import { fmtReadPreview, MAX_HASH_LINES } from "./read-render.js";
|
|
13
|
-
import { recordServed, clearDriftReported } from "./served-store.js";
|
|
10
|
+
import { assertReadRequest } from "./contract.js";
|
|
11
|
+
import { readAndServe } from "./read-and-serve.js";
|
|
14
12
|
import { READ_DESCRIPTION } from "./prompts.js";
|
|
15
13
|
import { pathSchema } from "./schema.js";
|
|
16
14
|
import { execCwd, execSessionKey } from "./dsh-context.js";
|
|
17
15
|
import { withWorkspace } from "./workspace.js";
|
|
18
|
-
const ROOT_KS = new Set(["path", "offset", "limit"]);
|
|
19
|
-
function assertReadReq(request) {
|
|
20
|
-
if (!isRec(request)) {
|
|
21
|
-
throw new Error("[E_BAD_SHAPE] Read request must be an object.");
|
|
22
|
-
}
|
|
23
|
-
rejectUnknownFields(request, ROOT_KS, "Read request");
|
|
24
|
-
if (typeof request.path !== "string" || request.path.length === 0) {
|
|
25
|
-
throw new Error('[E_BAD_SHAPE] Read request requires a non-empty "path" string.');
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
16
|
/**
|
|
29
17
|
* Register the hash-anchored `read` tool on the calling agent's scope.
|
|
30
18
|
* @param _rootCtx - host context.
|
|
@@ -57,30 +45,19 @@ export function buildReadTool(io) {
|
|
|
57
45
|
const sessionKey = execSessionKey(exec);
|
|
58
46
|
const signal = exec.signal;
|
|
59
47
|
const canonical = normReq(args);
|
|
60
|
-
|
|
48
|
+
assertReadRequest(canonical);
|
|
61
49
|
const rawPath = canonical.path;
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
const rawText = await io.readText(absolutePath, signal);
|
|
65
|
-
const { normalized, fileHashes, hadUtf8DecodeErrors } = await normFromText({
|
|
66
|
-
absolutePath,
|
|
67
|
-
rawText,
|
|
68
|
-
displayPath: rawPath,
|
|
50
|
+
const { text, absolutePath } = await readAndServe(io, rawPath, cwd, {
|
|
51
|
+
sessionKey,
|
|
69
52
|
signal,
|
|
70
|
-
|
|
53
|
+
offset: canonical.offset,
|
|
54
|
+
limit: canonical.limit,
|
|
71
55
|
});
|
|
72
|
-
const preview = await fmtReadPreview(normalized, { offset: canonical.offset, limit: canonical.limit }, fileHashes, absolutePath);
|
|
73
|
-
if (preview.served.length > 0) {
|
|
74
|
-
await recordServed(sessionKey, absolutePath, preview.served, fileHashes.length);
|
|
75
|
-
}
|
|
76
|
-
await clearDriftReported(sessionKey, absolutePath);
|
|
77
56
|
// Record the present observation with the fs policy gate so later
|
|
78
57
|
// built-in write/edit calls see this file as observed at the
|
|
79
58
|
// version the model just read (a no-op when no policy listens).
|
|
80
59
|
await io.emitObserved(absolutePath, exec, signal);
|
|
81
|
-
return
|
|
82
|
-
? `${preview.text}\n\n[Non-UTF-8 bytes shown as U+FFFD; editing rewrites the file as UTF-8.]`
|
|
83
|
-
: preview.text;
|
|
60
|
+
return text;
|
|
84
61
|
});
|
|
85
62
|
},
|
|
86
63
|
});
|
package/lib/tool-undo.js
CHANGED
|
@@ -6,26 +6,17 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
8
8
|
import { toLF, stripBOM, genDiff, restoreEndings } from "./edit-diff.js";
|
|
9
|
-
import { cntDiff, splitLines
|
|
9
|
+
import { cntDiff, splitLines } from "./utils.js";
|
|
10
|
+
import { assertUndoRequest } from "./contract.js";
|
|
10
11
|
import { normReq } from "./edit-normalize.js";
|
|
11
|
-
import { upsertSnapshotFor } from "./
|
|
12
|
+
import { upsertSnapshotFor } from "./hash-store.js";
|
|
12
13
|
import { contentChecksum } from "./hashline/hasher.js";
|
|
13
14
|
import { lineHashes, changedRange } from "./hashline/index.js";
|
|
14
15
|
import { getUndo, clearUndo } from "./undo-edit.js";
|
|
15
16
|
import { recordServedTruncated } from "./served-store.js";
|
|
16
17
|
import { UNDO_DESCRIPTION } from "./prompts.js";
|
|
17
18
|
import { execCwd, execSessionKey } from "./dsh-context.js";
|
|
18
|
-
import { FsSandboxController } from "./sandbox.js";
|
|
19
19
|
import { withWorkspace } from "./workspace.js";
|
|
20
|
-
function assertUndoReq(request) {
|
|
21
|
-
if (!isRec(request)) {
|
|
22
|
-
throw new Error("[E_BAD_SHAPE] undo_last_edit request must be an object.");
|
|
23
|
-
}
|
|
24
|
-
normalizeFilePath(request);
|
|
25
|
-
if (typeof request.path !== "string" || request.path.length === 0) {
|
|
26
|
-
throw new Error('[E_BAD_SHAPE] undo_last_edit request requires a non-empty "path" string.');
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
20
|
/**
|
|
30
21
|
* Register the `undo_last_edit` tool on the calling agent's scope.
|
|
31
22
|
* @param _rootCtx - host context.
|
|
@@ -55,7 +46,7 @@ export function buildUndoTool(io, sandbox) {
|
|
|
55
46
|
const sessionKey = execSessionKey(exec);
|
|
56
47
|
const signal = exec.signal;
|
|
57
48
|
const canonical = normReq(args);
|
|
58
|
-
|
|
49
|
+
assertUndoRequest(canonical);
|
|
59
50
|
const path = canonical.path;
|
|
60
51
|
const absolutePath = await io.resolve(path, cwd, signal);
|
|
61
52
|
const sandboxPolicy = await sandbox.resolvePolicy("undo_last_edit", canonical, exec);
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One module owns the request shapes for the hashline tools — edit,
|
|
3
|
+
* batch_edit, read, undo_last_edit — plus their validation. Field sets are
|
|
4
|
+
* declared once here; every tool validates through these asserts, and the
|
|
5
|
+
* [E_BAD_SHAPE] vocabulary is shared instead of re-implemented per tool.
|
|
6
|
+
*
|
|
7
|
+
* Note: `resolve.ts` keeps its own internal item check (content-only fields,
|
|
8
|
+
* no path) — that is the hashline-internal edit-item shape, deliberately
|
|
9
|
+
* decoupled from the tool-layer request contract so the hashline module does
|
|
10
|
+
* not depend on this one.
|
|
11
|
+
* @module dsh-better-edit/contract
|
|
12
|
+
*/
|
|
13
|
+
export interface EditParams {
|
|
14
|
+
path: string;
|
|
15
|
+
remove_from: string;
|
|
16
|
+
remove_to: string;
|
|
17
|
+
replacement_text: string;
|
|
18
|
+
}
|
|
19
|
+
export interface BatchItemParams {
|
|
20
|
+
path?: string;
|
|
21
|
+
remove_from: string;
|
|
22
|
+
remove_to: string;
|
|
23
|
+
replacement_text: string;
|
|
24
|
+
}
|
|
25
|
+
export interface BatchEditParams {
|
|
26
|
+
edits: BatchItemParams[];
|
|
27
|
+
}
|
|
28
|
+
export interface ReadParams {
|
|
29
|
+
path: string;
|
|
30
|
+
offset?: number;
|
|
31
|
+
limit?: number;
|
|
32
|
+
}
|
|
33
|
+
export interface UndoParams {
|
|
34
|
+
path: string;
|
|
35
|
+
}
|
|
36
|
+
export declare function assertEditRequest(request: unknown): asserts request is EditParams;
|
|
37
|
+
export declare function assertBatchEditRequest(request: unknown): asserts request is BatchEditParams;
|
|
38
|
+
export declare function assertReadRequest(request: unknown): asserts request is ReadParams;
|
|
39
|
+
export declare function assertUndoRequest(request: unknown): asserts request is UndoParams;
|