kovence-cli 1.2.0 → 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +43 -0
- package/README.md +66 -6
- package/nd.js +22 -1
- package/package.json +1 -1
- package/providers.js +524 -113
- package/src/agent/history.js +502 -9
- package/src/agent/project_context.js +219 -24
- package/src/agent/request_logger.js +148 -0
- package/src/agent/resilience.js +296 -46
- package/src/agent/streaming_write.js +23 -15
- package/src/agent/subagent.js +655 -0
- package/src/agent/turn.js +1211 -269
- package/src/cli/args.js +9 -1
- package/src/cli/sinks.js +193 -106
- package/src/commands/handlers.js +245 -7
- package/src/config/model_registry.js +39 -2
- package/src/config/sessions.js +19 -2
- package/src/config/skills.js +425 -0
- package/src/permissions/engine.js +22 -6
- package/src/permissions/store.js +4 -1
- package/src/settings/schema.js +298 -9
- package/src/settings/store.js +75 -6
- package/src/tools/browser.js +722 -0
- package/src/tools/edit.js +471 -0
- package/src/tools/exec.js +349 -34
- package/src/tools/patch_git.js +12 -1
- package/src/tools/read_tracker.js +87 -0
- package/src/tools/tasks.js +68 -28
- package/tools.js +784 -171
- package/tui.js +142 -30
- package/ui.js +22 -1
package/src/tools/exec.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
|
-
const
|
|
3
|
+
const fs = require("node:fs");
|
|
4
|
+
const os = require("node:os");
|
|
5
|
+
const path = require("node:path");
|
|
6
|
+
const { spawn, execFile } = require("node:child_process");
|
|
4
7
|
|
|
5
8
|
const SECRET_ENV_KEY_RE =
|
|
6
9
|
/(?:^|_)(API_KEY|SECRET|TOKEN|PASSWORD|PASSWD|PRIVATE_KEY|ACCESS_KEY|CREDENTIAL|AUTH)(?:$|_)/i;
|
|
@@ -15,6 +18,19 @@ const EXTRA_SCRUB_KEYS = new Set([
|
|
|
15
18
|
"API_KEY",
|
|
16
19
|
]);
|
|
17
20
|
|
|
21
|
+
const DEFAULT_HEAD_CHARS = 16000;
|
|
22
|
+
const DEFAULT_TAIL_CHARS = 32000;
|
|
23
|
+
const MAX_TEMP_LOG_BYTES = 10 * 1024 * 1024;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Strip ANSI CSI/OSC escape sequences cleanly while preserving newlines and tabs.
|
|
27
|
+
*/
|
|
28
|
+
function stripAnsiEscapes(text) {
|
|
29
|
+
return String(text || "")
|
|
30
|
+
.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, "")
|
|
31
|
+
.replace(/\x1b\[[0-9;?=<>]*[a-zA-Z~]/g, "");
|
|
32
|
+
}
|
|
33
|
+
|
|
18
34
|
/**
|
|
19
35
|
* Strip provider/API secrets from child process env so shell commands never expose user keys.
|
|
20
36
|
*/
|
|
@@ -33,10 +49,18 @@ function scrubChildEnv(baseEnv = process.env, extraKeys = []) {
|
|
|
33
49
|
}
|
|
34
50
|
|
|
35
51
|
/**
|
|
36
|
-
* Kill a child process group cleanly (POSIX negative PID
|
|
52
|
+
* Kill a child process group cleanly (POSIX negative PID, or Windows taskkill /T).
|
|
37
53
|
*/
|
|
38
54
|
function killProcessGroup(child, sig = "SIGTERM") {
|
|
39
55
|
if (!child || !child.pid) return;
|
|
56
|
+
if (process.platform === "win32") {
|
|
57
|
+
try {
|
|
58
|
+
execFile("taskkill", ["/pid", String(child.pid), "/T", "/F"], () => {});
|
|
59
|
+
return;
|
|
60
|
+
} catch {
|
|
61
|
+
// Fall through to child.kill
|
|
62
|
+
}
|
|
63
|
+
}
|
|
40
64
|
try {
|
|
41
65
|
process.kill(-child.pid, sig);
|
|
42
66
|
} catch {
|
|
@@ -49,17 +73,78 @@ function killProcessGroup(child, sig = "SIGTERM") {
|
|
|
49
73
|
}
|
|
50
74
|
|
|
51
75
|
/**
|
|
52
|
-
*
|
|
76
|
+
* Create a head + tail ring buffer that keeps the first `headLimit` chars,
|
|
77
|
+
* the last `tailLimit` chars, and tracks total bytes seen.
|
|
78
|
+
*/
|
|
79
|
+
function createHeadTailBuffer(headLimit = DEFAULT_HEAD_CHARS, tailLimit = DEFAULT_TAIL_CHARS) {
|
|
80
|
+
let head = "";
|
|
81
|
+
let tail = "";
|
|
82
|
+
let totalChars = 0;
|
|
83
|
+
let totalBytes = 0;
|
|
84
|
+
let overflowed = false;
|
|
85
|
+
|
|
86
|
+
return {
|
|
87
|
+
push(cleanText, rawBytes = Buffer.byteLength(cleanText, "utf8")) {
|
|
88
|
+
totalBytes += rawBytes;
|
|
89
|
+
totalChars += cleanText.length;
|
|
90
|
+
if (!overflowed) {
|
|
91
|
+
const remain = headLimit - head.length;
|
|
92
|
+
if (cleanText.length <= remain) {
|
|
93
|
+
head += cleanText;
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
head += cleanText.slice(0, remain);
|
|
97
|
+
overflowed = true;
|
|
98
|
+
const rest = cleanText.slice(remain);
|
|
99
|
+
tail = rest.length > tailLimit ? rest.slice(-tailLimit) : rest;
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
if (cleanText.length >= tailLimit) {
|
|
103
|
+
tail = cleanText.slice(-tailLimit);
|
|
104
|
+
} else {
|
|
105
|
+
tail += cleanText;
|
|
106
|
+
if (tail.length > tailLimit) {
|
|
107
|
+
tail = tail.slice(-tailLimit);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
},
|
|
111
|
+
get totalBytes() {
|
|
112
|
+
return totalBytes;
|
|
113
|
+
},
|
|
114
|
+
get totalChars() {
|
|
115
|
+
return totalChars;
|
|
116
|
+
},
|
|
117
|
+
get omittedChars() {
|
|
118
|
+
if (!overflowed) return 0;
|
|
119
|
+
return Math.max(0, totalChars - head.length - tail.length);
|
|
120
|
+
},
|
|
121
|
+
render() {
|
|
122
|
+
if (!overflowed) return head;
|
|
123
|
+
const omittedChars = this.omittedChars;
|
|
124
|
+
if (omittedChars <= 0) return head + tail;
|
|
125
|
+
const omittedBytes = Math.max(omittedChars, totalBytes - Buffer.byteLength(head + tail, "utf8"));
|
|
126
|
+
return `${head}\n[... ${omittedBytes} bytes omitted ...]\n${tail}`;
|
|
127
|
+
},
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Spawn shell command in its own process group with AbortSignal, timeout (kill or background promote),
|
|
133
|
+
* ANSI stripping, and head+tail capture in arrival order.
|
|
53
134
|
*/
|
|
54
135
|
function spawnShell(
|
|
55
136
|
command,
|
|
56
137
|
{
|
|
57
138
|
cwd = process.cwd(),
|
|
58
|
-
timeout =
|
|
139
|
+
timeout = 120000,
|
|
59
140
|
stdinText = null,
|
|
60
141
|
signal = null,
|
|
61
142
|
env = null,
|
|
62
|
-
|
|
143
|
+
headChars = DEFAULT_HEAD_CHARS,
|
|
144
|
+
tailChars = DEFAULT_TAIL_CHARS,
|
|
145
|
+
timeoutBehavior = "kill",
|
|
146
|
+
onPromoteChild = null,
|
|
147
|
+
saveOverflowToFile = true,
|
|
63
148
|
onData = null,
|
|
64
149
|
} = {}
|
|
65
150
|
) {
|
|
@@ -69,26 +154,78 @@ function spawnShell(
|
|
|
69
154
|
code: "aborted",
|
|
70
155
|
stdout: "",
|
|
71
156
|
stderr: "Aborted before execution",
|
|
157
|
+
combinedOutput: "Aborted before execution",
|
|
158
|
+
totalBytes: 0,
|
|
159
|
+
omittedChars: 0,
|
|
160
|
+
durationMs: 0,
|
|
161
|
+
fullOutputPath: null,
|
|
72
162
|
timedOut: false,
|
|
73
163
|
aborted: true,
|
|
164
|
+
promotedTask: null,
|
|
74
165
|
});
|
|
75
166
|
return;
|
|
76
167
|
}
|
|
77
168
|
|
|
78
|
-
const
|
|
169
|
+
const startedAt = Date.now();
|
|
170
|
+
const isWin = process.platform === "win32";
|
|
171
|
+
const shellBin = isWin ? process.env.COMSPEC || "cmd.exe" : "sh";
|
|
172
|
+
const shellArgs = isWin ? ["/d", "/s", "/c", command] : ["-c", command];
|
|
173
|
+
|
|
174
|
+
const child = spawn(shellBin, shellArgs, {
|
|
79
175
|
cwd,
|
|
80
176
|
env: env || scrubChildEnv(process.env),
|
|
81
|
-
detached:
|
|
177
|
+
detached: !isWin,
|
|
82
178
|
stdio: ["pipe", "pipe", "pipe"],
|
|
83
179
|
});
|
|
84
180
|
|
|
85
|
-
|
|
86
|
-
|
|
181
|
+
const combinedBuf = createHeadTailBuffer(headChars, tailChars);
|
|
182
|
+
const stdoutBuf = createHeadTailBuffer(headChars, tailChars);
|
|
183
|
+
const stderrBuf = createHeadTailBuffer(headChars, tailChars);
|
|
184
|
+
|
|
185
|
+
let fullOutputPath = null;
|
|
186
|
+
let fullOutputStream = null;
|
|
187
|
+
let fullOutputBytes = 0;
|
|
188
|
+
|
|
87
189
|
let timedOut = false;
|
|
88
190
|
let aborted = false;
|
|
89
191
|
let settled = false;
|
|
90
192
|
let forceKillTimer = null;
|
|
91
193
|
|
|
194
|
+
const openOverflowFile = (initialContent) => {
|
|
195
|
+
if (!saveOverflowToFile || fullOutputPath) return;
|
|
196
|
+
try {
|
|
197
|
+
const name = `kovence-cmd-${child.pid || process.pid}-${Date.now()}.log`;
|
|
198
|
+
fullOutputPath = path.join(os.tmpdir(), name);
|
|
199
|
+
fullOutputStream = fs.createWriteStream(fullOutputPath, { encoding: "utf8" });
|
|
200
|
+
fullOutputStream.on("error", () => {
|
|
201
|
+
fullOutputStream = null;
|
|
202
|
+
});
|
|
203
|
+
const bytes = Buffer.byteLength(initialContent, "utf8");
|
|
204
|
+
if (bytes <= MAX_TEMP_LOG_BYTES) {
|
|
205
|
+
fullOutputStream.write(initialContent);
|
|
206
|
+
fullOutputBytes += bytes;
|
|
207
|
+
}
|
|
208
|
+
} catch {
|
|
209
|
+
fullOutputPath = null;
|
|
210
|
+
fullOutputStream = null;
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
const appendOverflowFile = (text) => {
|
|
215
|
+
if (!fullOutputStream || fullOutputBytes >= MAX_TEMP_LOG_BYTES) return;
|
|
216
|
+
const bytes = Buffer.byteLength(text, "utf8");
|
|
217
|
+
if (fullOutputBytes + bytes <= MAX_TEMP_LOG_BYTES) {
|
|
218
|
+
fullOutputStream.write(text);
|
|
219
|
+
fullOutputBytes += bytes;
|
|
220
|
+
} else {
|
|
221
|
+
const remain = MAX_TEMP_LOG_BYTES - fullOutputBytes;
|
|
222
|
+
if (remain > 0) {
|
|
223
|
+
fullOutputStream.write(text.slice(0, remain) + "\n[... full log truncated at 10MB cap ...]\n");
|
|
224
|
+
fullOutputBytes = MAX_TEMP_LOG_BYTES;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
|
|
92
229
|
const terminateTree = () => {
|
|
93
230
|
killProcessGroup(child, "SIGTERM");
|
|
94
231
|
forceKillTimer = setTimeout(() => {
|
|
@@ -97,49 +234,114 @@ function spawnShell(
|
|
|
97
234
|
forceKillTimer.unref?.();
|
|
98
235
|
};
|
|
99
236
|
|
|
237
|
+
const onStdoutData = (chunk) => {
|
|
238
|
+
const rawStr = chunk.toString("utf8");
|
|
239
|
+
const clean = stripAnsiEscapes(rawStr);
|
|
240
|
+
const rawBytes = Buffer.isBuffer(chunk) ? chunk.length : Buffer.byteLength(rawStr, "utf8");
|
|
241
|
+
onData?.("stdout", clean);
|
|
242
|
+
const wasOverflow = combinedBuf.omittedChars > 0;
|
|
243
|
+
const prevContent = !wasOverflow && saveOverflowToFile ? combinedBuf.render() : "";
|
|
244
|
+
combinedBuf.push(clean, rawBytes);
|
|
245
|
+
stdoutBuf.push(clean, rawBytes);
|
|
246
|
+
if (combinedBuf.omittedChars > 0) {
|
|
247
|
+
if (!fullOutputPath) {
|
|
248
|
+
openOverflowFile(prevContent + clean);
|
|
249
|
+
} else {
|
|
250
|
+
appendOverflowFile(clean);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
const onStderrData = (chunk) => {
|
|
256
|
+
const rawStr = chunk.toString("utf8");
|
|
257
|
+
const clean = stripAnsiEscapes(rawStr);
|
|
258
|
+
const rawBytes = Buffer.isBuffer(chunk) ? chunk.length : Buffer.byteLength(rawStr, "utf8");
|
|
259
|
+
onData?.("stderr", clean);
|
|
260
|
+
const wasOverflow = combinedBuf.omittedChars > 0;
|
|
261
|
+
const prevContent = !wasOverflow && saveOverflowToFile ? combinedBuf.render() : "";
|
|
262
|
+
combinedBuf.push(clean, rawBytes);
|
|
263
|
+
stderrBuf.push(clean, rawBytes);
|
|
264
|
+
if (combinedBuf.omittedChars > 0) {
|
|
265
|
+
if (!fullOutputPath) {
|
|
266
|
+
openOverflowFile(prevContent + clean);
|
|
267
|
+
} else {
|
|
268
|
+
appendOverflowFile(clean);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
|
|
100
273
|
const onAbort = () => {
|
|
101
274
|
aborted = true;
|
|
102
275
|
terminateTree();
|
|
103
276
|
};
|
|
104
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
105
|
-
|
|
106
|
-
const timer = setTimeout(() => {
|
|
107
|
-
timedOut = true;
|
|
108
|
-
terminateTree();
|
|
109
|
-
}, timeout);
|
|
110
277
|
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
278
|
+
const detachListeners = () => {
|
|
279
|
+
signal?.removeEventListener("abort", onAbort);
|
|
280
|
+
child.stdout?.removeListener("data", onStdoutData);
|
|
281
|
+
child.stderr?.removeListener("data", onStderrData);
|
|
282
|
+
child.removeListener("close", onClose);
|
|
283
|
+
child.removeListener("error", onError);
|
|
284
|
+
};
|
|
116
285
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
286
|
+
const closeOverflowStream = () => {
|
|
287
|
+
if (fullOutputStream) {
|
|
288
|
+
try {
|
|
289
|
+
fullOutputStream.end();
|
|
290
|
+
} catch {}
|
|
291
|
+
fullOutputStream = null;
|
|
292
|
+
}
|
|
293
|
+
};
|
|
122
294
|
|
|
123
|
-
const finish = (code) => {
|
|
295
|
+
const finish = (code, promotedTask = null) => {
|
|
124
296
|
if (settled) return;
|
|
125
297
|
settled = true;
|
|
126
298
|
clearTimeout(timer);
|
|
127
299
|
if (forceKillTimer) clearTimeout(forceKillTimer);
|
|
128
|
-
|
|
300
|
+
detachListeners();
|
|
301
|
+
closeOverflowStream();
|
|
129
302
|
resolve({
|
|
130
|
-
code: aborted ? "aborted" : timedOut ? "timeout" : code,
|
|
131
|
-
stdout,
|
|
132
|
-
stderr,
|
|
303
|
+
code: aborted ? "aborted" : promotedTask ? "background" : timedOut ? "timeout" : code,
|
|
304
|
+
stdout: stdoutBuf.render(),
|
|
305
|
+
stderr: stderrBuf.render(),
|
|
306
|
+
combinedOutput: combinedBuf.render(),
|
|
307
|
+
totalBytes: combinedBuf.totalBytes,
|
|
308
|
+
omittedChars: combinedBuf.omittedChars,
|
|
309
|
+
durationMs: Date.now() - startedAt,
|
|
310
|
+
fullOutputPath,
|
|
133
311
|
timedOut,
|
|
134
312
|
aborted,
|
|
313
|
+
promotedTask,
|
|
135
314
|
});
|
|
136
315
|
};
|
|
137
316
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
317
|
+
const onClose = (code) => finish(code);
|
|
318
|
+
const onError = (err) => {
|
|
319
|
+
const msg = stripAnsiEscapes(err.message);
|
|
320
|
+
stderrBuf.push((stderrBuf.totalChars ? "\n" : "") + msg);
|
|
321
|
+
combinedBuf.push((combinedBuf.totalChars ? "\n" : "") + msg);
|
|
141
322
|
finish(1);
|
|
142
|
-
}
|
|
323
|
+
};
|
|
324
|
+
|
|
325
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
326
|
+
child.stdout.on("data", onStdoutData);
|
|
327
|
+
child.stderr.on("data", onStderrData);
|
|
328
|
+
child.on("close", onClose);
|
|
329
|
+
child.on("error", onError);
|
|
330
|
+
|
|
331
|
+
const timer = setTimeout(() => {
|
|
332
|
+
timedOut = true;
|
|
333
|
+
if (timeoutBehavior === "background" && typeof onPromoteChild === "function") {
|
|
334
|
+
detachListeners();
|
|
335
|
+
const promoted = onPromoteChild(child, {
|
|
336
|
+
command,
|
|
337
|
+
cwd,
|
|
338
|
+
initialOutput: combinedBuf.render(),
|
|
339
|
+
});
|
|
340
|
+
finish("background", promoted);
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
terminateTree();
|
|
344
|
+
}, timeout);
|
|
143
345
|
|
|
144
346
|
if (stdinText !== null && stdinText !== undefined) {
|
|
145
347
|
child.stdin.write(stdinText);
|
|
@@ -148,8 +350,121 @@ function spawnShell(
|
|
|
148
350
|
});
|
|
149
351
|
}
|
|
150
352
|
|
|
353
|
+
function shellQuoteArg(value) {
|
|
354
|
+
const str = String(value ?? "");
|
|
355
|
+
if (process.platform === "win32") {
|
|
356
|
+
return `"${str.replace(/"/g, '\\"')}"`;
|
|
357
|
+
}
|
|
358
|
+
return `'${str.replace(/'/g, "'\\''")}'`;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function isInsideDirectory(childPath, parentDir) {
|
|
362
|
+
if (!childPath || !parentDir) return false;
|
|
363
|
+
const rel = path.relative(path.resolve(parentDir), path.resolve(childPath));
|
|
364
|
+
return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function resolveUserCheckConfig(ctx = {}) {
|
|
368
|
+
const workspaceRoot = path.resolve(ctx?.workspaceRoot || ctx?.cwd || process.cwd());
|
|
369
|
+
// SECURITY: never load checkCommand from any repo file (.kovence/settings.json inside workspace).
|
|
370
|
+
const settingsFile = ctx?.paths?.settingsFile;
|
|
371
|
+
if (settingsFile && isInsideDirectory(settingsFile, path.join(workspaceRoot, ".kovence"))) {
|
|
372
|
+
return { enabled: false, command: "", timeoutMs: 30000, maxLines: 30 };
|
|
373
|
+
}
|
|
374
|
+
if (ctx?.settings?._checkSource === "repo") {
|
|
375
|
+
return { enabled: false, command: "", timeoutMs: 30000, maxLines: 30 };
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
const enabled = Boolean(ctx?.settings?.checkAfterEdit);
|
|
379
|
+
const command = typeof ctx?.settings?.checkCommand === "string" ? ctx.settings.checkCommand.trim() : "";
|
|
380
|
+
const timeoutRaw = Number(ctx?.settings?.checkTimeoutMs);
|
|
381
|
+
const timeoutMs = Number.isFinite(timeoutRaw) && timeoutRaw >= 100 ? timeoutRaw : 30000;
|
|
382
|
+
const maxLinesRaw = Number.parseInt(String(ctx?.settings?.checkMaxLines ?? ""), 10);
|
|
383
|
+
const maxLines = Number.isSafeInteger(maxLinesRaw) && maxLinesRaw >= 1 ? maxLinesRaw : 30;
|
|
384
|
+
return {
|
|
385
|
+
enabled: enabled && Boolean(command),
|
|
386
|
+
command,
|
|
387
|
+
timeoutMs,
|
|
388
|
+
maxLines,
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
function formatPostEditCheckCommand(template, files = []) {
|
|
393
|
+
const cleanFiles = [...new Set((Array.isArray(files) ? files : []).filter(Boolean).map((f) => String(f)))];
|
|
394
|
+
if (!template.includes("{file}")) return template;
|
|
395
|
+
const quotedList = cleanFiles.length ? cleanFiles.map(shellQuoteArg).join(" ") : "''";
|
|
396
|
+
return template.replace(/\{file\}/g, quotedList);
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
async function runPostEditCheck({ files = [], ctx = {}, signal = null } = {}) {
|
|
400
|
+
const cfg = resolveUserCheckConfig(ctx);
|
|
401
|
+
if (!cfg.enabled || !cfg.command) {
|
|
402
|
+
return { ran: false, ok: true, timedOut: false, text: "" };
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
const cwd = path.resolve(ctx?.workspaceRoot || ctx?.cwd || process.cwd());
|
|
406
|
+
const cmd = formatPostEditCheckCommand(cfg.command, files);
|
|
407
|
+
const env = scrubChildEnv(process.env, ctx?.extraSecretEnvKeys || []);
|
|
408
|
+
const res = await spawnShell(cmd, {
|
|
409
|
+
cwd,
|
|
410
|
+
timeout: cfg.timeoutMs,
|
|
411
|
+
timeoutBehavior: "kill",
|
|
412
|
+
signal,
|
|
413
|
+
env,
|
|
414
|
+
saveOverflowToFile: false,
|
|
415
|
+
});
|
|
416
|
+
|
|
417
|
+
if (res.aborted) {
|
|
418
|
+
return { ran: true, ok: false, timedOut: false, aborted: true, text: `\n[check cancelled: ${cmd}]` };
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
const rawLines = String(res.combinedOutput || "")
|
|
422
|
+
.replace(/\r\n/g, "\n")
|
|
423
|
+
.replace(/\n+$/, "")
|
|
424
|
+
.split("\n");
|
|
425
|
+
const nonEmptyTrimmed = rawLines.length === 1 && rawLines[0] === "" ? [] : rawLines;
|
|
426
|
+
const clipped = nonEmptyTrimmed.slice(0, cfg.maxLines).join("\n");
|
|
427
|
+
const moreCount = Math.max(0, nonEmptyTrimmed.length - cfg.maxLines);
|
|
428
|
+
const body = moreCount > 0 ? `${clipped}\n... (+${moreCount} more lines)` : clipped;
|
|
429
|
+
|
|
430
|
+
if (res.timedOut) {
|
|
431
|
+
const header = `[post-edit check timed out after ${cfg.timeoutMs}ms: ${cmd}]`;
|
|
432
|
+
return {
|
|
433
|
+
ran: true,
|
|
434
|
+
ok: false,
|
|
435
|
+
timedOut: true,
|
|
436
|
+
text: body ? `\n${header}\n${body}` : `\n${header}`,
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
if (res.code !== 0) {
|
|
441
|
+
const header = `[check failed (exit ${res.code}): ${cmd}]`;
|
|
442
|
+
return {
|
|
443
|
+
ran: true,
|
|
444
|
+
ok: false,
|
|
445
|
+
timedOut: false,
|
|
446
|
+
text: body ? `\n${header}\n${body}` : `\n${header}`,
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
return {
|
|
451
|
+
ran: true,
|
|
452
|
+
ok: true,
|
|
453
|
+
timedOut: false,
|
|
454
|
+
text: `\n[check ok: ${cmd}]`,
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
|
|
151
458
|
module.exports = {
|
|
459
|
+
DEFAULT_HEAD_CHARS,
|
|
460
|
+
DEFAULT_TAIL_CHARS,
|
|
461
|
+
stripAnsiEscapes,
|
|
152
462
|
scrubChildEnv,
|
|
153
463
|
killProcessGroup,
|
|
464
|
+
createHeadTailBuffer,
|
|
154
465
|
spawnShell,
|
|
466
|
+
shellQuoteArg,
|
|
467
|
+
resolveUserCheckConfig,
|
|
468
|
+
formatPostEditCheckCommand,
|
|
469
|
+
runPostEditCheck,
|
|
155
470
|
};
|
package/src/tools/patch_git.js
CHANGED
|
@@ -128,7 +128,14 @@ function applyHunksToLines(origLines, hunks, filePathLabel) {
|
|
|
128
128
|
/**
|
|
129
129
|
* Validate and apply a unified diff patch atomically across workspace files.
|
|
130
130
|
*/
|
|
131
|
-
function applyUnifiedPatch({
|
|
131
|
+
function applyUnifiedPatch({
|
|
132
|
+
patch,
|
|
133
|
+
workspaceRoot,
|
|
134
|
+
assertFileAccess,
|
|
135
|
+
assertReadBeforeEdit,
|
|
136
|
+
onBeforeMutate,
|
|
137
|
+
onAfterMutate,
|
|
138
|
+
}) {
|
|
132
139
|
const filePatches = parseUnifiedDiff(patch);
|
|
133
140
|
if (!filePatches.length) {
|
|
134
141
|
throw new Error("Invalid or empty unified diff patch (expected --- / +++ / @@ headers).");
|
|
@@ -144,8 +151,10 @@ function applyUnifiedPatch({ patch, workspaceRoot, assertFileAccess, onBeforeMut
|
|
|
144
151
|
|
|
145
152
|
if (fp.isDelete) {
|
|
146
153
|
if (!fs.existsSync(abs)) throw new Error(`Cannot delete missing file: ${fp.targetPath}`);
|
|
154
|
+
assertReadBeforeEdit?.(abs);
|
|
147
155
|
planned.push({ abs, rel: fp.targetPath, op: "delete", nextContent: "" });
|
|
148
156
|
} else if (fp.isCreate) {
|
|
157
|
+
if (fs.existsSync(abs)) assertReadBeforeEdit?.(abs);
|
|
149
158
|
const addedLines = [];
|
|
150
159
|
for (const h of fp.hunks) {
|
|
151
160
|
for (const hl of h.lines) {
|
|
@@ -160,6 +169,7 @@ function applyUnifiedPatch({ patch, workspaceRoot, assertFileAccess, onBeforeMut
|
|
|
160
169
|
});
|
|
161
170
|
} else {
|
|
162
171
|
if (!fs.existsSync(abs)) throw new Error(`Target file not found: ${fp.targetPath}`);
|
|
172
|
+
assertReadBeforeEdit?.(abs);
|
|
163
173
|
const raw = fs.readFileSync(abs, "utf8");
|
|
164
174
|
const nextContent = applyHunksToLines(raw.split(/\r?\n/), fp.hunks, fp.targetPath);
|
|
165
175
|
planned.push({ abs, rel: fp.targetPath, op: "write", nextContent });
|
|
@@ -179,6 +189,7 @@ function applyUnifiedPatch({ patch, workspaceRoot, assertFileAccess, onBeforeMut
|
|
|
179
189
|
summary.push(`patched ${p.rel}`);
|
|
180
190
|
}
|
|
181
191
|
}
|
|
192
|
+
onAfterMutate?.(planned);
|
|
182
193
|
return summary;
|
|
183
194
|
}
|
|
184
195
|
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const crypto = require("node:crypto");
|
|
4
|
+
const fs = require("node:fs");
|
|
5
|
+
const path = require("node:path");
|
|
6
|
+
|
|
7
|
+
function hashContent(bufOrStr) {
|
|
8
|
+
return crypto.createHash("sha256").update(bufOrStr).digest("hex");
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Per-session / per-agent read-before-edit tracker.
|
|
13
|
+
* Maps resolved file path -> { mtimeMs, size, hash, stale }.
|
|
14
|
+
*/
|
|
15
|
+
class ReadTracker {
|
|
16
|
+
constructor() {
|
|
17
|
+
this.files = new Map();
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
record(absPath, content = null) {
|
|
21
|
+
const resolved = path.resolve(absPath);
|
|
22
|
+
try {
|
|
23
|
+
const st = fs.statSync(resolved);
|
|
24
|
+
const raw = content !== null ? content : fs.readFileSync(resolved);
|
|
25
|
+
this.files.set(resolved, {
|
|
26
|
+
mtimeMs: st.mtimeMs,
|
|
27
|
+
size: st.size,
|
|
28
|
+
hash: hashContent(raw),
|
|
29
|
+
stale: false,
|
|
30
|
+
});
|
|
31
|
+
} catch {
|
|
32
|
+
this.files.delete(resolved);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
markStale(absPath) {
|
|
37
|
+
const resolved = path.resolve(absPath);
|
|
38
|
+
const entry = this.files.get(resolved);
|
|
39
|
+
if (entry) entry.stale = true;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
markAllStale() {
|
|
43
|
+
for (const entry of this.files.values()) {
|
|
44
|
+
entry.stale = true;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Check whether an existing file may be edited or overwritten.
|
|
50
|
+
* Creating a new file requires no prior read.
|
|
51
|
+
*/
|
|
52
|
+
assertCanWriteOrEdit(absPath) {
|
|
53
|
+
const resolved = path.resolve(absPath);
|
|
54
|
+
if (!fs.existsSync(resolved)) return; // Creating a new file needs no prior read
|
|
55
|
+
|
|
56
|
+
const entry = this.files.get(resolved);
|
|
57
|
+
if (!entry || entry.stale) {
|
|
58
|
+
throw new Error("Read this file with read_file first (it was not read).");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
try {
|
|
62
|
+
const st = fs.statSync(resolved);
|
|
63
|
+
if (st.mtimeMs !== entry.mtimeMs || st.size !== entry.size) {
|
|
64
|
+
const currentHash = hashContent(fs.readFileSync(resolved));
|
|
65
|
+
if (currentHash !== entry.hash) {
|
|
66
|
+
throw new Error("Read this file with read_file first (it changed on disk).");
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
} catch (err) {
|
|
70
|
+
if (/Read this file with read_file first/.test(err.message)) throw err;
|
|
71
|
+
throw new Error("Read this file with read_file first (it changed on disk).");
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
isFresh(absPath) {
|
|
76
|
+
try {
|
|
77
|
+
this.assertCanWriteOrEdit(absPath);
|
|
78
|
+
return true;
|
|
79
|
+
} catch {
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
module.exports = {
|
|
86
|
+
ReadTracker,
|
|
87
|
+
};
|