dsh-better-edit 0.1.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/LICENSE +23 -0
- package/README.md +188 -0
- package/cordis.patch.yml +8 -0
- package/lib/constants.js +12 -0
- package/lib/drift.js +98 -0
- package/lib/dsh-context.js +27 -0
- package/lib/edit-diff.js +121 -0
- package/lib/edit-normalize.js +9 -0
- package/lib/edit-pipeline.js +199 -0
- package/lib/edit-response.js +172 -0
- package/lib/file-kind.js +121 -0
- package/lib/file-reader.js +80 -0
- package/lib/fs-bridge.js +106 -0
- package/lib/fs-write.js +151 -0
- package/lib/hash-store.js +380 -0
- package/lib/hashline/alphabet.js +6 -0
- package/lib/hashline/apply.js +223 -0
- package/lib/hashline/hash.js +241 -0
- package/lib/hashline/hasher.js +23 -0
- package/lib/hashline/index.js +4 -0
- package/lib/hashline/parse.js +35 -0
- package/lib/hashline/resolve.js +365 -0
- package/lib/hashline/served.js +120 -0
- package/lib/index.js +91 -0
- package/lib/noop-guard.js +15 -0
- package/lib/paths.js +37 -0
- package/lib/prompts.js +54 -0
- package/lib/read-render.js +142 -0
- package/lib/schema.js +24 -0
- package/lib/served-state.js +34 -0
- package/lib/served-store.js +230 -0
- package/lib/snapshot-store.js +108 -0
- package/lib/tool-batch-edit.js +434 -0
- package/lib/tool-edit.js +152 -0
- package/lib/tool-read.js +86 -0
- package/lib/tool-undo.js +118 -0
- package/lib/truncate.js +98 -0
- package/lib/types/constants.d.ts +11 -0
- package/lib/types/drift.d.ts +29 -0
- package/lib/types/dsh-context.d.ts +23 -0
- package/lib/types/edit-diff.d.ts +14 -0
- package/lib/types/edit-normalize.d.ts +1 -0
- package/lib/types/edit-pipeline.d.ts +54 -0
- package/lib/types/edit-response.d.ts +107 -0
- package/lib/types/file-kind.d.ts +18 -0
- package/lib/types/file-reader.d.ts +47 -0
- package/lib/types/fs-bridge.d.ts +32 -0
- package/lib/types/fs-write.d.ts +2 -0
- package/lib/types/hash-store.d.ts +33 -0
- package/lib/types/hashline/alphabet.d.ts +5 -0
- package/lib/types/hashline/apply.d.ts +22 -0
- package/lib/types/hashline/hash.d.ts +19 -0
- package/lib/types/hashline/hasher.d.ts +8 -0
- package/lib/types/hashline/index.d.ts +4 -0
- package/lib/types/hashline/parse.d.ts +7 -0
- package/lib/types/hashline/resolve.d.ts +59 -0
- package/lib/types/hashline/served.d.ts +43 -0
- package/lib/types/index.d.ts +23 -0
- package/lib/types/noop-guard.d.ts +5 -0
- package/lib/types/paths.d.ts +11 -0
- package/lib/types/prompts.d.ts +17 -0
- package/lib/types/read-render.d.ts +21 -0
- package/lib/types/schema.d.ts +39 -0
- package/lib/types/served-state.d.ts +3 -0
- package/lib/types/served-store.d.ts +53 -0
- package/lib/types/snapshot-store.d.ts +14 -0
- package/lib/types/tool-batch-edit.d.ts +21 -0
- package/lib/types/tool-edit.d.ts +22 -0
- package/lib/types/tool-read.d.ts +21 -0
- package/lib/types/tool-undo.d.ts +20 -0
- package/lib/types/truncate.d.ts +32 -0
- package/lib/types/undo-edit.d.ts +32 -0
- package/lib/types/undo-store.d.ts +14 -0
- package/lib/types/utils.d.ts +13 -0
- package/lib/types/validation.d.ts +7 -0
- package/lib/types/write-hook.d.ts +21 -0
- package/lib/undo-edit.js +83 -0
- package/lib/undo-store.js +43 -0
- package/lib/utils.js +76 -0
- package/lib/validation.js +33 -0
- package/lib/write-hook.js +72 -0
- package/package.json +87 -0
|
@@ -0,0 +1,434 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The dsh `batch_edit` tool: several hash-anchored edits in one all-or-nothing
|
|
3
|
+
* call. Items targeting the same file are applied in order against the served
|
|
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.
|
|
6
|
+
* @module dsh-better-edit/tool-batch-edit
|
|
7
|
+
*/
|
|
8
|
+
import { defineTool } from '@deepseek-ai/dsh-tools';
|
|
9
|
+
import { restoreEndings } from './edit-diff.js';
|
|
10
|
+
import { normFromText } from './file-reader.js';
|
|
11
|
+
import { scanDrift } from './drift.js';
|
|
12
|
+
import { abortIf, isRec, normalizeFilePath, rejectUnknownFields, splitLines } from './utils.js';
|
|
13
|
+
import { normReq } from './edit-normalize.js';
|
|
14
|
+
import { applyEdit, lineHashes, resEdit, MAX_HASH_LINES, } from './hashline/index.js';
|
|
15
|
+
import { AnchorMismatchError, ServedRejectionError, buildRangeEcho, fmtServedRows, recordEchoServes, } from './hashline/served.js';
|
|
16
|
+
import { buildBatchResult } from './edit-response.js';
|
|
17
|
+
import { saveUndo } from './undo-edit.js';
|
|
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';
|
|
22
|
+
import { BATCH_EDIT_DESCRIPTION } from './prompts.js';
|
|
23
|
+
import { pathSchema, removeFromSchema, removeToSchema, replacementTextSchema } from './schema.js';
|
|
24
|
+
import { execCwd, execSessionKey } from './dsh-context.js';
|
|
25
|
+
const BATCH_ITEM_KS = new Set(['path', 'remove_from', 'remove_to', 'replacement_text']);
|
|
26
|
+
function assertBatchReq(request) {
|
|
27
|
+
if (!isRec(request)) {
|
|
28
|
+
throw new Error('[E_BAD_SHAPE] batch_edit request must be an object with an "edits" array.');
|
|
29
|
+
}
|
|
30
|
+
rejectUnknownFields(request, new Set(['edits']), 'batch_edit request');
|
|
31
|
+
if (!Array.isArray(request.edits) || request.edits.length === 0) {
|
|
32
|
+
throw new Error('[E_BAD_SHAPE] batch_edit request requires a non-empty "edits" array.');
|
|
33
|
+
}
|
|
34
|
+
if (request.edits.length > BATCH_EDIT_MAX_ITEMS) {
|
|
35
|
+
throw new Error(`[E_BAD_SHAPE] batch_edit accepts at most ${BATCH_EDIT_MAX_ITEMS} edits; got ${request.edits.length}. Split the batch.`);
|
|
36
|
+
}
|
|
37
|
+
request.edits.forEach((item, index) => {
|
|
38
|
+
if (!isRec(item)) {
|
|
39
|
+
throw new Error(`[E_BAD_SHAPE] edits[${index}] must be an object with remove_from, remove_to, and replacement_text.`);
|
|
40
|
+
}
|
|
41
|
+
rejectUnknownFields(item, BATCH_ITEM_KS, `edits[${index}]`);
|
|
42
|
+
if (typeof item.remove_from !== 'string' ||
|
|
43
|
+
typeof item.remove_to !== 'string' ||
|
|
44
|
+
typeof item.replacement_text !== 'string') {
|
|
45
|
+
throw new Error(`[E_BAD_SHAPE] edits[${index}] requires "remove_from", "remove_to", and "replacement_text" strings.`);
|
|
46
|
+
}
|
|
47
|
+
if (item.path !== undefined &&
|
|
48
|
+
(typeof item.path !== 'string' || item.path.length === 0)) {
|
|
49
|
+
throw new Error(`[E_BAD_SHAPE] edits[${index}].path must be a non-empty string.`);
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
async function prepareItems(io, params, cwd, signal) {
|
|
54
|
+
const items = [];
|
|
55
|
+
for (let index = 0; index < params.edits.length; index++) {
|
|
56
|
+
const raw = params.edits[index];
|
|
57
|
+
const record = { ...raw };
|
|
58
|
+
normalizeFilePath(record);
|
|
59
|
+
let path = typeof record.path === 'string' ? record.path : undefined;
|
|
60
|
+
let pathWarning;
|
|
61
|
+
if (!path) {
|
|
62
|
+
let resolution;
|
|
63
|
+
try {
|
|
64
|
+
resolution = await resolveMissingPath(record);
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
if (error instanceof Error) {
|
|
68
|
+
throw new Error(`edits[${index}]: ${error.message}`);
|
|
69
|
+
}
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
if (resolution) {
|
|
73
|
+
path = resolution.path;
|
|
74
|
+
pathWarning = resolution.warning;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
if (!path) {
|
|
78
|
+
throw new Error(`[E_BAD_SHAPE] edits[${index}] requires a non-empty "path" string, and its anchors match no known file.`);
|
|
79
|
+
}
|
|
80
|
+
items.push({
|
|
81
|
+
index,
|
|
82
|
+
path,
|
|
83
|
+
absolutePath: await io.resolve(path, cwd, signal),
|
|
84
|
+
remove_from: record.remove_from,
|
|
85
|
+
remove_to: record.remove_to,
|
|
86
|
+
replacement_text: record.replacement_text,
|
|
87
|
+
pathWarning,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
return items;
|
|
91
|
+
}
|
|
92
|
+
function groupByPath(items) {
|
|
93
|
+
const groups = new Map();
|
|
94
|
+
for (const item of items) {
|
|
95
|
+
const list = groups.get(item.absolutePath);
|
|
96
|
+
if (list)
|
|
97
|
+
list.push(item);
|
|
98
|
+
else
|
|
99
|
+
groups.set(item.absolutePath, [item]);
|
|
100
|
+
}
|
|
101
|
+
return groups;
|
|
102
|
+
}
|
|
103
|
+
function echoRowsForItem(edit, originalHashes) {
|
|
104
|
+
const startHash = edit.hash_bounds[0].hash;
|
|
105
|
+
const endHash = edit.hash_bounds[1].hash;
|
|
106
|
+
const s = originalHashes.indexOf(startHash);
|
|
107
|
+
const e = originalHashes.indexOf(endHash);
|
|
108
|
+
if (s < 0 || e < 0)
|
|
109
|
+
return undefined;
|
|
110
|
+
return buildRangeEcho(Math.min(s, e) + 1, Math.max(s, e) + 1, originalHashes);
|
|
111
|
+
}
|
|
112
|
+
async function processFile(io, items, _cwd, opts) {
|
|
113
|
+
const first = items[0];
|
|
114
|
+
abortIf(opts.signal);
|
|
115
|
+
const absolutePath = first.absolutePath;
|
|
116
|
+
const rawText = await io.readText(absolutePath, opts.signal);
|
|
117
|
+
const { normalized: originalNormalized, bom, originalEnding, fileHashes: originalHashes, hadUtf8DecodeErrors, } = await normFromText({
|
|
118
|
+
absolutePath,
|
|
119
|
+
rawText,
|
|
120
|
+
displayPath: first.path,
|
|
121
|
+
signal: opts.signal,
|
|
122
|
+
maxLines: MAX_HASH_LINES,
|
|
123
|
+
});
|
|
124
|
+
const served = await loadServed(opts.sessionKey, absolutePath);
|
|
125
|
+
const warnings = [];
|
|
126
|
+
let currentContent = originalNormalized;
|
|
127
|
+
let currentHashes = originalHashes;
|
|
128
|
+
let appliedCount = 0;
|
|
129
|
+
let noopCount = 0;
|
|
130
|
+
let totalAddedLines = 0;
|
|
131
|
+
let totalRemovedLines = 0;
|
|
132
|
+
let unionStartLine = Infinity;
|
|
133
|
+
let unionEndLine = -Infinity;
|
|
134
|
+
let unionStartHash = '';
|
|
135
|
+
let unionEndHash = '';
|
|
136
|
+
let lastApplied;
|
|
137
|
+
for (const item of items) {
|
|
138
|
+
abortIf(opts.signal);
|
|
139
|
+
let edit;
|
|
140
|
+
try {
|
|
141
|
+
edit = resEdit({
|
|
142
|
+
remove_from: item.remove_from,
|
|
143
|
+
remove_to: item.remove_to,
|
|
144
|
+
replacement_text: item.replacement_text,
|
|
145
|
+
}, warnings);
|
|
146
|
+
}
|
|
147
|
+
catch (error) {
|
|
148
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
149
|
+
throw new Error(`[E_BATCH_ABORT] edits[${item.index}] (${item.path}) failed: ${message}\n` +
|
|
150
|
+
'The whole batch was rejected and NOTHING was written — no file changed and earlier items in the batch were NOT applied.');
|
|
151
|
+
}
|
|
152
|
+
let anchorResult;
|
|
153
|
+
try {
|
|
154
|
+
anchorResult = applyEdit(currentContent, edit, opts.signal, currentHashes, item.path, served);
|
|
155
|
+
}
|
|
156
|
+
catch (error) {
|
|
157
|
+
if (error instanceof AnchorMismatchError ||
|
|
158
|
+
error instanceof ServedRejectionError) {
|
|
159
|
+
const originalLines = splitLines(originalNormalized);
|
|
160
|
+
const echoRows = error.servedRows.length > 0
|
|
161
|
+
? error.servedRows
|
|
162
|
+
: echoRowsForItem(edit, originalHashes);
|
|
163
|
+
if (echoRows) {
|
|
164
|
+
await recordEchoServes(opts.sessionKey, absolutePath, echoRows, 'live');
|
|
165
|
+
}
|
|
166
|
+
const echoBlock = echoRows
|
|
167
|
+
? ` Current on-disk range for edits[${item.index}] (unchanged — nothing was written):\n${fmtServedRows(echoRows, originalLines)}`
|
|
168
|
+
: ' Call read() to get fresh anchors.';
|
|
169
|
+
throw new Error(`[E_BATCH_ABORT] edits[${item.index}] (${item.path}) failed: ${error.message}${echoBlock}\n` +
|
|
170
|
+
'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.');
|
|
171
|
+
}
|
|
172
|
+
throw error;
|
|
173
|
+
}
|
|
174
|
+
const nextContent = anchorResult.content;
|
|
175
|
+
const isNoop = nextContent === currentContent;
|
|
176
|
+
const range = anchorResult.range;
|
|
177
|
+
if (range.startLine < unionStartLine) {
|
|
178
|
+
unionStartLine = range.startLine;
|
|
179
|
+
unionStartHash = range.startHash;
|
|
180
|
+
}
|
|
181
|
+
if (range.endLine > unionEndLine) {
|
|
182
|
+
unionEndLine = range.endLine;
|
|
183
|
+
unionEndHash = range.endHash;
|
|
184
|
+
}
|
|
185
|
+
if (isNoop) {
|
|
186
|
+
noopCount += 1;
|
|
187
|
+
const payload = noopPayloadKey(absolutePath, item.remove_from, item.remove_to, item.replacement_text);
|
|
188
|
+
const count = trackNoopPayload(absolutePath, payload);
|
|
189
|
+
if (count >= NOOP_LOOP_THRESHOLD) {
|
|
190
|
+
const originalLines = splitLines(originalNormalized);
|
|
191
|
+
const echoRows = echoRowsForItem(edit, originalHashes);
|
|
192
|
+
if (echoRows) {
|
|
193
|
+
await recordEchoServes(opts.sessionKey, absolutePath, echoRows, 'live');
|
|
194
|
+
}
|
|
195
|
+
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.` +
|
|
196
|
+
(echoRows
|
|
197
|
+
? ` Current on-disk range:\n${fmtServedRows(echoRows, originalLines)}`
|
|
198
|
+
: ''));
|
|
199
|
+
}
|
|
200
|
+
if (count === 2) {
|
|
201
|
+
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.`);
|
|
202
|
+
}
|
|
203
|
+
warnings.push(`edits[${item.index}] (${item.path}) was a noop: the range already contains the replacement text.`);
|
|
204
|
+
if (anchorResult.warnings?.length)
|
|
205
|
+
warnings.push(...anchorResult.warnings);
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
appliedCount += 1;
|
|
209
|
+
const removedHashes = collectRemovedHashes(edit, currentHashes);
|
|
210
|
+
const nextHashes = await lineHashes(nextContent, absolutePath, { content: currentContent, hashes: currentHashes, removedHashes }, undefined, false);
|
|
211
|
+
const { totalAddedLines: added, totalRemovedLines: removed } = countLineChanges(edit, originalHashes, false, anchorResult.autoFixes?.length ?? 0);
|
|
212
|
+
totalAddedLines += added;
|
|
213
|
+
totalRemovedLines += removed;
|
|
214
|
+
lastApplied = {
|
|
215
|
+
content: currentContent,
|
|
216
|
+
hashes: currentHashes,
|
|
217
|
+
removedHashes,
|
|
218
|
+
};
|
|
219
|
+
currentContent = nextContent;
|
|
220
|
+
currentHashes = nextHashes;
|
|
221
|
+
clearNoopLoop(absolutePath);
|
|
222
|
+
if (anchorResult.warnings?.length)
|
|
223
|
+
warnings.push(...anchorResult.warnings);
|
|
224
|
+
}
|
|
225
|
+
const result = currentContent;
|
|
226
|
+
let resultHashes = currentHashes;
|
|
227
|
+
if (appliedCount > 0 && lastApplied) {
|
|
228
|
+
resultHashes = await lineHashes(result, absolutePath, {
|
|
229
|
+
content: lastApplied.content,
|
|
230
|
+
hashes: lastApplied.hashes,
|
|
231
|
+
removedHashes: lastApplied.removedHashes,
|
|
232
|
+
}, undefined, true);
|
|
233
|
+
}
|
|
234
|
+
if (hadUtf8DecodeErrors) {
|
|
235
|
+
warnings.push('Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.');
|
|
236
|
+
}
|
|
237
|
+
if (first.pathWarning)
|
|
238
|
+
warnings.unshift(first.pathWarning);
|
|
239
|
+
let driftNotice;
|
|
240
|
+
if (appliedCount > 0 && unionStartLine !== Infinity) {
|
|
241
|
+
const resultLines = splitLines(result);
|
|
242
|
+
const originalLines = splitLines(originalNormalized);
|
|
243
|
+
try {
|
|
244
|
+
driftNotice = await scanDrift({
|
|
245
|
+
sessionKey: opts.sessionKey,
|
|
246
|
+
served,
|
|
247
|
+
resultHashes,
|
|
248
|
+
resultLines,
|
|
249
|
+
range: {
|
|
250
|
+
startLine: unionStartLine,
|
|
251
|
+
endLine: unionEndLine,
|
|
252
|
+
startHash: unionStartHash,
|
|
253
|
+
endHash: unionEndHash,
|
|
254
|
+
delta: resultLines.length - originalLines.length,
|
|
255
|
+
},
|
|
256
|
+
path: absolutePath,
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
catch (error) {
|
|
260
|
+
console.error('Failed to compute drift notice:', error);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
return {
|
|
264
|
+
displayPath: first.path,
|
|
265
|
+
absolutePath,
|
|
266
|
+
originalNormalized,
|
|
267
|
+
result,
|
|
268
|
+
bom,
|
|
269
|
+
originalEnding,
|
|
270
|
+
hadUtf8DecodeErrors,
|
|
271
|
+
warnings,
|
|
272
|
+
originalHashes,
|
|
273
|
+
resultHashes,
|
|
274
|
+
appliedCount,
|
|
275
|
+
noopCount,
|
|
276
|
+
totalAddedLines,
|
|
277
|
+
totalRemovedLines,
|
|
278
|
+
driftNotice,
|
|
279
|
+
range: {
|
|
280
|
+
startLine: unionStartLine,
|
|
281
|
+
endLine: unionEndLine,
|
|
282
|
+
startHash: unionStartHash,
|
|
283
|
+
endHash: unionEndHash,
|
|
284
|
+
delta: splitLines(result).length - splitLines(originalNormalized).length,
|
|
285
|
+
},
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
function toSection(file) {
|
|
289
|
+
return {
|
|
290
|
+
path: file.displayPath,
|
|
291
|
+
originalNormalized: file.originalNormalized,
|
|
292
|
+
result: file.result,
|
|
293
|
+
originalHashes: file.originalHashes,
|
|
294
|
+
resultHashes: file.resultHashes,
|
|
295
|
+
warnings: file.warnings,
|
|
296
|
+
driftNotice: file.driftNotice,
|
|
297
|
+
appliedCount: file.appliedCount,
|
|
298
|
+
noopCount: file.noopCount,
|
|
299
|
+
totalAddedLines: file.totalAddedLines,
|
|
300
|
+
totalRemovedLines: file.totalRemovedLines,
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Register the `batch_edit` tool on the calling agent's scope.
|
|
305
|
+
* @param _rootCtx - host context.
|
|
306
|
+
* @param agentCtx - the agent's scoped context (own scope layer).
|
|
307
|
+
* @param io - the filesystem bridge.
|
|
308
|
+
* @returns the exact disposer that unregisters the tool.
|
|
309
|
+
*/
|
|
310
|
+
export function buildBatchEditTool(io) {
|
|
311
|
+
return defineTool({
|
|
312
|
+
name: 'batch_edit',
|
|
313
|
+
description: BATCH_EDIT_DESCRIPTION,
|
|
314
|
+
parameters: {
|
|
315
|
+
edits: {
|
|
316
|
+
type: 'array',
|
|
317
|
+
required: true,
|
|
318
|
+
description: `Ordered list of edits, each with the same shape as the edit tool: { path?, remove_from, remove_to, replacement_text }. ` +
|
|
319
|
+
'Edits to the same file are applied in order and verified against what was served before anything is written. ' +
|
|
320
|
+
'The batch is all-or-nothing: if any edit fails validation, nothing is written and the failing edit\u2019s current range is served back. ' +
|
|
321
|
+
'Use batch_edit when you have multiple edits; do not issue several edit calls in one message.',
|
|
322
|
+
items: {
|
|
323
|
+
type: 'object',
|
|
324
|
+
additionalProperties: false,
|
|
325
|
+
properties: {
|
|
326
|
+
path: pathSchema,
|
|
327
|
+
remove_from: removeFromSchema,
|
|
328
|
+
remove_to: removeToSchema,
|
|
329
|
+
replacement_text: replacementTextSchema,
|
|
330
|
+
},
|
|
331
|
+
},
|
|
332
|
+
},
|
|
333
|
+
},
|
|
334
|
+
output: {
|
|
335
|
+
schema: { type: 'string' },
|
|
336
|
+
render: (_args, value) => [{ type: 'text', text: value }],
|
|
337
|
+
},
|
|
338
|
+
async execute(args, exec) {
|
|
339
|
+
const cwd = execCwd(exec);
|
|
340
|
+
const sessionKey = execSessionKey(exec);
|
|
341
|
+
const signal = exec.signal;
|
|
342
|
+
const canonical = normReq(args);
|
|
343
|
+
if (isRec(canonical) && Array.isArray(canonical.edits)) {
|
|
344
|
+
canonical.edits = canonical.edits.map((item) => {
|
|
345
|
+
if (!isRec(item))
|
|
346
|
+
return item;
|
|
347
|
+
const cloned = { ...item };
|
|
348
|
+
normalizeFilePath(cloned);
|
|
349
|
+
return cloned;
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
assertBatchReq(canonical);
|
|
353
|
+
const items = await prepareItems(io, canonical, cwd, signal);
|
|
354
|
+
const groups = groupByPath(items);
|
|
355
|
+
const processed = [];
|
|
356
|
+
for (const groupItems of groups.values()) {
|
|
357
|
+
abortIf(signal);
|
|
358
|
+
processed.push(await processFile(io, groupItems, cwd, {
|
|
359
|
+
signal,
|
|
360
|
+
sessionKey,
|
|
361
|
+
}));
|
|
362
|
+
}
|
|
363
|
+
const undos = [];
|
|
364
|
+
for (const file of processed) {
|
|
365
|
+
if (file.appliedCount === 0)
|
|
366
|
+
continue;
|
|
367
|
+
const undo = await saveUndo(file.absolutePath, {
|
|
368
|
+
content: file.originalNormalized,
|
|
369
|
+
bom: file.bom,
|
|
370
|
+
originalEnding: file.originalEnding,
|
|
371
|
+
hashes: file.originalHashes,
|
|
372
|
+
resultContent: file.result,
|
|
373
|
+
});
|
|
374
|
+
if (!undo.persisted) {
|
|
375
|
+
for (const u of undos) {
|
|
376
|
+
try {
|
|
377
|
+
await u.restore();
|
|
378
|
+
}
|
|
379
|
+
catch (error) {
|
|
380
|
+
console.error('Failed to restore undo entry after batch abort:', error);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
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.');
|
|
384
|
+
}
|
|
385
|
+
undos.push({ file, restore: undo.restore });
|
|
386
|
+
}
|
|
387
|
+
const written = [];
|
|
388
|
+
try {
|
|
389
|
+
for (const u of undos) {
|
|
390
|
+
abortIf(signal);
|
|
391
|
+
await io.writeText(u.file.absolutePath, u.file.bom + restoreEndings(u.file.result, u.file.originalEnding), signal);
|
|
392
|
+
written.push(u);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
catch (error) {
|
|
396
|
+
for (const w of written) {
|
|
397
|
+
try {
|
|
398
|
+
await io.writeText(w.file.absolutePath, w.file.bom +
|
|
399
|
+
restoreEndings(w.file.originalNormalized, w.file.originalEnding));
|
|
400
|
+
}
|
|
401
|
+
catch (restoreError) {
|
|
402
|
+
console.error('Failed to restore file after batch write failure:', restoreError);
|
|
403
|
+
}
|
|
404
|
+
try {
|
|
405
|
+
await w.restore();
|
|
406
|
+
}
|
|
407
|
+
catch (restoreError) {
|
|
408
|
+
console.error('Failed to restore undo entry after batch write failure:', restoreError);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
throw error;
|
|
412
|
+
}
|
|
413
|
+
const result = buildBatchResult(processed.map(toSection));
|
|
414
|
+
if (result.details.servedRows && result.details.servedRows.length > 0) {
|
|
415
|
+
const byPath = result.details.servedByPath ?? [];
|
|
416
|
+
for (const entry of byPath) {
|
|
417
|
+
if (entry.servedRows.length === 0)
|
|
418
|
+
continue;
|
|
419
|
+
const file = processed.find((f) => f.displayPath === entry.path);
|
|
420
|
+
if (file) {
|
|
421
|
+
await recordServedTruncated(sessionKey, file.absolutePath, entry.servedRows, splitLines(file.result).length, file.range.startLine - 1);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
return result.content[0].text;
|
|
426
|
+
},
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* Register the hashline tool on the calling agent’s scope (own layer).
|
|
431
|
+
*/
|
|
432
|
+
export function registerBatchEditTool(_rootCtx, agentCtx, io) {
|
|
433
|
+
return agentCtx.tools.register(buildBatchEditTool(io));
|
|
434
|
+
}
|
package/lib/tool-edit.js
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The dsh `edit` tool: hash-anchored literal range edits that shadow the
|
|
3
|
+
* built-in `edit` on the agent's own scope layer. Registered through the
|
|
4
|
+
* agent context so the model-facing contract (remove_from/remove_to hashes,
|
|
5
|
+
* served-range verification, reject-and-serve) replaces the built-in one.
|
|
6
|
+
* @module dsh-better-edit/tool-edit
|
|
7
|
+
*/
|
|
8
|
+
import { defineTool } from '@deepseek-ai/dsh-tools';
|
|
9
|
+
import { restoreEndings } from './edit-diff.js';
|
|
10
|
+
import { normReq } from './edit-normalize.js';
|
|
11
|
+
import { abortIf, isRec, splitLines } from './utils.js';
|
|
12
|
+
import { assertReq, execPipeline, resolveMissingPath, snapshotIdFor, } from './edit-pipeline.js';
|
|
13
|
+
import { buildRangeEcho, fmtServedRows, recordEchoServes, } from './hashline/served.js';
|
|
14
|
+
import { saveUndo } from './undo-edit.js';
|
|
15
|
+
import { clearNoopLoop, noopPayloadKey, trackNoopPayload } from './noop-guard.js';
|
|
16
|
+
import { buildNoop, buildChanged } from './edit-response.js';
|
|
17
|
+
import { recordServedTruncated } from './served-store.js';
|
|
18
|
+
import { NOOP_LOOP_THRESHOLD } from './constants.js';
|
|
19
|
+
import { EDIT_DESCRIPTION } from './prompts.js';
|
|
20
|
+
import { pathSchema, removeFromSchema, removeToSchema, replacementTextSchema } from './schema.js';
|
|
21
|
+
import { execCwd, execSessionKey } from './dsh-context.js';
|
|
22
|
+
/**
|
|
23
|
+
* Register the hash-anchored `edit` tool on the calling agent's scope.
|
|
24
|
+
* @param _rootCtx - host context (logger, lifecycle).
|
|
25
|
+
* @param agentCtx - the agent's scoped context; registrations here land on the
|
|
26
|
+
* agent's OWN scope layer, shadowing the preset's built-in `edit`.
|
|
27
|
+
* @param io - the filesystem bridge (ctx.fs backed in deployment).
|
|
28
|
+
* @returns the exact disposer that unregisters the tool.
|
|
29
|
+
*/
|
|
30
|
+
export function buildEditTool(io) {
|
|
31
|
+
return defineTool({
|
|
32
|
+
name: 'edit',
|
|
33
|
+
description: EDIT_DESCRIPTION,
|
|
34
|
+
parameters: {
|
|
35
|
+
path: pathSchema,
|
|
36
|
+
remove_from: removeFromSchema,
|
|
37
|
+
remove_to: removeToSchema,
|
|
38
|
+
replacement_text: replacementTextSchema,
|
|
39
|
+
},
|
|
40
|
+
output: {
|
|
41
|
+
schema: { type: 'string' },
|
|
42
|
+
render: (_args, value) => [{ type: 'text', text: value }],
|
|
43
|
+
},
|
|
44
|
+
async execute(args, exec) {
|
|
45
|
+
const cwd = execCwd(exec);
|
|
46
|
+
const sessionKey = execSessionKey(exec);
|
|
47
|
+
const signal = exec.signal;
|
|
48
|
+
const canonical = normReq(args);
|
|
49
|
+
const resolution = isRec(canonical)
|
|
50
|
+
? await resolveMissingPath(canonical)
|
|
51
|
+
: undefined;
|
|
52
|
+
if (resolution && isRec(canonical)) {
|
|
53
|
+
canonical.path = resolution.path;
|
|
54
|
+
}
|
|
55
|
+
assertReq(canonical);
|
|
56
|
+
const normalizedParams = canonical;
|
|
57
|
+
const path = normalizedParams.path;
|
|
58
|
+
abortIf(signal);
|
|
59
|
+
const pipeline = await execPipeline(io, normalizedParams, cwd, {
|
|
60
|
+
signal,
|
|
61
|
+
sessionKey,
|
|
62
|
+
});
|
|
63
|
+
const { originalNormalized, originalHashes, result, bom, originalEnding, hadUtf8DecodeErrors, warnings, noopEdit, firstChangedLine, lastChangedLine, resultHashes, totalAddedLines, totalRemovedLines, driftNotice, range, absolutePath, } = pipeline;
|
|
64
|
+
if (resolution) {
|
|
65
|
+
warnings.unshift(resolution.warning);
|
|
66
|
+
}
|
|
67
|
+
const editsAttempted = 1;
|
|
68
|
+
if (originalNormalized === result) {
|
|
69
|
+
const payload = noopPayloadKey(absolutePath, canonical.remove_from, canonical.remove_to, canonical.replacement_text);
|
|
70
|
+
const count = trackNoopPayload(absolutePath, payload);
|
|
71
|
+
if (count >= NOOP_LOOP_THRESHOLD) {
|
|
72
|
+
const echoRows = buildRangeEcho(range.startLine, range.endLine, originalHashes);
|
|
73
|
+
const echo = fmtServedRows(echoRows, splitLines(originalNormalized));
|
|
74
|
+
await recordEchoServes(sessionKey, absolutePath, echoRows, 'live');
|
|
75
|
+
throw new Error(`[E_NOOP_LOOP] This exact edit (anchors ${canonical.remove_from} to ${canonical.remove_to} in ${path}) has been submitted ${count} times and produced no changes each time — the range already contains the replacement text. Do not resend this edit; it will never change the file. Current range:\n${echo}`);
|
|
76
|
+
}
|
|
77
|
+
if (count === 2) {
|
|
78
|
+
warnings.push(`[E_NOOP_LOOP] Notice: this exact edit (anchors ${canonical.remove_from} to ${canonical.remove_to} in ${path}) has produced no changes twice in a row. The range already contains the replacement text; resending it again will be rejected.`);
|
|
79
|
+
}
|
|
80
|
+
const noopSnapshotId = await snapshotIdFor(io, absolutePath, signal);
|
|
81
|
+
const noopResult = buildNoop({
|
|
82
|
+
path,
|
|
83
|
+
noopEdit,
|
|
84
|
+
snapshotId: noopSnapshotId,
|
|
85
|
+
editMeta: {
|
|
86
|
+
editsAttempted,
|
|
87
|
+
noopEditsCount: noopEdit ? 1 : 0,
|
|
88
|
+
addedLines: 0,
|
|
89
|
+
removedLines: 0,
|
|
90
|
+
},
|
|
91
|
+
warnings,
|
|
92
|
+
driftNotice,
|
|
93
|
+
});
|
|
94
|
+
return noopResult.content[0].text;
|
|
95
|
+
}
|
|
96
|
+
clearNoopLoop(absolutePath);
|
|
97
|
+
if (hadUtf8DecodeErrors) {
|
|
98
|
+
warnings.push('Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.');
|
|
99
|
+
}
|
|
100
|
+
abortIf(signal);
|
|
101
|
+
const undo = await saveUndo(absolutePath, {
|
|
102
|
+
content: originalNormalized,
|
|
103
|
+
bom,
|
|
104
|
+
originalEnding,
|
|
105
|
+
hashes: originalHashes,
|
|
106
|
+
resultContent: result,
|
|
107
|
+
});
|
|
108
|
+
if (!undo.persisted) {
|
|
109
|
+
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.`);
|
|
110
|
+
}
|
|
111
|
+
try {
|
|
112
|
+
abortIf(signal);
|
|
113
|
+
await io.writeText(absolutePath, bom + restoreEndings(result, originalEnding), signal);
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
await undo.restore();
|
|
117
|
+
throw error;
|
|
118
|
+
}
|
|
119
|
+
const updatedSnapshotId = await snapshotIdFor(io, absolutePath, signal);
|
|
120
|
+
const editMeta = {
|
|
121
|
+
editsAttempted,
|
|
122
|
+
noopEditsCount: noopEdit ? 1 : 0,
|
|
123
|
+
firstChangedLine,
|
|
124
|
+
lastChangedLine,
|
|
125
|
+
addedLines: totalAddedLines,
|
|
126
|
+
removedLines: totalRemovedLines,
|
|
127
|
+
};
|
|
128
|
+
const successInput = {
|
|
129
|
+
path,
|
|
130
|
+
originalNormalized,
|
|
131
|
+
originalHashes,
|
|
132
|
+
result,
|
|
133
|
+
resultHashes,
|
|
134
|
+
warnings,
|
|
135
|
+
snapshotId: updatedSnapshotId,
|
|
136
|
+
editMeta,
|
|
137
|
+
driftNotice,
|
|
138
|
+
};
|
|
139
|
+
const changed = buildChanged(successInput);
|
|
140
|
+
if (changed.details.servedRows && changed.details.servedRows.length > 0) {
|
|
141
|
+
await recordServedTruncated(sessionKey, absolutePath, changed.details.servedRows, splitLines(result).length, range.startLine - 1);
|
|
142
|
+
}
|
|
143
|
+
return changed.content[0].text;
|
|
144
|
+
},
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Register the hashline tool on the calling agent’s scope (own layer).
|
|
149
|
+
*/
|
|
150
|
+
export function registerEditTool(_rootCtx, agentCtx, io) {
|
|
151
|
+
return agentCtx.tools.register(buildEditTool(io));
|
|
152
|
+
}
|
package/lib/tool-read.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The dsh `read` tool: hash-anchored reads (`HASH│content` rows) that shadow
|
|
3
|
+
* the built-in `read` on the agent's own scope layer. Every shown row is
|
|
4
|
+
* recorded as served, so a later `edit` can verify the model was actually
|
|
5
|
+
* shown the lines it targets.
|
|
6
|
+
* @module dsh-better-edit/tool-read
|
|
7
|
+
*/
|
|
8
|
+
import { defineTool } from '@deepseek-ai/dsh-tools';
|
|
9
|
+
import { normReq } from './edit-normalize.js';
|
|
10
|
+
import { abortIf, isRec, rejectUnknownFields } from './utils.js';
|
|
11
|
+
import { normFromText } from './file-reader.js';
|
|
12
|
+
import { fmtReadPreview, MAX_HASH_LINES } from './read-render.js';
|
|
13
|
+
import { recordServed, clearDriftReported } from './served-store.js';
|
|
14
|
+
import { READ_DESCRIPTION } from './prompts.js';
|
|
15
|
+
import { pathSchema } from './schema.js';
|
|
16
|
+
import { execCwd, execSessionKey } from './dsh-context.js';
|
|
17
|
+
const ROOT_KS = new Set(['path', 'offset', 'limit']);
|
|
18
|
+
function assertReadReq(request) {
|
|
19
|
+
if (!isRec(request)) {
|
|
20
|
+
throw new Error('[E_BAD_SHAPE] Read request must be an object.');
|
|
21
|
+
}
|
|
22
|
+
rejectUnknownFields(request, ROOT_KS, 'Read request');
|
|
23
|
+
if (typeof request.path !== 'string' || request.path.length === 0) {
|
|
24
|
+
throw new Error('[E_BAD_SHAPE] Read request requires a non-empty "path" string.');
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Register the hash-anchored `read` tool on the calling agent's scope.
|
|
29
|
+
* @param _rootCtx - host context.
|
|
30
|
+
* @param agentCtx - the agent's scoped context (own scope layer).
|
|
31
|
+
* @param io - the filesystem bridge.
|
|
32
|
+
* @returns the exact disposer that unregisters the tool.
|
|
33
|
+
*/
|
|
34
|
+
export function buildReadTool(io) {
|
|
35
|
+
return defineTool({
|
|
36
|
+
name: 'read',
|
|
37
|
+
description: READ_DESCRIPTION,
|
|
38
|
+
parameters: {
|
|
39
|
+
path: pathSchema,
|
|
40
|
+
offset: {
|
|
41
|
+
type: 'number',
|
|
42
|
+
description: 'Line number to start reading from (1-indexed)',
|
|
43
|
+
},
|
|
44
|
+
limit: {
|
|
45
|
+
type: 'number',
|
|
46
|
+
description: 'Maximum number of lines to read',
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
output: {
|
|
50
|
+
schema: { type: 'string' },
|
|
51
|
+
render: (_args, value) => [{ type: 'text', text: value }],
|
|
52
|
+
},
|
|
53
|
+
async execute(args, exec) {
|
|
54
|
+
const cwd = execCwd(exec);
|
|
55
|
+
const sessionKey = execSessionKey(exec);
|
|
56
|
+
const signal = exec.signal;
|
|
57
|
+
const canonical = normReq(args);
|
|
58
|
+
assertReadReq(canonical);
|
|
59
|
+
const rawPath = canonical.path;
|
|
60
|
+
abortIf(signal);
|
|
61
|
+
const absolutePath = await io.resolve(rawPath, cwd, signal);
|
|
62
|
+
const rawText = await io.readText(absolutePath, signal);
|
|
63
|
+
const { normalized, fileHashes, hadUtf8DecodeErrors } = await normFromText({
|
|
64
|
+
absolutePath,
|
|
65
|
+
rawText,
|
|
66
|
+
displayPath: rawPath,
|
|
67
|
+
signal,
|
|
68
|
+
maxLines: MAX_HASH_LINES,
|
|
69
|
+
});
|
|
70
|
+
const preview = await fmtReadPreview(normalized, { offset: canonical.offset, limit: canonical.limit }, fileHashes, absolutePath);
|
|
71
|
+
if (preview.served.length > 0) {
|
|
72
|
+
await recordServed(sessionKey, absolutePath, preview.served);
|
|
73
|
+
}
|
|
74
|
+
await clearDriftReported(sessionKey, absolutePath);
|
|
75
|
+
return hadUtf8DecodeErrors
|
|
76
|
+
? `${preview.text}\n\n[Non-UTF-8 bytes shown as U+FFFD; editing rewrites the file as UTF-8.]`
|
|
77
|
+
: preview.text;
|
|
78
|
+
},
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Register the hashline tool on the calling agent’s scope (own layer).
|
|
83
|
+
*/
|
|
84
|
+
export function registerReadTool(_rootCtx, agentCtx, io) {
|
|
85
|
+
return agentCtx.tools.register(buildReadTool(io));
|
|
86
|
+
}
|