dsh-rwkv-plugin 0.0.0-stage → 0.2.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 +21 -0
- package/README.md +50 -2
- package/cordis.patch.yml +59 -0
- package/lib/client.js +3148 -0
- package/lib/client.js.map +7 -0
- package/lib/index.js +6294 -0
- package/lib/index.js.map +7 -0
- package/lib/line-edit.js +1423 -0
- package/lib/line-edit.js.map +7 -0
- package/lib/todo.js +610 -0
- package/lib/todo.js.map +7 -0
- package/package.json +72 -4
- package/scripts/build.mjs +77 -0
- package/scripts/headless.ts +279 -0
- package/scripts/link-dsh.sh +31 -0
- package/scripts/relay-e2e.mjs +157 -0
- package/scripts/smoke.ts +116 -0
- package/scripts/state.ts +39 -0
- package/scripts/tokenizer-parity.ts +107 -0
- package/scripts/trace-stats.ts +33 -0
- package/src/adapter.ts +388 -0
- package/src/backend/generator.ts +221 -0
- package/src/backend/irwkv.ts +117 -0
- package/src/backend/lightning.ts +228 -0
- package/src/backend/stream.ts +97 -0
- package/src/client/AdapterPicker.tsx +264 -0
- package/src/client/DeveloperPanel.tsx +403 -0
- package/src/client/FoldNode.tsx +82 -0
- package/src/client/ModelCard.tsx +230 -0
- package/src/client/RwkvSettings.tsx +265 -0
- package/src/client/Segment.tsx +15 -0
- package/src/client/StatePicker.tsx +248 -0
- package/src/client/TraceFrames.tsx +462 -0
- package/src/client/TraceView.tsx +77 -0
- package/src/client/WirePanel.tsx +566 -0
- package/src/client/fields.tsx +362 -0
- package/src/client/index.tsx +109 -0
- package/src/client/styles.ts +277 -0
- package/src/client/traces-api.ts +222 -0
- package/src/client/url.ts +20 -0
- package/src/core/agent.ts +586 -0
- package/src/core/defaults.ts +51 -0
- package/src/core/dsh-prompt.ts +32 -0
- package/src/core/edit-modes/index.ts +108 -0
- package/src/core/edit-modes/line-edit.ts +793 -0
- package/src/core/edit-modes/literal.ts +26 -0
- package/src/core/edit-modes/shared.ts +213 -0
- package/src/core/edit-modes/tolerant.ts +558 -0
- package/src/core/fold-pairs.ts +407 -0
- package/src/core/fold-window.ts +563 -0
- package/src/core/line-edit.ts +33 -0
- package/src/core/parse.ts +290 -0
- package/src/core/policy.ts +500 -0
- package/src/core/prompt.ts +220 -0
- package/src/core/relay.ts +400 -0
- package/src/core/step-gates.ts +371 -0
- package/src/core/time-zone.ts +32 -0
- package/src/core/todo-state.ts +227 -0
- package/src/core/tolerant-edit.ts +14 -0
- package/src/core/tool-mappings.ts +209 -0
- package/src/core/tool-repairs.ts +255 -0
- package/src/core/tools.ts +162 -0
- package/src/core/worklist.ts +606 -0
- package/src/dsh-host.ts +48 -0
- package/src/edit-modes/folded-read-guard.ts +32 -0
- package/src/edit-modes/index.ts +26 -0
- package/src/edit-modes/line-edit.ts +154 -0
- package/src/edit-modes/literal.ts +9 -0
- package/src/edit-modes/observations.ts +234 -0
- package/src/edit-modes/syntax-check.ts +226 -0
- package/src/edit-modes/tolerant.ts +232 -0
- package/src/folded-read-guard.ts +6 -0
- package/src/history.ts +163 -0
- package/src/index.ts +287 -0
- package/src/line-edit.ts +15 -0
- package/src/live-wire.ts +133 -0
- package/src/paths.ts +91 -0
- package/src/relay-store.ts +59 -0
- package/src/result-budget.ts +225 -0
- package/src/routes.ts +324 -0
- package/src/session-setup.ts +150 -0
- package/src/syntax-check.ts +2 -0
- package/src/todo.ts +328 -0
- package/src/tokenizer.ts +48 -0
- package/src/tolerant-edit.ts +2 -0
- package/src/trace-stats.ts +225 -0
- package/src/traces.ts +289 -0
- package/vendor/rwkv-tokenizer/NOTICE.md +26 -0
- package/vendor/rwkv-tokenizer/package.json +5 -0
- package/vendor/rwkv-tokenizer/rwkv_tokenizer.d.ts +11 -0
- package/vendor/rwkv-tokenizer/rwkv_tokenizer.js +280 -0
- package/vendor/rwkv-tokenizer/rwkv_tokenizer_bg.wasm +0 -0
package/lib/line-edit.js
ADDED
|
@@ -0,0 +1,1423 @@
|
|
|
1
|
+
// src/edit-modes/line-edit.ts
|
|
2
|
+
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
3
|
+
|
|
4
|
+
// src/core/edit-modes/shared.ts
|
|
5
|
+
var pluralLines = (count) => `${count} line${count === 1 ? "" : "s"}`;
|
|
6
|
+
function splitDocumentLines(text) {
|
|
7
|
+
const eol = text.includes("\r\n") ? "\r\n" : "\n";
|
|
8
|
+
const normalized = eol === "\r\n" ? text.replace(/\r\n/g, "\n") : text;
|
|
9
|
+
const trailingNewline = normalized.endsWith("\n");
|
|
10
|
+
const lines = normalized === "" ? [] : (trailingNewline ? normalized.slice(0, -1) : normalized).split("\n");
|
|
11
|
+
return { eol, trailingNewline, lines };
|
|
12
|
+
}
|
|
13
|
+
function joinDocumentLines(after, eol, trailingNewline, wasEmpty) {
|
|
14
|
+
const keepNewline = trailingNewline || wasEmpty && after.length > 0;
|
|
15
|
+
const joined = after.join("\n") + (keepNewline && after.length > 0 ? "\n" : "");
|
|
16
|
+
return eol === "\r\n" ? joined.replace(/\n/g, "\r\n") : joined;
|
|
17
|
+
}
|
|
18
|
+
function renderWindow(displayPath, lines, from, to) {
|
|
19
|
+
if (lines.length === 0) return `=== ${displayPath} (empty file, 0 lines) ===`;
|
|
20
|
+
const first = Math.max(1, Math.min(lines.length, from));
|
|
21
|
+
const last = Math.max(first, Math.min(lines.length, to));
|
|
22
|
+
const out = [`=== ${displayPath} (lines ${first}-${last} of ${lines.length}) ===`];
|
|
23
|
+
if (first > 1) out.push(`(${pluralLines(first - 1)} above)`);
|
|
24
|
+
for (let n = first; n <= last; n++) out.push(`${n}: ${lines[n - 1]}`);
|
|
25
|
+
if (last < lines.length) out.push(`(${pluralLines(lines.length - last)} below)`);
|
|
26
|
+
return out.join("\n");
|
|
27
|
+
}
|
|
28
|
+
function addSeen(seen, first, last) {
|
|
29
|
+
if (seen === "all") return seen;
|
|
30
|
+
const next = new Set(seen);
|
|
31
|
+
for (let n = Math.max(1, first); n <= last; n++) next.add(n);
|
|
32
|
+
return next;
|
|
33
|
+
}
|
|
34
|
+
function unseenLines(seen, edit, total) {
|
|
35
|
+
if (seen === "all") return [];
|
|
36
|
+
const { startLine: start, endLine: end } = edit;
|
|
37
|
+
if (end >= start) {
|
|
38
|
+
const missing = [];
|
|
39
|
+
for (let n = start; n <= end; n++) if (!seen.has(n)) missing.push(n);
|
|
40
|
+
return missing;
|
|
41
|
+
}
|
|
42
|
+
const neighbours = [start - 1, start].filter((n) => n >= 1 && n <= total);
|
|
43
|
+
return neighbours.length === 0 || neighbours.some((n) => seen.has(n)) ? [] : neighbours;
|
|
44
|
+
}
|
|
45
|
+
function seenAfterBatchEdit(seen, hunks, afterTotal, contextLines = 3) {
|
|
46
|
+
if (seen === "all") return seen;
|
|
47
|
+
const ordered = [...hunks].sort((a, b) => a.startLine - b.startLine);
|
|
48
|
+
const next = /* @__PURE__ */ new Set();
|
|
49
|
+
for (const n of seen) {
|
|
50
|
+
let shift = 0;
|
|
51
|
+
let overwritten = false;
|
|
52
|
+
for (const h of ordered) {
|
|
53
|
+
if (h.endLine >= h.startLine && n >= h.startLine && n <= h.endLine) {
|
|
54
|
+
overwritten = true;
|
|
55
|
+
break;
|
|
56
|
+
}
|
|
57
|
+
if (n > h.endLine || h.endLine < h.startLine && n >= h.startLine) {
|
|
58
|
+
shift += h.added - h.removed;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (!overwritten && n + shift >= 1 && n + shift <= afterTotal) {
|
|
62
|
+
next.add(n + shift);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
let cumulativeDelta = 0;
|
|
66
|
+
for (const h of ordered) {
|
|
67
|
+
const postStart = h.startLine + cumulativeDelta;
|
|
68
|
+
const from = Math.max(1, postStart - contextLines);
|
|
69
|
+
const to = Math.min(afterTotal, postStart + Math.max(h.added, 1) - 1 + contextLines);
|
|
70
|
+
for (let n = from; n <= to; n++) next.add(n);
|
|
71
|
+
cumulativeDelta += h.added - h.removed;
|
|
72
|
+
}
|
|
73
|
+
return next;
|
|
74
|
+
}
|
|
75
|
+
function formatRanges(lines) {
|
|
76
|
+
const sorted = [...lines].sort((a, b) => a - b);
|
|
77
|
+
const parts = [];
|
|
78
|
+
for (let i = 0; i < sorted.length; ) {
|
|
79
|
+
let j = i;
|
|
80
|
+
while (j + 1 < sorted.length && sorted[j + 1] === sorted[j] + 1) j++;
|
|
81
|
+
parts.push(sorted[i] === sorted[j] ? `${sorted[i]}` : `${sorted[i]}-${sorted[j]}`);
|
|
82
|
+
i = j + 1;
|
|
83
|
+
}
|
|
84
|
+
return parts.join(", ");
|
|
85
|
+
}
|
|
86
|
+
function unseenRejection(displayPath, missing, seen, total, contextLines = 3) {
|
|
87
|
+
const offset = Math.max(1, missing[0] - contextLines);
|
|
88
|
+
const shown = seen.size === 0 ? "you have seen none of it" : `you have seen lines ${formatRanges(seen)}`;
|
|
89
|
+
const which = missing.length === 1 ? `line ${missing[0]} of ${displayPath} has` : `lines ${formatRanges(missing)} of ${displayPath} have`;
|
|
90
|
+
return `Your edit was NOT applied: ${which} not been shown to you (the file has ${total} lines; ${shown}). Read them first (read with offset=${offset}), then edit by the numbers you see.`;
|
|
91
|
+
}
|
|
92
|
+
function sandboxPolicyFor(service, session) {
|
|
93
|
+
if (service === void 0) return void 0;
|
|
94
|
+
return service.resolve(session === void 0 ? {} : { session });
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// src/core/edit-modes/tolerant.ts
|
|
98
|
+
var indentOf = (line) => /^[ \t]*/.exec(line)[0];
|
|
99
|
+
var isBlank = (line) => line.trim() === "";
|
|
100
|
+
function bigrams(text) {
|
|
101
|
+
const map = /* @__PURE__ */ new Map();
|
|
102
|
+
for (let i = 0; i < text.length - 1; i++) {
|
|
103
|
+
const gram = text.slice(i, i + 2);
|
|
104
|
+
map.set(gram, (map.get(gram) ?? 0) + 1);
|
|
105
|
+
}
|
|
106
|
+
return map;
|
|
107
|
+
}
|
|
108
|
+
function similarity(a, b) {
|
|
109
|
+
if (a === b) return 1;
|
|
110
|
+
if (a.length < 2 || b.length < 2) return 0;
|
|
111
|
+
const x = bigrams(a);
|
|
112
|
+
const y = bigrams(b);
|
|
113
|
+
let shared = 0;
|
|
114
|
+
for (const [gram, count] of x) shared += Math.min(count, y.get(gram) ?? 0);
|
|
115
|
+
return 2 * shared / (a.length - 1 + b.length - 1);
|
|
116
|
+
}
|
|
117
|
+
function reindent(text, indents) {
|
|
118
|
+
if (indents.every(([from, to]) => from === to)) return text;
|
|
119
|
+
const map = /* @__PURE__ */ new Map();
|
|
120
|
+
for (const [from, to] of indents) if (!map.has(from)) map.set(from, to);
|
|
121
|
+
let spacesPerTab = 0;
|
|
122
|
+
let tabToSpaces = 0;
|
|
123
|
+
for (const [from, to] of indents) {
|
|
124
|
+
if (!spacesPerTab && /^ +$/.test(from) && /^\t+$/.test(to) && from.length % to.length === 0) spacesPerTab = from.length / to.length;
|
|
125
|
+
if (!tabToSpaces && /^\t+$/.test(from) && /^ +$/.test(to) && to.length % from.length === 0) tabToSpaces = to.length / from.length;
|
|
126
|
+
}
|
|
127
|
+
return text.split("\n").map((line) => {
|
|
128
|
+
if (isBlank(line)) return line;
|
|
129
|
+
const ws = indentOf(line);
|
|
130
|
+
const mapped = map.get(ws);
|
|
131
|
+
if (mapped !== void 0) return mapped + line.slice(ws.length);
|
|
132
|
+
const from = [...map.keys()].filter((key) => ws.startsWith(key)).sort((a, b) => b.length - a.length)[0];
|
|
133
|
+
if (from === void 0) return line;
|
|
134
|
+
let rest = ws.slice(from.length);
|
|
135
|
+
if (spacesPerTab) rest = rest.replace(new RegExp(` {${spacesPerTab}}`, "g"), " ");
|
|
136
|
+
if (tabToSpaces) rest = rest.replace(/\t/g, " ".repeat(tabToSpaces));
|
|
137
|
+
return map.get(from) + rest + line.slice(ws.length);
|
|
138
|
+
}).join("\n");
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// src/core/edit-modes/line-edit.ts
|
|
142
|
+
var LINE_EDIT_CONTEXT_LINES = 3;
|
|
143
|
+
var ANCHOR_SEARCH_RADIUS = 15;
|
|
144
|
+
var END_ANCHOR_SEARCH_RADIUS = 10;
|
|
145
|
+
var ERROR_WINDOW_RADIUS = 8;
|
|
146
|
+
var MIN_WHOLE_FILE_ANCHOR_LEN = 10;
|
|
147
|
+
var TRIVIAL_ANCHORS = /* @__PURE__ */ new Set([
|
|
148
|
+
"{",
|
|
149
|
+
"}",
|
|
150
|
+
"(",
|
|
151
|
+
")",
|
|
152
|
+
"[",
|
|
153
|
+
"]",
|
|
154
|
+
"},",
|
|
155
|
+
"],",
|
|
156
|
+
");",
|
|
157
|
+
"};",
|
|
158
|
+
"else:",
|
|
159
|
+
"else {",
|
|
160
|
+
"} else {",
|
|
161
|
+
"try:",
|
|
162
|
+
"try {",
|
|
163
|
+
"finally:",
|
|
164
|
+
"finally {",
|
|
165
|
+
"pass",
|
|
166
|
+
"break",
|
|
167
|
+
"continue",
|
|
168
|
+
"return",
|
|
169
|
+
"return;",
|
|
170
|
+
"return None",
|
|
171
|
+
"return true",
|
|
172
|
+
"return false",
|
|
173
|
+
"end",
|
|
174
|
+
"fi",
|
|
175
|
+
"done",
|
|
176
|
+
"esac"
|
|
177
|
+
]);
|
|
178
|
+
var ELISION_LINE = /^\s*(?:\/\/|#|\/\*|--|<!--)?\s*(?:\.\.\.|…)\s*(?:existing|unchanged|rest|remaining|omitted|same|code|lines|more|snip|truncated)?[^\n]{0,40}(?:\*\/|-->)?\s*$/i;
|
|
179
|
+
var NUMBERED_PREFIX = /^(\d+): ?(.*)$/;
|
|
180
|
+
function indentOf2(line) {
|
|
181
|
+
return /^[ \t]*/.exec(line)?.[0] ?? "";
|
|
182
|
+
}
|
|
183
|
+
function normalizeAnchorLine(line) {
|
|
184
|
+
return line.normalize("NFKC").replace(/[\u2018\u2019\u201A\u201B]/g, "'").replace(/[\u201C\u201D\u201E\u201F]/g, '"').replace(/[\u2010-\u2015\u2212]/g, "-").replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g, " ").replace(/\s+/g, " ").trim();
|
|
185
|
+
}
|
|
186
|
+
function stripOptionalLinePrefix(text) {
|
|
187
|
+
const m = /^\s*\d+:\s?(.*)$/.exec(text);
|
|
188
|
+
return m ? m[1] : text;
|
|
189
|
+
}
|
|
190
|
+
function isNonTrivialAnchor(anchor, minLen = 8) {
|
|
191
|
+
if (typeof anchor !== "string") return false;
|
|
192
|
+
const cleaned = normalizeAnchorLine(stripOptionalLinePrefix(anchor));
|
|
193
|
+
if (cleaned.length < minLen) return false;
|
|
194
|
+
if (TRIVIAL_ANCHORS.has(cleaned)) return false;
|
|
195
|
+
return /[A-Za-z0-9_\u4e00-\u9fff]{3,}/.test(cleaned);
|
|
196
|
+
}
|
|
197
|
+
function lineAnchorScore(anchor, fileLine) {
|
|
198
|
+
const raw = stripOptionalLinePrefix(anchor);
|
|
199
|
+
const a = normalizeAnchorLine(raw);
|
|
200
|
+
const b = normalizeAnchorLine(fileLine);
|
|
201
|
+
if (a === "" && b === "") return 1;
|
|
202
|
+
if (a === "" || b === "") return 0;
|
|
203
|
+
if (a === b) return 1;
|
|
204
|
+
if (a.length >= 16 && b.startsWith(a)) return 0.96;
|
|
205
|
+
return similarity(a, b);
|
|
206
|
+
}
|
|
207
|
+
function newLinesOf(text) {
|
|
208
|
+
if (text === "") return [];
|
|
209
|
+
const normalized = text.replace(/\r\n/g, "\n");
|
|
210
|
+
return (normalized.endsWith("\n") ? normalized.slice(0, -1) : normalized).split("\n");
|
|
211
|
+
}
|
|
212
|
+
function stripNumberedReplacement(newLines, startLine, before) {
|
|
213
|
+
if (newLines.length === 0) return { lines: [], stripped: false };
|
|
214
|
+
const existingNear = before.slice(Math.max(0, startLine - 2), Math.min(before.length, startLine + 2));
|
|
215
|
+
if (existingNear.some((line) => NUMBERED_PREFIX.test(line))) {
|
|
216
|
+
return { lines: [...newLines], stripped: false };
|
|
217
|
+
}
|
|
218
|
+
const out = [];
|
|
219
|
+
let expected;
|
|
220
|
+
let numberedCount = 0;
|
|
221
|
+
for (const line of newLines) {
|
|
222
|
+
if (line === "") {
|
|
223
|
+
out.push("");
|
|
224
|
+
if (expected !== void 0) expected++;
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
const m = NUMBERED_PREFIX.exec(line);
|
|
228
|
+
if (!m) return { lines: [...newLines], stripped: false };
|
|
229
|
+
const num = Number(m[1]);
|
|
230
|
+
if (expected === void 0) {
|
|
231
|
+
if (Math.abs(num - startLine) > 20) return { lines: [...newLines], stripped: false };
|
|
232
|
+
expected = num + 1;
|
|
233
|
+
} else {
|
|
234
|
+
if (num !== expected) return { lines: [...newLines], stripped: false };
|
|
235
|
+
expected++;
|
|
236
|
+
}
|
|
237
|
+
numberedCount++;
|
|
238
|
+
out.push(m[2]);
|
|
239
|
+
}
|
|
240
|
+
if (numberedCount === 0 || numberedCount === 1 && newLines.length > 1) {
|
|
241
|
+
return { lines: [...newLines], stripped: false };
|
|
242
|
+
}
|
|
243
|
+
return { lines: out, stripped: true };
|
|
244
|
+
}
|
|
245
|
+
function pickUniqueAnchorHit(hits) {
|
|
246
|
+
if (hits.length === 0) return { kind: "none" };
|
|
247
|
+
const exact = hits.filter((h) => h.score >= 0.98);
|
|
248
|
+
if (exact.length === 1) return { kind: "unique", ln: exact[0].ln };
|
|
249
|
+
if (exact.length > 1) return { kind: "ambiguous", lines: exact.map((h) => h.ln) };
|
|
250
|
+
const sorted = [...hits].sort((a, b) => b.score - a.score);
|
|
251
|
+
const best = sorted[0];
|
|
252
|
+
const runner = sorted[1];
|
|
253
|
+
if (best.score >= 0.9 && (!runner || runner.score <= best.score - 0.08)) {
|
|
254
|
+
return { kind: "unique", ln: best.ln };
|
|
255
|
+
}
|
|
256
|
+
return { kind: "ambiguous", lines: sorted.slice(0, 4).map((h) => h.ln) };
|
|
257
|
+
}
|
|
258
|
+
function refineEndLineWithEndText(before, resolvedStart, resolvedEnd, endText, allowSelfHeal) {
|
|
259
|
+
if (resolvedEnd < resolvedStart || resolvedEnd > before.length) return { ok: false };
|
|
260
|
+
if (lineAnchorScore(endText, before[resolvedEnd - 1]) >= 0.9) {
|
|
261
|
+
return { ok: true, endLine: resolvedEnd };
|
|
262
|
+
}
|
|
263
|
+
if (!allowSelfHeal) return { ok: false };
|
|
264
|
+
const lo = Math.max(resolvedStart, resolvedEnd - END_ANCHOR_SEARCH_RADIUS);
|
|
265
|
+
const hi = Math.min(before.length, resolvedEnd + END_ANCHOR_SEARCH_RADIUS);
|
|
266
|
+
const hits = [];
|
|
267
|
+
for (let ln = lo; ln <= hi; ln++) {
|
|
268
|
+
const score = lineAnchorScore(endText, before[ln - 1]);
|
|
269
|
+
if (score >= 0.9) hits.push({ ln, score });
|
|
270
|
+
}
|
|
271
|
+
const picked = pickUniqueAnchorHit(hits);
|
|
272
|
+
if (picked.kind === "unique") {
|
|
273
|
+
return {
|
|
274
|
+
ok: true,
|
|
275
|
+
endLine: picked.ln,
|
|
276
|
+
note: `Auto-aligned edit end_line ${resolvedEnd} -> ${picked.ln} via end_text.`
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
return { ok: false };
|
|
280
|
+
}
|
|
281
|
+
function resolveSingleHunk(before, displayPath, edit, index, totalHunks, allowSelfHeal) {
|
|
282
|
+
const label = totalHunks > 1 ? `edit #${index + 1}` : "edit";
|
|
283
|
+
const { startLine: start, endLine: end } = edit;
|
|
284
|
+
const total = before.length;
|
|
285
|
+
if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end)) {
|
|
286
|
+
return `${label}: start_line and end_line must be whole numbers`;
|
|
287
|
+
}
|
|
288
|
+
if (start < 1) return `${label}: start_line must be 1 or more (got ${start})`;
|
|
289
|
+
if (start > total + 1) return `${label}: start_line ${start} is past the end: ${displayPath} has ${total} lines`;
|
|
290
|
+
if (end > total) return `${label}: end_line ${end} is past the end: ${displayPath} has ${total} lines`;
|
|
291
|
+
if (end < start - 1) {
|
|
292
|
+
return `${label}: end_line ${end} is before start_line ${start}; use end_line = start_line - 1 to insert without replacing`;
|
|
293
|
+
}
|
|
294
|
+
const isInsert = end === start - 1;
|
|
295
|
+
const rawAnchor = typeof edit.startText === "string" ? edit.startText : "";
|
|
296
|
+
const hasAnchor = rawAnchor.trim() !== "";
|
|
297
|
+
let resolvedStart = start;
|
|
298
|
+
let resolvedEnd = end;
|
|
299
|
+
let alignedNote;
|
|
300
|
+
let anchorVerified = false;
|
|
301
|
+
let endAnchorVerified = false;
|
|
302
|
+
let matchedAnchorLine;
|
|
303
|
+
if (hasAnchor && total > 0) {
|
|
304
|
+
const anchorTargetLine = isInsert ? start <= total ? start : total : start;
|
|
305
|
+
const directLine = before[anchorTargetLine - 1];
|
|
306
|
+
if (directLine !== void 0 && lineAnchorScore(rawAnchor, directLine) >= 0.9) {
|
|
307
|
+
anchorVerified = true;
|
|
308
|
+
matchedAnchorLine = directLine;
|
|
309
|
+
} else if (allowSelfHeal) {
|
|
310
|
+
const lo = Math.max(1, anchorTargetLine - ANCHOR_SEARCH_RADIUS);
|
|
311
|
+
const hi = Math.min(total, anchorTargetLine + ANCHOR_SEARCH_RADIUS);
|
|
312
|
+
const localHits = [];
|
|
313
|
+
for (let ln = lo; ln <= hi; ln++) {
|
|
314
|
+
const score = lineAnchorScore(rawAnchor, before[ln - 1]);
|
|
315
|
+
if (score >= 0.9) localHits.push({ ln, score });
|
|
316
|
+
}
|
|
317
|
+
const localExactHits = localHits.filter((h) => h.score >= 0.98);
|
|
318
|
+
const localPick = pickUniqueAnchorHit(localHits);
|
|
319
|
+
const localIsExact = localExactHits.length === 1 && localPick.kind === "unique" && localPick.ln === localExactHits[0].ln;
|
|
320
|
+
if (localIsExact) {
|
|
321
|
+
const shift = localPick.ln - anchorTargetLine;
|
|
322
|
+
const nextStart = start + shift;
|
|
323
|
+
const nextEnd = end + shift;
|
|
324
|
+
if (nextStart >= 1 && nextStart <= total + 1 && nextEnd <= total && nextEnd >= nextStart - 1) {
|
|
325
|
+
resolvedStart = nextStart;
|
|
326
|
+
resolvedEnd = nextEnd;
|
|
327
|
+
anchorVerified = true;
|
|
328
|
+
matchedAnchorLine = before[localPick.ln - 1];
|
|
329
|
+
alignedNote = `Auto-aligned ${label} lines ${start}-${end} -> ${resolvedStart}-${resolvedEnd} via start_text.`;
|
|
330
|
+
}
|
|
331
|
+
} else if (localExactHits.length > 1) {
|
|
332
|
+
const win = renderWindow(displayPath, before, Math.max(1, anchorTargetLine - ERROR_WINDOW_RADIUS), Math.min(total, anchorTargetLine + ERROR_WINDOW_RADIUS));
|
|
333
|
+
return `Your ${label} in ${displayPath} was NOT applied: start_text (${JSON.stringify(rawAnchor.trim())}) did not match line ${anchorTargetLine}, and matched multiple nearby lines (${localExactHits.map((h) => h.ln).join(", ")}).
|
|
334
|
+
|
|
335
|
+
Current lines around line ${anchorTargetLine}:
|
|
336
|
+
${win}`;
|
|
337
|
+
}
|
|
338
|
+
if (!anchorVerified && isNonTrivialAnchor(rawAnchor, MIN_WHOLE_FILE_ANCHOR_LEN)) {
|
|
339
|
+
const globalHits = [];
|
|
340
|
+
for (let ln = 1; ln <= total; ln++) {
|
|
341
|
+
const score = lineAnchorScore(rawAnchor, before[ln - 1]);
|
|
342
|
+
if (score >= 0.92) globalHits.push({ ln, score });
|
|
343
|
+
}
|
|
344
|
+
const globalExact = globalHits.filter((h) => h.score >= 0.98);
|
|
345
|
+
const globalPick = pickUniqueAnchorHit(globalHits);
|
|
346
|
+
if (globalPick.kind === "unique" && (globalExact.length === 1 || localPick.kind !== "unique")) {
|
|
347
|
+
const shift = globalPick.ln - anchorTargetLine;
|
|
348
|
+
const nextStart = start + shift;
|
|
349
|
+
const nextEnd = end + shift;
|
|
350
|
+
if (nextStart >= 1 && nextStart <= total + 1 && nextEnd <= total && nextEnd >= nextStart - 1) {
|
|
351
|
+
resolvedStart = nextStart;
|
|
352
|
+
resolvedEnd = nextEnd;
|
|
353
|
+
anchorVerified = true;
|
|
354
|
+
matchedAnchorLine = before[globalPick.ln - 1];
|
|
355
|
+
alignedNote = `Auto-aligned ${label} lines ${start}-${end} -> ${resolvedStart}-${resolvedEnd} via unique file-wide start_text.`;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
if (!anchorVerified && localPick.kind === "unique") {
|
|
360
|
+
const shift = localPick.ln - anchorTargetLine;
|
|
361
|
+
const nextStart = start + shift;
|
|
362
|
+
const nextEnd = end + shift;
|
|
363
|
+
if (nextStart >= 1 && nextStart <= total + 1 && nextEnd <= total && nextEnd >= nextStart - 1) {
|
|
364
|
+
resolvedStart = nextStart;
|
|
365
|
+
resolvedEnd = nextEnd;
|
|
366
|
+
anchorVerified = true;
|
|
367
|
+
matchedAnchorLine = before[localPick.ln - 1];
|
|
368
|
+
alignedNote = `Auto-aligned ${label} lines ${start}-${end} -> ${resolvedStart}-${resolvedEnd} via start_text.`;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
if (!anchorVerified) {
|
|
372
|
+
const win = renderWindow(displayPath, before, Math.max(1, anchorTargetLine - ERROR_WINDOW_RADIUS), Math.min(total, anchorTargetLine + ERROR_WINDOW_RADIUS));
|
|
373
|
+
const extraMatches = [];
|
|
374
|
+
for (let ln = 1; ln <= total; ln++) {
|
|
375
|
+
if (lineAnchorScore(rawAnchor, before[ln - 1]) >= 0.8) {
|
|
376
|
+
extraMatches.push(` ${ln}: ${before[ln - 1]}`);
|
|
377
|
+
if (extraMatches.length >= 4) break;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
const candHint = extraMatches.length > 0 ? `
|
|
381
|
+
Matching lines elsewhere in ${displayPath}:
|
|
382
|
+
${extraMatches.join("\n")}` : "";
|
|
383
|
+
return `Your ${label} in ${displayPath} was NOT applied: start_text (${JSON.stringify(rawAnchor.trim())}) did not match line ${anchorTargetLine} (${JSON.stringify(before[anchorTargetLine - 1]?.trim() ?? "")}).${candHint}
|
|
384
|
+
|
|
385
|
+
Current lines around line ${anchorTargetLine}:
|
|
386
|
+
${win}`;
|
|
387
|
+
}
|
|
388
|
+
} else {
|
|
389
|
+
const win = renderWindow(displayPath, before, Math.max(1, start - ERROR_WINDOW_RADIUS), Math.min(total, Math.max(end, start) + ERROR_WINDOW_RADIUS));
|
|
390
|
+
return `Your ${label} in ${displayPath} was NOT applied: start_text (${JSON.stringify(rawAnchor.trim())}) did not match line ${anchorTargetLine} (${JSON.stringify(before[anchorTargetLine - 1]?.trim() ?? "")}).
|
|
391
|
+
${win}`;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
if (!isInsert && typeof edit.endText === "string" && edit.endText.trim() !== "") {
|
|
395
|
+
const endCheck = refineEndLineWithEndText(before, resolvedStart, resolvedEnd, edit.endText, allowSelfHeal);
|
|
396
|
+
if (!endCheck.ok) {
|
|
397
|
+
const win = renderWindow(displayPath, before, Math.max(1, resolvedStart - 3), Math.min(total, resolvedEnd + ERROR_WINDOW_RADIUS));
|
|
398
|
+
return `Your ${label} in ${displayPath} was NOT applied: end_text (${JSON.stringify(edit.endText.trim())}) did not match line ${resolvedEnd} (${JSON.stringify(before[resolvedEnd - 1]?.trim() ?? "")}).
|
|
399
|
+
|
|
400
|
+
Current lines around line ${resolvedEnd}:
|
|
401
|
+
${win}`;
|
|
402
|
+
}
|
|
403
|
+
resolvedEnd = endCheck.endLine;
|
|
404
|
+
endAnchorVerified = true;
|
|
405
|
+
if (endCheck.note) {
|
|
406
|
+
alignedNote = alignedNote ? `${alignedNote} ${endCheck.note}` : endCheck.note;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
const rawNewLines = newLinesOf(edit.newText);
|
|
410
|
+
const { lines: strippedLines, stripped: strippedLineNumbers } = stripNumberedReplacement(rawNewLines, resolvedStart, before);
|
|
411
|
+
let newLines = strippedLines;
|
|
412
|
+
let reindented = false;
|
|
413
|
+
if (allowSelfHeal && matchedAnchorLine !== void 0 && newLines.length > 0 && hasAnchor) {
|
|
414
|
+
const anchorWithoutPrefix = stripOptionalLinePrefix(rawAnchor);
|
|
415
|
+
const oldIndent = indentOf2(anchorWithoutPrefix);
|
|
416
|
+
const fileIndent = indentOf2(matchedAnchorLine);
|
|
417
|
+
const firstNonBlank = newLines.find((line) => line.trim() !== "");
|
|
418
|
+
if (oldIndent !== fileIndent && firstNonBlank !== void 0 && oldIndent.length > 0 && firstNonBlank.startsWith(oldIndent)) {
|
|
419
|
+
const moved = reindent(newLines.join("\n"), [[oldIndent, fileIndent]]).split("\n");
|
|
420
|
+
if (moved.join("\n") !== newLines.join("\n")) {
|
|
421
|
+
newLines = moved;
|
|
422
|
+
reindented = true;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
const removedSlice = before.slice(resolvedStart - 1, resolvedEnd);
|
|
427
|
+
const oldTrimmedSet = new Set(removedSlice.map((line) => line.trim()));
|
|
428
|
+
for (const nl of newLines) {
|
|
429
|
+
if (ELISION_LINE.test(nl) && !oldTrimmedSet.has(nl.trim())) {
|
|
430
|
+
return `Your ${label} in ${displayPath} was NOT applied: new_text contains an elision placeholder (${JSON.stringify(nl.trim())}), which would delete code. Narrow start_line..end_line to only the lines changing and write complete replacement code.`;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
if (removedSlice.length === newLines.length && removedSlice.every((line, i) => line === newLines[i])) {
|
|
434
|
+
const spanStr = resolvedStart === resolvedEnd ? `line ${resolvedStart}` : `lines ${resolvedStart}-${resolvedEnd}`;
|
|
435
|
+
return `No edit needed in ${displayPath}: new_text is the same as ${spanStr}; nothing changed.`;
|
|
436
|
+
}
|
|
437
|
+
if (newLines.length >= 2 && resolvedStart > 1) {
|
|
438
|
+
const above = before[resolvedStart - 2].trim();
|
|
439
|
+
if (above.length >= 8 && newLines[0].trim() === above && !oldTrimmedSet.has(above)) {
|
|
440
|
+
const win = renderWindow(displayPath, before, Math.max(1, resolvedStart - 4), Math.min(total, Math.max(resolvedEnd, resolvedStart) + 4));
|
|
441
|
+
return `Your ${label} in ${displayPath} was NOT applied: the first line of new_text duplicates line ${resolvedStart - 1} (${JSON.stringify(above)}) immediately above start_line=${resolvedStart}. Drop that unchanged line from new_text or adjust start_line.
|
|
442
|
+
|
|
443
|
+
${win}`;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
if (newLines.length >= 2 && resolvedEnd < total) {
|
|
447
|
+
const below = before[resolvedEnd].trim();
|
|
448
|
+
if (below.length >= 8 && newLines[newLines.length - 1].trim() === below && !oldTrimmedSet.has(below)) {
|
|
449
|
+
const win = renderWindow(displayPath, before, Math.max(1, resolvedStart - 4), Math.min(total, Math.max(resolvedEnd, resolvedStart) + 4));
|
|
450
|
+
return `Your ${label} in ${displayPath} was NOT applied: the last line of new_text duplicates line ${resolvedEnd + 1} (${JSON.stringify(below)}) immediately below end_line=${resolvedEnd}. Drop that unchanged line from new_text or adjust end_line.
|
|
451
|
+
|
|
452
|
+
${win}`;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
return {
|
|
456
|
+
index,
|
|
457
|
+
requestedStart: start,
|
|
458
|
+
requestedEnd: end,
|
|
459
|
+
startLine: resolvedStart,
|
|
460
|
+
endLine: resolvedEnd,
|
|
461
|
+
newLines,
|
|
462
|
+
removed: removedSlice.length,
|
|
463
|
+
added: newLines.length,
|
|
464
|
+
strippedLineNumbers,
|
|
465
|
+
reindented,
|
|
466
|
+
...alignedNote ? { alignedNote } : {},
|
|
467
|
+
anchorVerified,
|
|
468
|
+
endAnchorVerified
|
|
469
|
+
};
|
|
470
|
+
}
|
|
471
|
+
function hunksOverlap(a, b) {
|
|
472
|
+
const aInsert = a.endLine < a.startLine;
|
|
473
|
+
const bInsert = b.endLine < b.startLine;
|
|
474
|
+
if (aInsert && bInsert) return a.startLine === b.startLine;
|
|
475
|
+
if (aInsert) return a.startLine > b.startLine && a.startLine <= b.endLine;
|
|
476
|
+
if (bInsert) return b.startLine > a.startLine && b.startLine <= a.endLine;
|
|
477
|
+
return a.startLine <= b.endLine && b.startLine <= a.endLine;
|
|
478
|
+
}
|
|
479
|
+
function applyAnchoredLineEdits(text, displayPath, edits, options = {}) {
|
|
480
|
+
if (edits.length === 0) return "edits must contain at least one edit hunk";
|
|
481
|
+
const allowSelfHeal = options.selfHeal !== false;
|
|
482
|
+
const { eol, trailingNewline, lines: before } = splitDocumentLines(text);
|
|
483
|
+
const resolved = [];
|
|
484
|
+
for (let i = 0; i < edits.length; i++) {
|
|
485
|
+
const out = resolveSingleHunk(before, displayPath, edits[i], i, edits.length, allowSelfHeal);
|
|
486
|
+
if (typeof out === "string") return out;
|
|
487
|
+
resolved.push(out);
|
|
488
|
+
}
|
|
489
|
+
const sortedAsc = [...resolved].sort((a, b) => a.startLine - b.startLine || a.endLine - b.endLine);
|
|
490
|
+
for (let i = 1; i < sortedAsc.length; i++) {
|
|
491
|
+
if (hunksOverlap(sortedAsc[i - 1], sortedAsc[i])) {
|
|
492
|
+
return `Your batch edit in ${displayPath} was NOT applied: edit #${sortedAsc[i - 1].index + 1} (lines ${sortedAsc[i - 1].startLine}-${sortedAsc[i - 1].endLine}) overlaps edit #${sortedAsc[i].index + 1} (lines ${sortedAsc[i].startLine}-${sortedAsc[i].endLine}). Combine overlapping edits into one range.`;
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
const after = [...before];
|
|
496
|
+
const sortedDesc = [...sortedAsc].reverse();
|
|
497
|
+
for (const h of sortedDesc) {
|
|
498
|
+
after.splice(h.startLine - 1, h.removed, ...h.newLines);
|
|
499
|
+
}
|
|
500
|
+
const content = joinDocumentLines(after, eol, trailingNewline, before.length === 0);
|
|
501
|
+
const totalRemoved = resolved.reduce((acc, h) => acc + h.removed, 0);
|
|
502
|
+
const totalAdded = resolved.reduce((acc, h) => acc + h.added, 0);
|
|
503
|
+
return { content, before, after, hunks: sortedAsc, totalRemoved, totalAdded };
|
|
504
|
+
}
|
|
505
|
+
function resultWindow(displayPath, start, added, after) {
|
|
506
|
+
return renderWindow(
|
|
507
|
+
displayPath,
|
|
508
|
+
after,
|
|
509
|
+
start - LINE_EDIT_CONTEXT_LINES,
|
|
510
|
+
start + Math.max(added, 1) - 1 + LINE_EDIT_CONTEXT_LINES
|
|
511
|
+
);
|
|
512
|
+
}
|
|
513
|
+
function editSummary(displayPath, edit, result) {
|
|
514
|
+
const start = result.resolvedStart ?? edit.startLine;
|
|
515
|
+
const end = result.resolvedEnd ?? edit.endLine;
|
|
516
|
+
const { removed, added } = result;
|
|
517
|
+
let what;
|
|
518
|
+
if (removed === 0) what = start > 1 ? `Inserted ${pluralLines(added)} after line ${start - 1}` : `Inserted ${pluralLines(added)} at the start`;
|
|
519
|
+
else if (added === 0) what = `Deleted lines ${start}-${end}`;
|
|
520
|
+
else what = `Replaced lines ${start}-${end} with ${pluralLines(added)}`;
|
|
521
|
+
const parts = [`File updated. ${what}.`];
|
|
522
|
+
if (result.alignedNote) parts.push(`(${result.alignedNote})`);
|
|
523
|
+
if (result.strippedLineNumbers) parts.push("(Stripped copied line-number prefixes from new_text.)");
|
|
524
|
+
if (result.reindented) parts.push("(Auto-aligned indentation to match the file.)");
|
|
525
|
+
const delta = added - removed;
|
|
526
|
+
if (delta !== 0 && end < result.before.length) {
|
|
527
|
+
parts.push(`Lines after it moved ${delta > 0 ? "down" : "up"} by ${Math.abs(delta)}: old line ${end + 1} is now line ${end + 1 + delta}.`);
|
|
528
|
+
}
|
|
529
|
+
parts.push("Review the change (correct indentation, no duplicate or missing lines) and edit again if necessary.");
|
|
530
|
+
return `${parts.join(" ")}
|
|
531
|
+
${resultWindow(displayPath, start, added, result.after)}`;
|
|
532
|
+
}
|
|
533
|
+
function batchEditSummary(displayPath, batch) {
|
|
534
|
+
if (batch.hunks.length === 1) {
|
|
535
|
+
const h = batch.hunks[0];
|
|
536
|
+
return editSummary(
|
|
537
|
+
displayPath,
|
|
538
|
+
{ startLine: h.startLine, endLine: h.endLine, newText: h.newLines.join("\n") },
|
|
539
|
+
{
|
|
540
|
+
content: batch.content,
|
|
541
|
+
before: batch.before,
|
|
542
|
+
after: batch.after,
|
|
543
|
+
removed: h.removed,
|
|
544
|
+
added: h.added,
|
|
545
|
+
resolvedStart: h.startLine,
|
|
546
|
+
resolvedEnd: h.endLine,
|
|
547
|
+
...h.alignedNote ? { alignedNote: h.alignedNote } : {},
|
|
548
|
+
anchorVerified: h.anchorVerified,
|
|
549
|
+
strippedLineNumbers: h.strippedLineNumbers,
|
|
550
|
+
reindented: h.reindented
|
|
551
|
+
}
|
|
552
|
+
);
|
|
553
|
+
}
|
|
554
|
+
const notes = [];
|
|
555
|
+
let cumulativeDelta = 0;
|
|
556
|
+
const windows = [];
|
|
557
|
+
for (const h of batch.hunks) {
|
|
558
|
+
const postStart = h.startLine + cumulativeDelta;
|
|
559
|
+
if (h.alignedNote) notes.push(h.alignedNote);
|
|
560
|
+
if (h.strippedLineNumbers) notes.push(`Stripped copied line-number prefixes in edit #${h.index + 1}.`);
|
|
561
|
+
if (h.reindented) notes.push(`Auto-aligned indentation in edit #${h.index + 1}.`);
|
|
562
|
+
windows.push(resultWindow(displayPath, postStart, h.added, batch.after));
|
|
563
|
+
cumulativeDelta += h.added - h.removed;
|
|
564
|
+
}
|
|
565
|
+
const parts = [`File updated with ${batch.hunks.length} atomic edits (${pluralLines(batch.totalRemoved)} removed, ${pluralLines(batch.totalAdded)} added).`];
|
|
566
|
+
if (notes.length > 0) parts.push(`(${notes.join(" ")})`);
|
|
567
|
+
parts.push("Review the updated windows below and edit again if necessary.");
|
|
568
|
+
return `${parts.join(" ")}
|
|
569
|
+
${windows.join("\n\n")}`;
|
|
570
|
+
}
|
|
571
|
+
function syntaxRejection(displayPath, edit, result, error) {
|
|
572
|
+
const start = result.resolvedStart ?? edit.startLine;
|
|
573
|
+
const end = result.resolvedEnd ?? edit.endLine;
|
|
574
|
+
const original = renderWindow(displayPath, result.before, start - LINE_EDIT_CONTEXT_LINES, Math.max(end, start) + LINE_EDIT_CONTEXT_LINES);
|
|
575
|
+
return [
|
|
576
|
+
"Your edit was NOT applied: it introduces a syntax error.",
|
|
577
|
+
`ERROR: ${error}`,
|
|
578
|
+
"",
|
|
579
|
+
"This is how the file would have looked:",
|
|
580
|
+
resultWindow(displayPath, start, result.added, result.after),
|
|
581
|
+
"",
|
|
582
|
+
"This is the original code before your edit:",
|
|
583
|
+
original,
|
|
584
|
+
"",
|
|
585
|
+
"Fix start_line/end_line or new_text (check the indentation) and try again. Do not repeat the same edit."
|
|
586
|
+
].join("\n");
|
|
587
|
+
}
|
|
588
|
+
function batchSyntaxRejection(displayPath, batch, error) {
|
|
589
|
+
if (batch.hunks.length === 1) {
|
|
590
|
+
const h = batch.hunks[0];
|
|
591
|
+
return syntaxRejection(
|
|
592
|
+
displayPath,
|
|
593
|
+
{ startLine: h.startLine, endLine: h.endLine, newText: h.newLines.join("\n") },
|
|
594
|
+
{
|
|
595
|
+
content: batch.content,
|
|
596
|
+
before: batch.before,
|
|
597
|
+
after: batch.after,
|
|
598
|
+
removed: h.removed,
|
|
599
|
+
added: h.added,
|
|
600
|
+
resolvedStart: h.startLine,
|
|
601
|
+
resolvedEnd: h.endLine
|
|
602
|
+
},
|
|
603
|
+
error
|
|
604
|
+
);
|
|
605
|
+
}
|
|
606
|
+
const first = batch.hunks[0];
|
|
607
|
+
const last = batch.hunks[batch.hunks.length - 1];
|
|
608
|
+
const delta = batch.totalAdded - batch.totalRemoved;
|
|
609
|
+
const afterWin = renderWindow(displayPath, batch.after, first.startLine - LINE_EDIT_CONTEXT_LINES, last.endLine + delta + LINE_EDIT_CONTEXT_LINES);
|
|
610
|
+
const beforeWin = renderWindow(displayPath, batch.before, first.startLine - LINE_EDIT_CONTEXT_LINES, last.endLine + LINE_EDIT_CONTEXT_LINES);
|
|
611
|
+
return [
|
|
612
|
+
`Your batch edit (${batch.hunks.length} hunks) was NOT applied: it introduces a syntax error.`,
|
|
613
|
+
`ERROR: ${error}`,
|
|
614
|
+
"",
|
|
615
|
+
"This is how the file would have looked:",
|
|
616
|
+
afterWin,
|
|
617
|
+
"",
|
|
618
|
+
"This is the original code before your edit:",
|
|
619
|
+
beforeWin,
|
|
620
|
+
"",
|
|
621
|
+
"Fix the affected hunk(s) and try again. Do not repeat the same edit."
|
|
622
|
+
].join("\n");
|
|
623
|
+
}
|
|
624
|
+
function toSafeInt(value) {
|
|
625
|
+
if (typeof value === "number" && Number.isFinite(value)) return Math.trunc(value);
|
|
626
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
627
|
+
const parsed = Number(value.replace(/,/g, "").trim());
|
|
628
|
+
if (Number.isFinite(parsed)) return Math.trunc(parsed);
|
|
629
|
+
}
|
|
630
|
+
return void 0;
|
|
631
|
+
}
|
|
632
|
+
function normalizeRawHunk(raw) {
|
|
633
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return void 0;
|
|
634
|
+
const obj = raw;
|
|
635
|
+
const sl = toSafeInt(obj.start_line ?? obj.startLine ?? obj.line_start ?? obj.from_line ?? obj.start ?? obj.line);
|
|
636
|
+
const el = toSafeInt(obj.end_line ?? obj.endLine ?? obj.line_end ?? obj.to_line ?? obj.end);
|
|
637
|
+
const ntRaw = obj.new_text ?? obj.newText ?? obj.new_string ?? obj.new_str ?? obj.text ?? obj.content ?? obj.replacement ?? obj.lines;
|
|
638
|
+
if (sl === void 0 || el === void 0 || typeof ntRaw !== "string") return void 0;
|
|
639
|
+
const stRaw = obj.start_text ?? obj.startText ?? obj.anchor ?? obj.start_anchor ?? obj.first_line;
|
|
640
|
+
const etRaw = obj.end_text ?? obj.endText ?? obj.end_anchor ?? obj.last_line;
|
|
641
|
+
return {
|
|
642
|
+
start_line: sl,
|
|
643
|
+
end_line: el,
|
|
644
|
+
...typeof stRaw === "string" ? { start_text: stRaw } : {},
|
|
645
|
+
...typeof etRaw === "string" ? { end_text: etRaw } : {},
|
|
646
|
+
new_text: ntRaw
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
function parseLineEditHunks(args) {
|
|
650
|
+
if (args.edits !== void 0) {
|
|
651
|
+
let source = args.edits;
|
|
652
|
+
if (typeof source === "string") {
|
|
653
|
+
try {
|
|
654
|
+
source = JSON.parse(source);
|
|
655
|
+
} catch {
|
|
656
|
+
return "edits must be a valid JSON array of edit hunks";
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
const items = Array.isArray(source) ? source : typeof source === "object" && source !== null ? [source] : void 0;
|
|
660
|
+
if (!items || items.length === 0) return "edits must be a non-empty array of { start_line, end_line, start_text?, new_text } hunks";
|
|
661
|
+
const out = [];
|
|
662
|
+
for (let i = 0; i < items.length; i++) {
|
|
663
|
+
const normalized = normalizeRawHunk(items[i]);
|
|
664
|
+
if (normalized === void 0) {
|
|
665
|
+
return `edits[${i}] is missing required start_line, end_line, or new_text`;
|
|
666
|
+
}
|
|
667
|
+
out.push({
|
|
668
|
+
startLine: normalized.start_line,
|
|
669
|
+
endLine: normalized.end_line,
|
|
670
|
+
...normalized.start_text !== void 0 ? { startText: normalized.start_text } : {},
|
|
671
|
+
...normalized.end_text !== void 0 ? { endText: normalized.end_text } : {},
|
|
672
|
+
newText: normalized.new_text
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
return out;
|
|
676
|
+
}
|
|
677
|
+
const single = normalizeRawHunk(args);
|
|
678
|
+
if (single === void 0) {
|
|
679
|
+
return "Provide either edits: [{ start_line, end_line, start_text, new_text }] or single-hunk start_line, end_line, new_text";
|
|
680
|
+
}
|
|
681
|
+
return [{
|
|
682
|
+
startLine: single.start_line,
|
|
683
|
+
endLine: single.end_line,
|
|
684
|
+
...single.start_text !== void 0 ? { startText: single.start_text } : {},
|
|
685
|
+
...single.end_text !== void 0 ? { endText: single.end_text } : {},
|
|
686
|
+
newText: single.new_text
|
|
687
|
+
}];
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
// src/edit-modes/folded-read-guard.ts
|
|
691
|
+
var foldedUnreadBySession = /* @__PURE__ */ new Map();
|
|
692
|
+
function isFoldedUnreadPath(sessionId, candidates) {
|
|
693
|
+
if (sessionId === void 0 || sessionId === "") return false;
|
|
694
|
+
const blocked = foldedUnreadBySession.get(sessionId);
|
|
695
|
+
if (blocked === void 0 || blocked.size === 0) return false;
|
|
696
|
+
return candidates.some((candidate) => candidate !== void 0 && candidate !== "" && blocked.has(candidate));
|
|
697
|
+
}
|
|
698
|
+
function foldedUnreadErrorMessage(displayPath, toolName = "edit") {
|
|
699
|
+
return `The earlier read output for ${displayPath} was folded out of the active context window. Call \`read\` on ${displayPath} again to inspect its current content before calling \`${toolName}\`.`;
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
// src/edit-modes/observations.ts
|
|
703
|
+
import { resolve } from "node:path";
|
|
704
|
+
import { appendPluginRecord, pluginRecordOf } from "@deepseek-ai/dsh-session";
|
|
705
|
+
|
|
706
|
+
// src/dsh-host.ts
|
|
707
|
+
function sessionIdOfExec(exec) {
|
|
708
|
+
return exec.agent?.session?.header?.id;
|
|
709
|
+
}
|
|
710
|
+
async function ensureExecWorkingDir(host, exec) {
|
|
711
|
+
const workingDirectory = host.get("workingDirectory");
|
|
712
|
+
if (exec.agent === void 0 || workingDirectory === void 0) return void 0;
|
|
713
|
+
return workingDirectory.ensure(exec.agent, exec.signal);
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
// src/core/todo-state.ts
|
|
717
|
+
var TODO_PLAN_TOOL = "todo_plan";
|
|
718
|
+
var TODO_UPDATE_TOOL = "todo_update";
|
|
719
|
+
var TODO_PLAN_DESCRIPTION = "Create or revise the ordered work list for multi-step tasks (touching multiple methods/files, code + docs/tests, or 3+ distinct subgoals). Skip this tool for casual chat, quick single-goal lookups (1-3 reads or searches), or a trivial one-spot edit. For multi-step changes, you may inspect 1-2 files first to understand the layout, then call todo_plan BEFORE making your first file edit \u2014 do not wait until after editing to plan. Calling todo_plan mid-turn keeps completed/dropped items and their notes intact and replaces only unfinished items.";
|
|
720
|
+
var TODO_UPDATE_DESCRIPTION = "Update one item in the current work list by id. As soon as an item is finished, mark it completed with a concise factual note (<= 120 words: exact /app/... file paths, updated line ranges, signatures, and test exit codes \u2014 never mark unexecuted work completed). Older exploratory tool outputs before the recent workspace actions are folded once note is saved, while your initial todo_plan and the latest workspace results stay visible. The next pending item becomes in_progress automatically; you may also checkpoint an in_progress item with an interim note before context fills up.";
|
|
721
|
+
var WORKLIST_PROTOCOL_TAG = /<\/?(?:think|tool_call|tool_response)(?:\s[^>]*)?>/gi;
|
|
722
|
+
var WORKLIST_LEADING_BULLET = /^\s*(?:\[\d+\]|\d+[.)]|[-*•])\s*/;
|
|
723
|
+
function sanitizeWorklistField(text) {
|
|
724
|
+
return text.replace(WORKLIST_PROTOCOL_TAG, "").replace(/\s*\n+\s*/g, " | ").trim();
|
|
725
|
+
}
|
|
726
|
+
function parsePlanItems(raw) {
|
|
727
|
+
if (Array.isArray(raw)) {
|
|
728
|
+
const out = [];
|
|
729
|
+
for (const entry of raw) {
|
|
730
|
+
if (typeof entry === "string") {
|
|
731
|
+
const cleaned = sanitizeWorklistField(entry.replace(WORKLIST_LEADING_BULLET, ""));
|
|
732
|
+
if (cleaned !== "") out.push(cleaned);
|
|
733
|
+
} else if (typeof entry === "object" && entry !== null) {
|
|
734
|
+
const obj = entry;
|
|
735
|
+
const candidate = obj.content ?? obj.title ?? obj.text ?? obj.step;
|
|
736
|
+
if (typeof candidate === "string") {
|
|
737
|
+
const cleaned = sanitizeWorklistField(candidate.replace(WORKLIST_LEADING_BULLET, ""));
|
|
738
|
+
if (cleaned !== "") out.push(cleaned);
|
|
739
|
+
}
|
|
740
|
+
} else {
|
|
741
|
+
return void 0;
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
return out;
|
|
745
|
+
}
|
|
746
|
+
if (typeof raw === "string") {
|
|
747
|
+
const lines = raw.split(/\r?\n/).map((line) => sanitizeWorklistField(line.replace(WORKLIST_LEADING_BULLET, ""))).filter((line) => line !== "");
|
|
748
|
+
return lines.length > 0 ? lines : void 0;
|
|
749
|
+
}
|
|
750
|
+
return void 0;
|
|
751
|
+
}
|
|
752
|
+
function normalizeWorklistStatus(raw) {
|
|
753
|
+
if (typeof raw !== "string") return void 0;
|
|
754
|
+
const lower = raw.trim().toLowerCase();
|
|
755
|
+
if (lower === "pending" || lower === "todo" || lower === "not_started") return "pending";
|
|
756
|
+
if (lower === "in_progress" || lower === "in-progress" || lower === "doing" || lower === "active") return "in_progress";
|
|
757
|
+
if (lower === "completed" || lower === "complete" || lower === "done" || lower === "finished") return "completed";
|
|
758
|
+
if (lower === "dropped" || lower === "cancelled" || lower === "canceled" || lower === "skipped") return "dropped";
|
|
759
|
+
return void 0;
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
// src/core/tool-mappings.ts
|
|
763
|
+
var nonEmptyStr = (value) => typeof value === "string" && value.trim() !== "" ? value : void 0;
|
|
764
|
+
var finiteInt = (value) => typeof value === "number" && Number.isFinite(value) ? Math.trunc(value) : void 0;
|
|
765
|
+
function stripUndefined(args) {
|
|
766
|
+
return Object.fromEntries(Object.entries(args).filter(([, value]) => value !== void 0));
|
|
767
|
+
}
|
|
768
|
+
function workspacePath(value) {
|
|
769
|
+
const path = nonEmptyStr(value);
|
|
770
|
+
if (path === void 0) return void 0;
|
|
771
|
+
const index = path.lastIndexOf("workspace/");
|
|
772
|
+
if (path.startsWith("/") && index >= 0) return path.slice(index + "workspace/".length) || ".";
|
|
773
|
+
if (path === "/workspace") return ".";
|
|
774
|
+
return path;
|
|
775
|
+
}
|
|
776
|
+
function escapeRegex(text) {
|
|
777
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
778
|
+
}
|
|
779
|
+
function unescapeRegex(text) {
|
|
780
|
+
return text.replace(/\\([.*+?^${}()|[\]\\])/g, "$1");
|
|
781
|
+
}
|
|
782
|
+
var BUILTIN_MAPPINGS = {
|
|
783
|
+
read: {
|
|
784
|
+
wireName: "read_file",
|
|
785
|
+
description: "Read a UTF-8 text file in the workspace. Lines come numbered. Without start_line/end_line it returns the start of the file.",
|
|
786
|
+
arguments: '{"path":"relative file path","start_line":"optional integer >= 1","end_line":"optional integer >= start_line"}',
|
|
787
|
+
schema: { properties: { path: { type: "string" }, start_line: { type: "integer" }, end_line: { type: "integer" } } },
|
|
788
|
+
toDsh(args) {
|
|
789
|
+
const start = finiteInt(args.start_line);
|
|
790
|
+
const end = finiteInt(args.end_line);
|
|
791
|
+
return stripUndefined({
|
|
792
|
+
file_path: workspacePath(args.path),
|
|
793
|
+
offset: start,
|
|
794
|
+
limit: end !== void 0 ? Math.max(1, end - (start ?? 1) + 1) : void 0
|
|
795
|
+
});
|
|
796
|
+
},
|
|
797
|
+
fromDsh(args) {
|
|
798
|
+
const offset = finiteInt(args.offset);
|
|
799
|
+
const limit = finiteInt(args.limit);
|
|
800
|
+
return stripUndefined({
|
|
801
|
+
path: args.file_path,
|
|
802
|
+
start_line: offset,
|
|
803
|
+
end_line: limit !== void 0 ? (offset ?? 1) + limit - 1 : void 0
|
|
804
|
+
});
|
|
805
|
+
}
|
|
806
|
+
},
|
|
807
|
+
write: {
|
|
808
|
+
wireName: "write_file",
|
|
809
|
+
description: "Create or overwrite a workspace text file with the given content. The content becomes the whole file.",
|
|
810
|
+
arguments: '{"path":"relative file path","content":"full file content"}',
|
|
811
|
+
schema: { properties: { path: { type: "string" }, content: { type: "string" } } },
|
|
812
|
+
toDsh: (args) => ({ file_path: workspacePath(args.path), content: args.content ?? "" }),
|
|
813
|
+
fromDsh: (args) => ({ path: args.file_path, content: args.content })
|
|
814
|
+
},
|
|
815
|
+
edit: {
|
|
816
|
+
wireName: "edit_file",
|
|
817
|
+
description: "Replace one exact piece of text in a workspace text file. old_text must appear exactly once; copy it from read_file without the line numbers.",
|
|
818
|
+
arguments: '{"path":"relative file path","old_text":"exact text to replace","new_text":"replacement text"}',
|
|
819
|
+
schema: { properties: { path: { type: "string" }, old_text: { type: "string" }, new_text: { type: "string" } } },
|
|
820
|
+
toDsh: (args) => ({ file_path: workspacePath(args.path), old_string: args.old_text ?? "", new_string: args.new_text ?? "" }),
|
|
821
|
+
fromDsh: (args) => ({ path: args.file_path, old_text: args.old_string, new_text: args.new_string })
|
|
822
|
+
},
|
|
823
|
+
// Line-range edit (src/line-edit.ts); offered only where that plugin is mounted.
|
|
824
|
+
edit_lines: {
|
|
825
|
+
wireName: "edit_lines",
|
|
826
|
+
description: "Replace a range of lines in a workspace text file, numbered as read_file shows them. end_line = start_line - 1 inserts before start_line.",
|
|
827
|
+
arguments: '{"path":"relative file path","start_line":"first line to replace","end_line":"last line to replace","new_text":"replacement lines without line numbers"}',
|
|
828
|
+
schema: { properties: { path: { type: "string" }, start_line: { type: "integer" }, end_line: { type: "integer" }, new_text: { type: "string" } } },
|
|
829
|
+
toDsh: (args) => ({ file_path: workspacePath(args.path), start_line: args.start_line, end_line: args.end_line, new_text: args.new_text ?? "" }),
|
|
830
|
+
fromDsh: (args) => ({ path: args.file_path, start_line: args.start_line, end_line: args.end_line, new_text: args.new_text })
|
|
831
|
+
},
|
|
832
|
+
glob: {
|
|
833
|
+
wireName: "list_files",
|
|
834
|
+
description: "List files below a workspace-relative path.",
|
|
835
|
+
arguments: '{"path":"optional relative directory","pattern":"optional glob such as *.ts"}',
|
|
836
|
+
schema: { properties: { path: { type: "string" }, pattern: { type: "string" } } },
|
|
837
|
+
toDsh: (args) => stripUndefined({ pattern: nonEmptyStr(args.pattern) ?? "*", path: workspacePath(args.path) }),
|
|
838
|
+
fromDsh: (args) => stripUndefined({ path: args.path, pattern: args.pattern === "*" ? void 0 : args.pattern })
|
|
839
|
+
},
|
|
840
|
+
grep: {
|
|
841
|
+
wireName: "search_text",
|
|
842
|
+
description: "Search literal text in workspace files. Returns matching lines with line numbers.",
|
|
843
|
+
arguments: '{"query":"literal text","path":"optional relative path"}',
|
|
844
|
+
schema: { properties: { query: { type: "string" }, path: { type: "string" } } },
|
|
845
|
+
toDsh: (args) => stripUndefined({ pattern: escapeRegex(String(args.query ?? "")), path: workspacePath(args.path) }),
|
|
846
|
+
fromDsh: (args) => stripUndefined({ query: unescapeRegex(String(args.pattern ?? "")), path: args.path })
|
|
847
|
+
},
|
|
848
|
+
bash: {
|
|
849
|
+
wireName: "bash",
|
|
850
|
+
description: "Run a bash command in the workspace and return stdout and stderr. Each call starts in the workspace and does not keep cd or variables from earlier calls.",
|
|
851
|
+
arguments: '{"command":"bash command line"}',
|
|
852
|
+
schema: { properties: { command: { type: "string" } } },
|
|
853
|
+
toDsh(args) {
|
|
854
|
+
const command = String(args.command ?? "");
|
|
855
|
+
const firstLine = command.split("\n")[0] ?? "";
|
|
856
|
+
return { description: firstLine.length > 60 ? `${firstLine.slice(0, 57)}...` : firstLine || "Run command", command };
|
|
857
|
+
},
|
|
858
|
+
fromDsh: (args) => ({ command: args.command })
|
|
859
|
+
},
|
|
860
|
+
web_search: {
|
|
861
|
+
wireName: "web_search",
|
|
862
|
+
description: "Search the public web and return titles, URLs, snippets, and source IDs.",
|
|
863
|
+
arguments: '{"query":"search query"}',
|
|
864
|
+
schema: { properties: { query: { type: "string" } } },
|
|
865
|
+
toDsh: (args) => ({ queries: [String(args.query ?? "")] }),
|
|
866
|
+
fromDsh: (args) => ({ query: Array.isArray(args.queries) ? args.queries.join(" ") : args.queries })
|
|
867
|
+
},
|
|
868
|
+
web_fetch: {
|
|
869
|
+
wireName: "web_fetch",
|
|
870
|
+
description: "Fetch the readable content of one public web page.",
|
|
871
|
+
arguments: '{"url":"https://example.com/page"}',
|
|
872
|
+
schema: { properties: { url: { type: "string" } } },
|
|
873
|
+
toDsh(args) {
|
|
874
|
+
const url = nonEmptyStr(args.url) ?? (Array.isArray(args.urls) ? nonEmptyStr(args.urls[0]) : void 0);
|
|
875
|
+
return { url: url ?? "" };
|
|
876
|
+
},
|
|
877
|
+
fromDsh: (args) => ({ url: args.url })
|
|
878
|
+
},
|
|
879
|
+
// Stateful work list (src/todo.ts); offered when historyMode === 'worklist'.
|
|
880
|
+
[TODO_PLAN_TOOL]: {
|
|
881
|
+
wireName: TODO_PLAN_TOOL,
|
|
882
|
+
description: TODO_PLAN_DESCRIPTION,
|
|
883
|
+
arguments: '{"items":"array of string"}',
|
|
884
|
+
schema: { properties: { items: { type: "array", items: { type: "string" } } } },
|
|
885
|
+
toDsh: (args) => ({ items: parsePlanItems(args.items) ?? args.items }),
|
|
886
|
+
fromDsh: (args) => ({ items: args.items })
|
|
887
|
+
},
|
|
888
|
+
[TODO_UPDATE_TOOL]: {
|
|
889
|
+
wireName: TODO_UPDATE_TOOL,
|
|
890
|
+
description: TODO_UPDATE_DESCRIPTION,
|
|
891
|
+
arguments: '{"id":"integer","status":"in_progress|completed|dropped","note":"optional Concrete findings, exact file paths/lines, applied edits, or test outcomes","content":"optional Refined title for this item if the initial wording was inaccurate"}',
|
|
892
|
+
schema: {
|
|
893
|
+
properties: {
|
|
894
|
+
id: { type: "integer" },
|
|
895
|
+
status: { type: "string", enum: ["in_progress", "completed", "dropped"] },
|
|
896
|
+
note: { type: "string" },
|
|
897
|
+
content: { type: "string" }
|
|
898
|
+
}
|
|
899
|
+
},
|
|
900
|
+
toDsh: (args) => stripUndefined({
|
|
901
|
+
id: finiteInt(typeof args.id === "string" ? Number(args.id.trim()) : args.id) ?? args.id,
|
|
902
|
+
status: normalizeWorklistStatus(args.status) ?? args.status,
|
|
903
|
+
note: nonEmptyStr(args.note),
|
|
904
|
+
content: nonEmptyStr(args.content)
|
|
905
|
+
}),
|
|
906
|
+
fromDsh: (args) => stripUndefined({
|
|
907
|
+
id: args.id,
|
|
908
|
+
status: args.status,
|
|
909
|
+
note: args.note,
|
|
910
|
+
content: args.content
|
|
911
|
+
})
|
|
912
|
+
}
|
|
913
|
+
};
|
|
914
|
+
|
|
915
|
+
// src/core/tool-repairs.ts
|
|
916
|
+
var PATH_ALIASES = ["file_path", "filepath", "file", "filename", "file_name"];
|
|
917
|
+
var NATIVE_PATH_ALIASES = ["path", "filepath", "file", "filename", "file_name"];
|
|
918
|
+
var ARGUMENT_ALIASES = {
|
|
919
|
+
read_file: { path: PATH_ALIASES, start_line: ["line_start", "from_line"], end_line: ["line_end", "to_line"] },
|
|
920
|
+
write_file: { path: PATH_ALIASES, content: ["text", "file_text", "contents", "data", "code"] },
|
|
921
|
+
edit_file: {
|
|
922
|
+
path: PATH_ALIASES,
|
|
923
|
+
old_text: ["old_string", "old_str", "old", "search", "find", "original"],
|
|
924
|
+
new_text: ["new_string", "new_str", "new", "replace", "replacement", "updated"]
|
|
925
|
+
},
|
|
926
|
+
edit_lines: {
|
|
927
|
+
path: PATH_ALIASES,
|
|
928
|
+
start_line: ["line_start", "from_line", "start", "line"],
|
|
929
|
+
end_line: ["line_end", "to_line", "end"],
|
|
930
|
+
new_text: ["new_string", "new_str", "text", "content", "replacement", "lines"]
|
|
931
|
+
},
|
|
932
|
+
list_files: { path: ["directory", "dir", "folder", "dir_path"], pattern: ["glob"] },
|
|
933
|
+
search_text: { query: ["pattern", "text", "search", "keyword", "regex"], path: ["file_path", "directory", "dir"] },
|
|
934
|
+
bash: { command: ["cmd", "script", "code", "shell"] },
|
|
935
|
+
web_fetch: { url: ["link", "href", "page"] },
|
|
936
|
+
web_search: { query: ["q", "keywords", "search", "search_query"] },
|
|
937
|
+
[TODO_PLAN_TOOL]: { items: ["todos", "tasks", "steps", "plan"] },
|
|
938
|
+
[TODO_UPDATE_TOOL]: {
|
|
939
|
+
id: ["index", "item_id", "task_id", "step"],
|
|
940
|
+
note: ["notes", "summary", "finding", "findings", "conclusion", "result"],
|
|
941
|
+
content: ["title", "task", "text", "description"]
|
|
942
|
+
}
|
|
943
|
+
};
|
|
944
|
+
var NATIVE_ARGUMENT_ALIASES = {
|
|
945
|
+
read: { file_path: NATIVE_PATH_ALIASES, offset: ["start_line", "line_start", "from_line"] },
|
|
946
|
+
write: { file_path: NATIVE_PATH_ALIASES, content: ["text", "file_text", "contents", "data", "code"] },
|
|
947
|
+
edit: {
|
|
948
|
+
file_path: NATIVE_PATH_ALIASES,
|
|
949
|
+
old_string: ["old_text", "old_str", "old", "search", "find", "original"],
|
|
950
|
+
new_string: ["new_text", "new_str", "new", "replace", "replacement", "updated"]
|
|
951
|
+
},
|
|
952
|
+
edit_lines: {
|
|
953
|
+
file_path: NATIVE_PATH_ALIASES,
|
|
954
|
+
start_line: ["line_start", "from_line", "start", "line", "offset"],
|
|
955
|
+
end_line: ["line_end", "to_line", "end"],
|
|
956
|
+
new_text: ["new_string", "new_str", "text", "content", "replacement", "lines"]
|
|
957
|
+
},
|
|
958
|
+
glob: { pattern: ["glob"], path: ["directory", "dir", "folder", "dir_path"] },
|
|
959
|
+
grep: { pattern: ["query", "text", "search", "keyword", "regex"], path: ["file_path", "directory", "dir"] },
|
|
960
|
+
bash: { command: ["cmd", "script", "code", "shell"] },
|
|
961
|
+
web_fetch: { url: ["link", "href", "page"] },
|
|
962
|
+
web_search: { queries: ["query", "q", "keywords", "search", "search_query"] },
|
|
963
|
+
[TODO_PLAN_TOOL]: ARGUMENT_ALIASES[TODO_PLAN_TOOL],
|
|
964
|
+
[TODO_UPDATE_TOOL]: ARGUMENT_ALIASES[TODO_UPDATE_TOOL]
|
|
965
|
+
};
|
|
966
|
+
|
|
967
|
+
// src/result-budget.ts
|
|
968
|
+
var READ_SHOWN_EVENT = "rwkv/read-shown";
|
|
969
|
+
|
|
970
|
+
// src/edit-modes/observations.ts
|
|
971
|
+
var EDIT_LINES_TOOL = "edit_lines";
|
|
972
|
+
var OBSERVED_RECORD = "plugin:rwkv-edit-lines/observed";
|
|
973
|
+
var appendRecord = appendPluginRecord;
|
|
974
|
+
var recordOf = pluginRecordOf;
|
|
975
|
+
var encodeLines = (lines) => lines === "all" ? "all" : [...lines].sort((a, b) => a - b);
|
|
976
|
+
var decodeLines = (value) => {
|
|
977
|
+
if (value === "all") return "all";
|
|
978
|
+
if (!Array.isArray(value) || !value.every((n) => typeof n === "number" && Number.isSafeInteger(n))) return void 0;
|
|
979
|
+
return new Set(value);
|
|
980
|
+
};
|
|
981
|
+
var decodeObservation = (data) => {
|
|
982
|
+
if (typeof data !== "object" || data === null) return void 0;
|
|
983
|
+
const { targetKey, observation, lines } = data;
|
|
984
|
+
if (typeof targetKey !== "string" || targetKey === "") return void 0;
|
|
985
|
+
if (typeof observation !== "object" || observation === null) return void 0;
|
|
986
|
+
const kind = observation.kind;
|
|
987
|
+
if (kind !== "present" && kind !== "absent") return void 0;
|
|
988
|
+
if (kind === "present" && observation.version == null) return void 0;
|
|
989
|
+
const decoded = decodeLines(lines);
|
|
990
|
+
if (decoded === void 0) return void 0;
|
|
991
|
+
return { targetKey, observation, lines: decoded };
|
|
992
|
+
};
|
|
993
|
+
var sameVersion = (a, b) => a?.kind === "present" && b.kind === "present" && JSON.stringify(a.version) === JSON.stringify(b.version);
|
|
994
|
+
var Observations = class {
|
|
995
|
+
bySession = /* @__PURE__ */ new WeakMap();
|
|
996
|
+
hydrated = /* @__PURE__ */ new WeakSet();
|
|
997
|
+
readTargets = /* @__PURE__ */ new WeakMap();
|
|
998
|
+
mapFor(session) {
|
|
999
|
+
let byTarget = this.bySession.get(session);
|
|
1000
|
+
if (byTarget === void 0) this.bySession.set(session, byTarget = /* @__PURE__ */ new Map());
|
|
1001
|
+
return byTarget;
|
|
1002
|
+
}
|
|
1003
|
+
hydrate(session) {
|
|
1004
|
+
if (this.hydrated.has(session)) return;
|
|
1005
|
+
this.hydrated.add(session);
|
|
1006
|
+
const events = session.snapshotEvents?.();
|
|
1007
|
+
if (events === void 0) return;
|
|
1008
|
+
for (const event of events) {
|
|
1009
|
+
const record = recordOf(event);
|
|
1010
|
+
if (record?.type !== OBSERVED_RECORD) continue;
|
|
1011
|
+
const entry = decodeObservation(record.data);
|
|
1012
|
+
if (entry !== void 0) {
|
|
1013
|
+
this.mapFor(session).set(entry.targetKey, { observation: entry.observation, lines: entry.lines });
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
persist(session, targetKey, seen) {
|
|
1018
|
+
const data = {
|
|
1019
|
+
targetKey,
|
|
1020
|
+
observation: seen.observation,
|
|
1021
|
+
lines: encodeLines(seen.lines)
|
|
1022
|
+
};
|
|
1023
|
+
try {
|
|
1024
|
+
appendRecord(session, OBSERVED_RECORD, data);
|
|
1025
|
+
} catch (error) {
|
|
1026
|
+
if (!(error instanceof Error) || !error.message.includes("reenter")) return;
|
|
1027
|
+
setTimeout(() => {
|
|
1028
|
+
try {
|
|
1029
|
+
appendRecord(session, OBSERVED_RECORD, data);
|
|
1030
|
+
} catch {
|
|
1031
|
+
}
|
|
1032
|
+
}, 0);
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
record(actor, target, observation) {
|
|
1036
|
+
const session = actor?.agent?.session;
|
|
1037
|
+
if (session === void 0) return;
|
|
1038
|
+
this.hydrate(session);
|
|
1039
|
+
const byTarget = this.mapFor(session);
|
|
1040
|
+
const previous = byTarget.get(target.targetKey);
|
|
1041
|
+
const seen = { observation, lines: "all" };
|
|
1042
|
+
byTarget.set(target.targetKey, seen);
|
|
1043
|
+
if (actor !== void 0 && actor.name === "read") {
|
|
1044
|
+
const before = previous !== void 0 && sameVersion(previous.observation, observation) ? previous.lines : /* @__PURE__ */ new Set();
|
|
1045
|
+
this.readTargets.set(actor, { session, targetKey: target.targetKey, before });
|
|
1046
|
+
} else if (actor?.name !== EDIT_LINES_TOOL) {
|
|
1047
|
+
this.persist(session, target.targetKey, seen);
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
shown(exec, first, last) {
|
|
1051
|
+
const read = this.readTargets.get(exec);
|
|
1052
|
+
if (read === void 0) return;
|
|
1053
|
+
this.readTargets.delete(exec);
|
|
1054
|
+
const seen = this.bySession.get(read.session)?.get(read.targetKey);
|
|
1055
|
+
if (seen === void 0) return;
|
|
1056
|
+
seen.lines = addSeen(read.before, first, last);
|
|
1057
|
+
this.persist(read.session, read.targetKey, seen);
|
|
1058
|
+
}
|
|
1059
|
+
setLines(actor, target, lines) {
|
|
1060
|
+
const session = actor.agent?.session;
|
|
1061
|
+
if (session === void 0) return;
|
|
1062
|
+
this.hydrate(session);
|
|
1063
|
+
const seen = this.bySession.get(session)?.get(target.targetKey);
|
|
1064
|
+
if (seen === void 0) return;
|
|
1065
|
+
seen.lines = lines;
|
|
1066
|
+
this.persist(session, target.targetKey, seen);
|
|
1067
|
+
}
|
|
1068
|
+
guard(actor, target) {
|
|
1069
|
+
const session = actor.agent?.session;
|
|
1070
|
+
if (session === void 0) return { kind: "replaceIfVersion", version: void 0, lines: "all" };
|
|
1071
|
+
this.hydrate(session);
|
|
1072
|
+
const seen = this.bySession.get(session)?.get(target.targetKey);
|
|
1073
|
+
if (seen === void 0) return `cannot modify "${target.displayPath}": file has not been read \u2014 read the file, then retry`;
|
|
1074
|
+
if (seen.observation.kind === "absent") return `cannot edit "${target.displayPath}": not found \u2014 use write to create it`;
|
|
1075
|
+
return { kind: "replaceIfVersion", version: seen.observation.version, lines: seen.lines };
|
|
1076
|
+
}
|
|
1077
|
+
};
|
|
1078
|
+
function attachObservations(host) {
|
|
1079
|
+
const observations = new Observations();
|
|
1080
|
+
host.on("fs/observed", (target, observation, actor) => observations.record(actor, target, observation));
|
|
1081
|
+
host.on(READ_SHOWN_EVENT, (exec, window) => observations.shown(exec, window.first, window.last));
|
|
1082
|
+
return observations;
|
|
1083
|
+
}
|
|
1084
|
+
async function resolveTargetWithGuards(host, observations, rawFilePath, exec, options) {
|
|
1085
|
+
if (typeof rawFilePath !== "string" || rawFilePath.trim() === "") {
|
|
1086
|
+
throw new Error("file_path must be a non-empty string");
|
|
1087
|
+
}
|
|
1088
|
+
const cwd = await ensureExecWorkingDir(host, exec);
|
|
1089
|
+
const resolveOpts = { ...cwd !== void 0 ? { cwd } : {}, ...exec.signal ? { signal: exec.signal } : {} };
|
|
1090
|
+
const target = await host.fs.resolve(rawFilePath, resolveOpts);
|
|
1091
|
+
const folded = isFoldedUnreadPath(sessionIdOfExec(exec), [
|
|
1092
|
+
host.fs.processPath(target),
|
|
1093
|
+
target.displayPath,
|
|
1094
|
+
...cwd !== void 0 ? [resolve(cwd, rawFilePath.trim())] : []
|
|
1095
|
+
]);
|
|
1096
|
+
if (folded && !options?.allowFolded) {
|
|
1097
|
+
throw new Error(foldedUnreadErrorMessage(target.displayPath, EDIT_LINES_TOOL));
|
|
1098
|
+
}
|
|
1099
|
+
const guard = observations.guard(exec, target);
|
|
1100
|
+
if (typeof guard === "string") throw new Error(guard);
|
|
1101
|
+
return { target, guard, folded };
|
|
1102
|
+
}
|
|
1103
|
+
function remediateStaleVersion(error) {
|
|
1104
|
+
if (error?.code !== "FS_STALE_VERSION") return error;
|
|
1105
|
+
return new Error(`${error.message} \u2014 its line numbers may have moved; re-read the file, then retry`, { cause: error });
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
// src/edit-modes/syntax-check.ts
|
|
1109
|
+
import { spawn } from "node:child_process";
|
|
1110
|
+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
1111
|
+
import * as nodeModule from "node:module";
|
|
1112
|
+
import { tmpdir } from "node:os";
|
|
1113
|
+
import { extname, join } from "node:path";
|
|
1114
|
+
var stripTsTypes = nodeModule.stripTypeScriptTypes;
|
|
1115
|
+
var TIMEOUT_MS = 1e4;
|
|
1116
|
+
var PYTHON_CHECK = String.raw`
|
|
1117
|
+
import sys
|
|
1118
|
+
source = sys.stdin.read()
|
|
1119
|
+
try:
|
|
1120
|
+
compile(source, sys.argv[1], "exec", dont_inherit=True)
|
|
1121
|
+
except SyntaxError as error:
|
|
1122
|
+
print(f"{type(error).__name__}: {error.msg} (line {error.lineno})")
|
|
1123
|
+
sys.exit(1)
|
|
1124
|
+
`;
|
|
1125
|
+
var TOML_CHECK = String.raw`
|
|
1126
|
+
import sys, tomllib
|
|
1127
|
+
try:
|
|
1128
|
+
tomllib.loads(sys.stdin.read())
|
|
1129
|
+
except Exception as error:
|
|
1130
|
+
print(f"TOML: {error}")
|
|
1131
|
+
sys.exit(1)
|
|
1132
|
+
`;
|
|
1133
|
+
var YAML_CHECK = String.raw`
|
|
1134
|
+
import sys
|
|
1135
|
+
try:
|
|
1136
|
+
import yaml
|
|
1137
|
+
except ImportError:
|
|
1138
|
+
sys.exit(0)
|
|
1139
|
+
try:
|
|
1140
|
+
list(yaml.safe_load_all(sys.stdin.read()))
|
|
1141
|
+
except Exception as error:
|
|
1142
|
+
first = str(error).splitlines()[0] if str(error) else type(error).__name__
|
|
1143
|
+
print(f"YAML: {first}")
|
|
1144
|
+
sys.exit(1)
|
|
1145
|
+
`;
|
|
1146
|
+
var JAVA_PARSE_ERROR_RE = /error:\s*(?:';' expected|reached end of file while parsing|class, interface, enum, or record expected|illegal start of (?:expression|type)|unclosed (?:string|character) literal|unclosed comment|<identifier> expected|'[^']+' expected|(?:unnamed class|compact source file|implicitly declared class) should not have package declaration)/i;
|
|
1147
|
+
function run(command, args, input) {
|
|
1148
|
+
return new Promise((resolve2) => {
|
|
1149
|
+
let output = "";
|
|
1150
|
+
let settled = false;
|
|
1151
|
+
const done = (value) => {
|
|
1152
|
+
if (!settled) {
|
|
1153
|
+
settled = true;
|
|
1154
|
+
resolve2(value);
|
|
1155
|
+
}
|
|
1156
|
+
};
|
|
1157
|
+
let child;
|
|
1158
|
+
try {
|
|
1159
|
+
child = spawn(command, args, { stdio: ["pipe", "pipe", "pipe"], timeout: TIMEOUT_MS, env: { ...process.env, LC_ALL: "C", LANG: "C" } });
|
|
1160
|
+
} catch {
|
|
1161
|
+
done(void 0);
|
|
1162
|
+
return;
|
|
1163
|
+
}
|
|
1164
|
+
child.stdout.on("data", (chunk) => {
|
|
1165
|
+
output += String(chunk);
|
|
1166
|
+
});
|
|
1167
|
+
child.stderr.on("data", (chunk) => {
|
|
1168
|
+
output += String(chunk);
|
|
1169
|
+
});
|
|
1170
|
+
child.on("error", () => done(void 0));
|
|
1171
|
+
child.on("close", (code, signal) => done(signal !== null ? void 0 : code === 0 ? "" : output.trim() || `exit ${code}`));
|
|
1172
|
+
child.stdin.on("error", () => void 0);
|
|
1173
|
+
child.stdin.end(input);
|
|
1174
|
+
});
|
|
1175
|
+
}
|
|
1176
|
+
async function nodeCheck(text, extension) {
|
|
1177
|
+
const dir = await mkdtemp(join(tmpdir(), "rwkv-edit-check-"));
|
|
1178
|
+
try {
|
|
1179
|
+
const file = join(dir, `check${extension}`);
|
|
1180
|
+
await writeFile(file, text);
|
|
1181
|
+
const output = await run(process.execPath, ["--check", file], "");
|
|
1182
|
+
if (!output) return output;
|
|
1183
|
+
const line = new RegExp(`${file.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}:(\\d+)`).exec(output)?.[1];
|
|
1184
|
+
const message = output.split("\n").find((lineText) => /^[A-Za-z]*Error: /.test(lineText)) ?? output.split("\n")[0];
|
|
1185
|
+
return line === void 0 ? message : `${message} (line ${line})`;
|
|
1186
|
+
} finally {
|
|
1187
|
+
await rm(dir, { recursive: true, force: true });
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
function tsOrJsStripCheck(text) {
|
|
1191
|
+
if (!stripTsTypes) return void 0;
|
|
1192
|
+
try {
|
|
1193
|
+
stripTsTypes(text, { mode: "strip" });
|
|
1194
|
+
return "";
|
|
1195
|
+
} catch (error) {
|
|
1196
|
+
if (error && typeof error === "object" && "code" in error && error.code === "ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX") {
|
|
1197
|
+
return void 0;
|
|
1198
|
+
}
|
|
1199
|
+
const firstLine = (error instanceof Error ? error.message : String(error)).split("\n")[0];
|
|
1200
|
+
return `SyntaxError: ${firstLine}`;
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
async function javaParseCheck(text) {
|
|
1204
|
+
const dir = await mkdtemp(join(tmpdir(), "rwkv-java-check-"));
|
|
1205
|
+
try {
|
|
1206
|
+
const pubMatch = /\bpublic\s+(?:final\s+|abstract\s+)?(?:class|interface|enum|record)\s+([A-Za-z_$][A-Za-z0-9_$]*)/.exec(text);
|
|
1207
|
+
const fileName = `${pubMatch?.[1] ?? "Check"}.java`;
|
|
1208
|
+
const file = join(dir, fileName);
|
|
1209
|
+
await writeFile(file, text);
|
|
1210
|
+
const output = await run("javac", ["-J-Duser.language=en", "-J-Duser.country=US", "-encoding", "UTF-8", "-XDcompilePolicy=simple", "-proc:none", "-d", dir, file], "");
|
|
1211
|
+
if (!output) return output;
|
|
1212
|
+
const parseLine = output.split("\n").find((line) => JAVA_PARSE_ERROR_RE.test(line));
|
|
1213
|
+
if (!parseLine) return "";
|
|
1214
|
+
return parseLine.replace(file, fileName).trim();
|
|
1215
|
+
} finally {
|
|
1216
|
+
await rm(dir, { recursive: true, force: true });
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
function parseCsvRows(text) {
|
|
1220
|
+
const rows = [];
|
|
1221
|
+
let row = [];
|
|
1222
|
+
let field = "";
|
|
1223
|
+
let inQuotes = false;
|
|
1224
|
+
const s = text.replace(/\r\n/g, "\n");
|
|
1225
|
+
for (let i = 0; i < s.length; i++) {
|
|
1226
|
+
const ch = s[i];
|
|
1227
|
+
if (inQuotes) {
|
|
1228
|
+
if (ch === '"') {
|
|
1229
|
+
if (s[i + 1] === '"') {
|
|
1230
|
+
field += '"';
|
|
1231
|
+
i++;
|
|
1232
|
+
} else inQuotes = false;
|
|
1233
|
+
} else {
|
|
1234
|
+
field += ch;
|
|
1235
|
+
}
|
|
1236
|
+
} else if (ch === '"') {
|
|
1237
|
+
if (field === "") inQuotes = true;
|
|
1238
|
+
else field += ch;
|
|
1239
|
+
} else if (ch === ",") {
|
|
1240
|
+
row.push(field);
|
|
1241
|
+
field = "";
|
|
1242
|
+
} else if (ch === "\n") {
|
|
1243
|
+
row.push(field);
|
|
1244
|
+
field = "";
|
|
1245
|
+
if (!(row.length === 1 && row[0] === "")) rows.push(row);
|
|
1246
|
+
row = [];
|
|
1247
|
+
} else {
|
|
1248
|
+
field += ch;
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
if (inQuotes) return "CSV: unclosed double-quoted field";
|
|
1252
|
+
if (field !== "" || row.length > 0) {
|
|
1253
|
+
row.push(field);
|
|
1254
|
+
if (!(row.length === 1 && row[0] === "")) rows.push(row);
|
|
1255
|
+
}
|
|
1256
|
+
return rows;
|
|
1257
|
+
}
|
|
1258
|
+
function csvStructureError(text) {
|
|
1259
|
+
if (text.trim() === "") return "";
|
|
1260
|
+
const parsed = parseCsvRows(text);
|
|
1261
|
+
if (typeof parsed === "string") return parsed;
|
|
1262
|
+
if (parsed.length < 2) return "";
|
|
1263
|
+
const headerCols = parsed[0].length;
|
|
1264
|
+
if (headerCols < 2) return "";
|
|
1265
|
+
for (let r = 1; r < parsed.length; r++) {
|
|
1266
|
+
if (parsed[r].length !== headerCols) {
|
|
1267
|
+
return `CSV column count mismatch at row ${r + 1}: expected ${headerCols} columns (matching header "${parsed[0].slice(0, 4).join(",")}"), got ${parsed[r].length}`;
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
return "";
|
|
1271
|
+
}
|
|
1272
|
+
async function syntaxError(text, path) {
|
|
1273
|
+
const extension = extname(path).toLowerCase();
|
|
1274
|
+
switch (extension) {
|
|
1275
|
+
case ".py":
|
|
1276
|
+
return run("python3", ["-c", PYTHON_CHECK, path], text);
|
|
1277
|
+
case ".go":
|
|
1278
|
+
return run("gofmt", ["-e"], text);
|
|
1279
|
+
case ".java":
|
|
1280
|
+
return javaParseCheck(text);
|
|
1281
|
+
case ".ts":
|
|
1282
|
+
case ".mts":
|
|
1283
|
+
case ".cts":
|
|
1284
|
+
return tsOrJsStripCheck(text);
|
|
1285
|
+
case ".js":
|
|
1286
|
+
case ".mjs":
|
|
1287
|
+
case ".cjs":
|
|
1288
|
+
return nodeCheck(text, extension);
|
|
1289
|
+
case ".sh":
|
|
1290
|
+
case ".bash":
|
|
1291
|
+
return run("bash", ["-n"], text);
|
|
1292
|
+
case ".toml":
|
|
1293
|
+
return run("python3", ["-c", TOML_CHECK], text);
|
|
1294
|
+
case ".yaml":
|
|
1295
|
+
case ".yml":
|
|
1296
|
+
return run("python3", ["-c", YAML_CHECK], text);
|
|
1297
|
+
case ".csv":
|
|
1298
|
+
return csvStructureError(text);
|
|
1299
|
+
case ".json":
|
|
1300
|
+
if (text.trim() === "") return "";
|
|
1301
|
+
try {
|
|
1302
|
+
JSON.parse(text);
|
|
1303
|
+
return "";
|
|
1304
|
+
} catch (error) {
|
|
1305
|
+
return `JSON: ${error.message}`;
|
|
1306
|
+
}
|
|
1307
|
+
default:
|
|
1308
|
+
return void 0;
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
async function introducedSyntaxError(before, after, path) {
|
|
1312
|
+
const now = await syntaxError(after, path);
|
|
1313
|
+
if (!now) return void 0;
|
|
1314
|
+
return await syntaxError(before, path) === "" ? now : void 0;
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
// src/edit-modes/line-edit.ts
|
|
1318
|
+
function createLineEditToolDefinition(host, observations) {
|
|
1319
|
+
return defineTool({
|
|
1320
|
+
name: EDIT_LINES_TOOL,
|
|
1321
|
+
description: "Atomically apply one or more non-overlapping anchored line-range edits to an existing UTF-8 text file. Pass `edits: [{ start_line, end_line, start_text, end_text?, new_text }]` (pre-edit 1-based line numbers; `end_line = start_line - 1` inserts before `start_line`; empty `new_text` deletes). Always include `start_text` (the original text at `start_line` without line-number prefix) so minor line drift auto-aligns cleanly. Single-hunk top-level `start_line`/`end_line`/`new_text` shorthand is also accepted.",
|
|
1322
|
+
parameters: {
|
|
1323
|
+
file_path: { type: "string", required: true, description: "Path to edit, resolved by the filesystem backend. Read the file first." },
|
|
1324
|
+
edits: {
|
|
1325
|
+
type: "array",
|
|
1326
|
+
description: "One or more non-overlapping anchored edits evaluated against pre-edit 1-based line numbers.",
|
|
1327
|
+
items: {
|
|
1328
|
+
type: "object",
|
|
1329
|
+
additionalProperties: false,
|
|
1330
|
+
properties: {
|
|
1331
|
+
start_line: { type: "number", required: true, description: "1-based first line to replace (from read output)." },
|
|
1332
|
+
end_line: { type: "number", required: true, description: "1-based last line to replace (start_line - 1 inserts before start_line)." },
|
|
1333
|
+
start_text: { type: "string", description: "Original text of line start_line without line-number prefix (verifies and auto-aligns line drift)." },
|
|
1334
|
+
end_text: { type: "string", description: "Optional original text of line end_line for multi-line spans." },
|
|
1335
|
+
new_text: { type: "string", required: true, description: "Replacement lines without line-number prefixes (empty string deletes)." }
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
},
|
|
1339
|
+
start_line: { type: "number", description: "Single-hunk shorthand: 1-based first line to replace." },
|
|
1340
|
+
end_line: { type: "number", description: "Single-hunk shorthand: 1-based last line to replace (start_line - 1 inserts)." },
|
|
1341
|
+
start_text: { type: "string", description: "Single-hunk shorthand: original text of line start_line without line-number prefix." },
|
|
1342
|
+
end_text: { type: "string", description: "Single-hunk shorthand: optional original text of line end_line." },
|
|
1343
|
+
new_text: { type: "string", description: "Single-hunk shorthand: replacement lines without line numbers." }
|
|
1344
|
+
},
|
|
1345
|
+
output: {
|
|
1346
|
+
schema: {
|
|
1347
|
+
type: "object",
|
|
1348
|
+
additionalProperties: false,
|
|
1349
|
+
properties: {
|
|
1350
|
+
path: { type: "string", required: true, description: "Canonical absolute path in the filesystem execution world." },
|
|
1351
|
+
summary: { type: "string", required: true }
|
|
1352
|
+
}
|
|
1353
|
+
},
|
|
1354
|
+
render: (_args, value) => [{ type: "text", text: value.summary }]
|
|
1355
|
+
},
|
|
1356
|
+
async execute(args, exec) {
|
|
1357
|
+
const hunks = parseLineEditHunks(args);
|
|
1358
|
+
if (typeof hunks === "string") throw new Error(hunks);
|
|
1359
|
+
const allNonTrivialAnchored = hunks.every((h) => isNonTrivialAnchor(h.startText, 8));
|
|
1360
|
+
const { target, guard, folded } = await resolveTargetWithGuards(
|
|
1361
|
+
host,
|
|
1362
|
+
observations,
|
|
1363
|
+
args.file_path,
|
|
1364
|
+
exec,
|
|
1365
|
+
{ allowFolded: allNonTrivialAnchored }
|
|
1366
|
+
);
|
|
1367
|
+
try {
|
|
1368
|
+
const text = await host.fs.readText(target, exec.signal);
|
|
1369
|
+
const edited = applyAnchoredLineEdits(text, target.displayPath, hunks);
|
|
1370
|
+
if (typeof edited === "string") throw new Error(edited);
|
|
1371
|
+
const allVerified = allNonTrivialAnchored && edited.hunks.every((h) => h.anchorVerified);
|
|
1372
|
+
if (folded && !allVerified) {
|
|
1373
|
+
throw new Error(foldedUnreadErrorMessage(target.displayPath, EDIT_LINES_TOOL));
|
|
1374
|
+
}
|
|
1375
|
+
if (guard.lines !== "all" && !folded) {
|
|
1376
|
+
for (const h of edited.hunks) {
|
|
1377
|
+
const rawHunk = hunks[h.index];
|
|
1378
|
+
const startAnchored = h.anchorVerified && isNonTrivialAnchor(rawHunk?.startText, 8);
|
|
1379
|
+
const endAnchored = h.endAnchorVerified && isNonTrivialAnchor(rawHunk?.endText, 4);
|
|
1380
|
+
if (startAnchored && (h.endLine <= h.startLine || endAnchored)) continue;
|
|
1381
|
+
const missing = unseenLines(guard.lines, h, edited.before.length);
|
|
1382
|
+
if (missing.length > 0) {
|
|
1383
|
+
throw new Error(unseenRejection(target.displayPath, missing, guard.lines, edited.before.length, LINE_EDIT_CONTEXT_LINES));
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
const broken = await introducedSyntaxError(text, edited.content, target.displayPath);
|
|
1388
|
+
if (broken !== void 0) throw new Error(batchSyntaxRejection(target.displayPath, edited, broken));
|
|
1389
|
+
const expected = guard.version === void 0 ? void 0 : { kind: guard.kind, version: guard.version };
|
|
1390
|
+
const policy = sandboxPolicyFor(host.get("sandboxPolicy"), exec.agent?.session);
|
|
1391
|
+
const outcome = await host.fs.writeText(target, edited.content, expected, exec.signal, policy);
|
|
1392
|
+
host.emit("fs/observed", target, { kind: "present", version: outcome.version }, exec);
|
|
1393
|
+
observations.setLines(
|
|
1394
|
+
exec,
|
|
1395
|
+
target,
|
|
1396
|
+
seenAfterBatchEdit(guard.lines, edited.hunks, edited.after.length, LINE_EDIT_CONTEXT_LINES)
|
|
1397
|
+
);
|
|
1398
|
+
return { path: host.fs.processPath(target), summary: batchEditSummary(target.displayPath, edited) };
|
|
1399
|
+
} catch (error) {
|
|
1400
|
+
throw remediateStaleVersion(error);
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
});
|
|
1404
|
+
}
|
|
1405
|
+
function applyLineEditPlugin(ctx) {
|
|
1406
|
+
const host = ctx;
|
|
1407
|
+
const observations = attachObservations(host);
|
|
1408
|
+
host.tools.register(createLineEditToolDefinition(host, observations));
|
|
1409
|
+
}
|
|
1410
|
+
|
|
1411
|
+
// src/line-edit.ts
|
|
1412
|
+
var name = "rwkv-edit-lines";
|
|
1413
|
+
var inject = ["tools", "fs"];
|
|
1414
|
+
function apply(ctx) {
|
|
1415
|
+
applyLineEditPlugin(ctx);
|
|
1416
|
+
}
|
|
1417
|
+
export {
|
|
1418
|
+
EDIT_LINES_TOOL,
|
|
1419
|
+
apply,
|
|
1420
|
+
inject,
|
|
1421
|
+
name
|
|
1422
|
+
};
|
|
1423
|
+
//# sourceMappingURL=line-edit.js.map
|