kovence-cli 0.0.0-stage → 1.0.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 +15 -0
- package/LICENSE +21 -0
- package/README.md +386 -2
- package/SECURITY.md +13 -0
- package/nd.js +700 -0
- package/package.json +62 -5
- package/providers.js +530 -0
- package/src/agent/history.js +157 -0
- package/src/agent/project_context.js +136 -0
- package/src/agent/resilience.js +100 -0
- package/src/agent/turn.js +782 -0
- package/src/cli/args.js +171 -0
- package/src/cli/sinks.js +326 -0
- package/src/commands/handlers.js +1280 -0
- package/src/config/memory.js +175 -0
- package/src/config/model_registry.js +123 -0
- package/src/config/paths.js +268 -0
- package/src/config/providers.js +209 -0
- package/src/config/sessions.js +201 -0
- package/src/permissions/engine.js +846 -0
- package/src/permissions/store.js +113 -0
- package/src/settings/schema.js +340 -0
- package/src/settings/store.js +136 -0
- package/src/tools/checkpoints.js +108 -0
- package/src/tools/download.js +513 -0
- package/src/tools/exec.js +155 -0
- package/src/tools/fs_walk.js +165 -0
- package/src/tools/net.js +467 -0
- package/src/tools/patch_git.js +205 -0
- package/src/tools/sudo.js +212 -0
- package/src/tools/tasks.js +127 -0
- package/src/tui/settings_panel.js +223 -0
- package/src/tui/text_width.js +218 -0
- package/src/tui/themes.js +143 -0
- package/store.js +107 -0
- package/tools.js +1267 -0
- package/tui.js +1634 -0
- package/ui.js +394 -0
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("node:fs");
|
|
4
|
+
const path = require("node:path");
|
|
5
|
+
const { execFile } = require("node:child_process");
|
|
6
|
+
const { promisify } = require("node:util");
|
|
7
|
+
const { scrubChildEnv } = require("./exec");
|
|
8
|
+
|
|
9
|
+
const execFileAsync = promisify(execFile);
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Parse a standard unified diff into per-file hunk structures.
|
|
13
|
+
*/
|
|
14
|
+
function parseUnifiedDiff(patchText) {
|
|
15
|
+
const lines = String(patchText || "")
|
|
16
|
+
.replace(/\r\n/g, "\n")
|
|
17
|
+
.split("\n");
|
|
18
|
+
const files = [];
|
|
19
|
+
let current = null;
|
|
20
|
+
let currentHunk = null;
|
|
21
|
+
|
|
22
|
+
const stripPrefix = (p) => p.replace(/^[ab]\//, "").trim();
|
|
23
|
+
|
|
24
|
+
for (let i = 0; i < lines.length; i++) {
|
|
25
|
+
const line = lines[i];
|
|
26
|
+
if (line.startsWith("--- ")) {
|
|
27
|
+
const next = lines[i + 1] || "";
|
|
28
|
+
if (next.startsWith("+++ ")) {
|
|
29
|
+
if (current) files.push(current);
|
|
30
|
+
const oldPath = stripPrefix(line.slice(4).split("\t")[0]);
|
|
31
|
+
const newPath = stripPrefix(next.slice(4).split("\t")[0]);
|
|
32
|
+
current = {
|
|
33
|
+
oldPath,
|
|
34
|
+
newPath,
|
|
35
|
+
targetPath: newPath === "/dev/null" ? oldPath : newPath,
|
|
36
|
+
isCreate: oldPath === "/dev/null",
|
|
37
|
+
isDelete: newPath === "/dev/null",
|
|
38
|
+
hunks: [],
|
|
39
|
+
};
|
|
40
|
+
currentHunk = null;
|
|
41
|
+
i++;
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
const hunkMatch = line.match(/^@@\s+-(\d+)(?:,(\d+))?\s+\+(\d+)(?:,(\d+))?\s+@@/);
|
|
46
|
+
if (hunkMatch && current) {
|
|
47
|
+
currentHunk = {
|
|
48
|
+
oldStart: Number(hunkMatch[1]),
|
|
49
|
+
oldCount: hunkMatch[2] !== undefined ? Number(hunkMatch[2]) : 1,
|
|
50
|
+
newStart: Number(hunkMatch[3]),
|
|
51
|
+
newCount: hunkMatch[4] !== undefined ? Number(hunkMatch[4]) : 1,
|
|
52
|
+
lines: [],
|
|
53
|
+
};
|
|
54
|
+
current.hunks.push(currentHunk);
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (
|
|
58
|
+
currentHunk &&
|
|
59
|
+
(line.startsWith(" ") ||
|
|
60
|
+
line.startsWith("+") ||
|
|
61
|
+
line.startsWith("-") ||
|
|
62
|
+
line === "\")
|
|
63
|
+
) {
|
|
64
|
+
currentHunk.lines.push(line);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (current) files.push(current);
|
|
68
|
+
return files;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function applyHunksToLines(origLines, hunks, filePathLabel) {
|
|
72
|
+
const result = [...origLines];
|
|
73
|
+
let offset = 0;
|
|
74
|
+
|
|
75
|
+
for (let hIdx = 0; hIdx < hunks.length; hIdx++) {
|
|
76
|
+
const hunk = hunks[hIdx];
|
|
77
|
+
const expectedOld = [];
|
|
78
|
+
const replacement = [];
|
|
79
|
+
|
|
80
|
+
for (const hl of hunk.lines) {
|
|
81
|
+
if (hl.startsWith("\\")) continue;
|
|
82
|
+
if (hl.startsWith(" ")) {
|
|
83
|
+
expectedOld.push(hl.slice(1));
|
|
84
|
+
replacement.push(hl.slice(1));
|
|
85
|
+
} else if (hl.startsWith("-")) {
|
|
86
|
+
expectedOld.push(hl.slice(1));
|
|
87
|
+
} else if (hl.startsWith("+")) {
|
|
88
|
+
replacement.push(hl.slice(1));
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const approxIdx = Math.max(0, hunk.oldStart - 1 + offset);
|
|
93
|
+
let matchIdx = -1;
|
|
94
|
+
|
|
95
|
+
const matchesAt = (idx) => {
|
|
96
|
+
if (idx < 0 || idx + expectedOld.length > result.length) return false;
|
|
97
|
+
for (let k = 0; k < expectedOld.length; k++) {
|
|
98
|
+
if (result[idx + k] !== expectedOld[k]) return false;
|
|
99
|
+
}
|
|
100
|
+
return true;
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
if (matchesAt(approxIdx)) {
|
|
104
|
+
matchIdx = approxIdx;
|
|
105
|
+
} else {
|
|
106
|
+
for (let delta = 1; delta <= 40; delta++) {
|
|
107
|
+
if (matchesAt(approxIdx - delta)) {
|
|
108
|
+
matchIdx = approxIdx - delta;
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
if (matchesAt(approxIdx + delta)) {
|
|
112
|
+
matchIdx = approxIdx + delta;
|
|
113
|
+
break;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if (matchIdx === -1) {
|
|
119
|
+
throw new Error(`Patch hunk #${hIdx + 1} failed to match context in ${filePathLabel}`);
|
|
120
|
+
}
|
|
121
|
+
result.splice(matchIdx, expectedOld.length, ...replacement);
|
|
122
|
+
offset += replacement.length - expectedOld.length;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
return result.join("\n");
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Validate and apply a unified diff patch atomically across workspace files.
|
|
130
|
+
*/
|
|
131
|
+
function applyUnifiedPatch({ patch, workspaceRoot, assertFileAccess, onBeforeMutate }) {
|
|
132
|
+
const filePatches = parseUnifiedDiff(patch);
|
|
133
|
+
if (!filePatches.length) {
|
|
134
|
+
throw new Error("Invalid or empty unified diff patch (expected --- / +++ / @@ headers).");
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const planned = [];
|
|
138
|
+
for (const fp of filePatches) {
|
|
139
|
+
if (!fp.targetPath || fp.targetPath === "/dev/null") {
|
|
140
|
+
throw new Error("Patch missing valid target file path.");
|
|
141
|
+
}
|
|
142
|
+
const abs = path.resolve(workspaceRoot, fp.targetPath);
|
|
143
|
+
assertFileAccess?.(abs, "apply_patch");
|
|
144
|
+
|
|
145
|
+
if (fp.isDelete) {
|
|
146
|
+
if (!fs.existsSync(abs)) throw new Error(`Cannot delete missing file: ${fp.targetPath}`);
|
|
147
|
+
planned.push({ abs, rel: fp.targetPath, op: "delete", nextContent: "" });
|
|
148
|
+
} else if (fp.isCreate) {
|
|
149
|
+
const addedLines = [];
|
|
150
|
+
for (const h of fp.hunks) {
|
|
151
|
+
for (const hl of h.lines) {
|
|
152
|
+
if (hl.startsWith("+")) addedLines.push(hl.slice(1));
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
planned.push({
|
|
156
|
+
abs,
|
|
157
|
+
rel: fp.targetPath,
|
|
158
|
+
op: "write",
|
|
159
|
+
nextContent: addedLines.join("\n") + (addedLines.length ? "\n" : ""),
|
|
160
|
+
});
|
|
161
|
+
} else {
|
|
162
|
+
if (!fs.existsSync(abs)) throw new Error(`Target file not found: ${fp.targetPath}`);
|
|
163
|
+
const raw = fs.readFileSync(abs, "utf8");
|
|
164
|
+
const nextContent = applyHunksToLines(raw.split(/\r?\n/), fp.hunks, fp.targetPath);
|
|
165
|
+
planned.push({ abs, rel: fp.targetPath, op: "write", nextContent });
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
onBeforeMutate?.(planned.map((p) => p.abs));
|
|
170
|
+
|
|
171
|
+
const summary = [];
|
|
172
|
+
for (const p of planned) {
|
|
173
|
+
if (p.op === "delete") {
|
|
174
|
+
fs.unlinkSync(p.abs);
|
|
175
|
+
summary.push(`deleted ${p.rel}`);
|
|
176
|
+
} else {
|
|
177
|
+
fs.mkdirSync(path.dirname(p.abs), { recursive: true });
|
|
178
|
+
fs.writeFileSync(p.abs, p.nextContent, "utf8");
|
|
179
|
+
summary.push(`patched ${p.rel}`);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return summary;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async function execGitReadOnly(args, workspaceRoot) {
|
|
186
|
+
const env = scrubChildEnv(process.env);
|
|
187
|
+
try {
|
|
188
|
+
const { stdout, stderr } = await execFileAsync("git", args, {
|
|
189
|
+
cwd: workspaceRoot,
|
|
190
|
+
env,
|
|
191
|
+
timeout: 10000,
|
|
192
|
+
maxBuffer: 1024 * 1024,
|
|
193
|
+
});
|
|
194
|
+
return [stdout, stderr].filter(Boolean).join("\n").trim();
|
|
195
|
+
} catch (err) {
|
|
196
|
+
const msg = [err.stdout, err.stderr, err.message].filter(Boolean).join("\n").trim();
|
|
197
|
+
throw new Error(msg || "git command failed");
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
module.exports = {
|
|
202
|
+
parseUnifiedDiff,
|
|
203
|
+
applyUnifiedPatch,
|
|
204
|
+
execGitReadOnly,
|
|
205
|
+
};
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("node:fs");
|
|
4
|
+
const os = require("node:os");
|
|
5
|
+
const path = require("node:path");
|
|
6
|
+
const { spawnShell } = require("./exec");
|
|
7
|
+
|
|
8
|
+
const AUTH_FAIL_RE =
|
|
9
|
+
/authentication failed|authentication failure|incorrect password|sorry, try again|try again|no password was provided|pam_authenticate|1 incorrect password attempt|3 incorrect password attempts/i;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Rewrite `sudo` invocations in a shell command to use `-A` (SUDO_ASKPASS)
|
|
13
|
+
* so compound commands, pipes, and non-TTY detached process groups all work reliably.
|
|
14
|
+
*/
|
|
15
|
+
function rewriteSudoForAskpass(command) {
|
|
16
|
+
let cmd = String(command || "");
|
|
17
|
+
// Remove bare -S flags (stdin password mode conflicts with pipes & askpass)
|
|
18
|
+
cmd = cmd.replace(/(^|[;&|(\s])sudo\s+-S(?=\s)/g, "$1sudo");
|
|
19
|
+
// Inject -A on every sudo invocation unless -A or -n is already present
|
|
20
|
+
cmd = cmd.replace(/(^|[;&|(\s])sudo(?=\s|$)(?!\s+-[A-Za-z]*[An])/g, "$1sudo -A");
|
|
21
|
+
return cmd;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Create an ephemeral 0700 temp directory with a 0600 password file and 0700 askpass script.
|
|
26
|
+
* When `oneShot` is true, the script supplies the password only on the first call and exits 1
|
|
27
|
+
* on subsequent retries within the same sudo process, avoiding 3x PAM lock delays on wrong passwords.
|
|
28
|
+
*/
|
|
29
|
+
function createEphemeralAskpass(password, { oneShot = false } = {}) {
|
|
30
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "kovence-askpass-"));
|
|
31
|
+
try {
|
|
32
|
+
fs.chmodSync(dir, 0o700);
|
|
33
|
+
} catch {}
|
|
34
|
+
|
|
35
|
+
const pwFile = path.join(dir, "pw");
|
|
36
|
+
const usedFile = path.join(dir, "used");
|
|
37
|
+
const scriptFile = path.join(dir, "askpass.sh");
|
|
38
|
+
|
|
39
|
+
fs.writeFileSync(pwFile, `${password}\n`, { encoding: "utf8", mode: 0o600 });
|
|
40
|
+
try {
|
|
41
|
+
fs.chmodSync(pwFile, 0o600);
|
|
42
|
+
} catch {}
|
|
43
|
+
|
|
44
|
+
const safePwPath = pwFile.replace(/'/g, "'\\''");
|
|
45
|
+
const safeUsedPath = usedFile.replace(/'/g, "'\\''");
|
|
46
|
+
const script = oneShot
|
|
47
|
+
? `#!/bin/sh\nif [ -f '${safeUsedPath}' ]; then exit 1; fi\n: > '${safeUsedPath}'\ncat '${safePwPath}'\n`
|
|
48
|
+
: `#!/bin/sh\ncat '${safePwPath}'\n`;
|
|
49
|
+
|
|
50
|
+
fs.writeFileSync(scriptFile, script, { encoding: "utf8", mode: 0o700 });
|
|
51
|
+
try {
|
|
52
|
+
fs.chmodSync(scriptFile, 0o700);
|
|
53
|
+
} catch {}
|
|
54
|
+
|
|
55
|
+
const cleanup = () => {
|
|
56
|
+
try {
|
|
57
|
+
if (fs.existsSync(pwFile)) {
|
|
58
|
+
fs.writeFileSync(pwFile, "\0".repeat(Math.max(32, password.length + 1)), { mode: 0o600 });
|
|
59
|
+
}
|
|
60
|
+
} catch {}
|
|
61
|
+
try {
|
|
62
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
63
|
+
} catch {}
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
return { dir, pwFile, scriptFile, cleanup };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Check if passwordless sudo works in the SAME detached execution context as spawnShell.
|
|
71
|
+
*/
|
|
72
|
+
async function canRunPasswordlessSudo({ cwd, env, signal }) {
|
|
73
|
+
const check = await spawnShell("sudo -n true", { cwd, timeout: 2500, signal, env });
|
|
74
|
+
return !check.aborted && !check.timedOut && check.code === 0;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Verify a candidate sudo password quickly with a 1-shot askpass helper before executing the real command.
|
|
79
|
+
*/
|
|
80
|
+
async function verifySudoPassword(password, { cwd, env, signal }) {
|
|
81
|
+
const askpass = createEphemeralAskpass(password, { oneShot: true });
|
|
82
|
+
try {
|
|
83
|
+
const res = await spawnShell("sudo -A true", {
|
|
84
|
+
cwd,
|
|
85
|
+
timeout: 8000,
|
|
86
|
+
signal,
|
|
87
|
+
env: { ...env, SUDO_ASKPASS: askpass.scriptFile },
|
|
88
|
+
});
|
|
89
|
+
if (res.aborted) return { ok: false, aborted: true };
|
|
90
|
+
if (res.code === 0) return { ok: true };
|
|
91
|
+
const combined = [res.stdout, res.stderr].filter(Boolean).join("\n").trim();
|
|
92
|
+
return {
|
|
93
|
+
ok: false,
|
|
94
|
+
authFailed: AUTH_FAIL_RE.test(combined) || res.code === 1,
|
|
95
|
+
output: combined,
|
|
96
|
+
};
|
|
97
|
+
} finally {
|
|
98
|
+
askpass.cleanup();
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Execute a shell command containing `sudo`, prompting interactively for the password when needed,
|
|
104
|
+
* showing a clear warning and re-prompting whenever the password is wrong.
|
|
105
|
+
*/
|
|
106
|
+
async function runWithSudo(command, { cwd, timeout, ctx, env, onData = null, capOutput = (s) => s } = {}) {
|
|
107
|
+
if (await canRunPasswordlessSudo({ cwd, env, signal: ctx?.signal })) {
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const rewritten = rewriteSudoForAskpass(command);
|
|
112
|
+
const maxAttempts = 3;
|
|
113
|
+
|
|
114
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
115
|
+
if (ctx?.signal?.aborted) return "Command aborted by user.";
|
|
116
|
+
|
|
117
|
+
let pw = ctx?.getSudoPassword?.() || "";
|
|
118
|
+
let promptedNow = false;
|
|
119
|
+
if (!pw) {
|
|
120
|
+
if (!ctx?.askPassword) {
|
|
121
|
+
throw new Error("sudo password required but interactive prompt unavailable.");
|
|
122
|
+
}
|
|
123
|
+
const label =
|
|
124
|
+
attempt === 0
|
|
125
|
+
? `[sudo] password required (masked): `
|
|
126
|
+
: `[sudo] Password incorrect! Enter sudo password again (${attempt + 1}/${maxAttempts}): `;
|
|
127
|
+
ctx?.setBusy?.(
|
|
128
|
+
attempt === 0 ? "Waiting for sudo password..." : "Password incorrect — waiting for retry..."
|
|
129
|
+
);
|
|
130
|
+
pw = await ctx.askPassword(label);
|
|
131
|
+
promptedNow = true;
|
|
132
|
+
if (ctx?.signal?.aborted) return "Command aborted by user.";
|
|
133
|
+
if (!pw) throw new Error("sudo cancelled by user (empty password).");
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
ctx?.setBusy?.("Verifying sudo password...");
|
|
137
|
+
const check = await verifySudoPassword(pw, { cwd, env, signal: ctx?.signal });
|
|
138
|
+
if (check.aborted) return "Command aborted by user.";
|
|
139
|
+
if (!check.ok) {
|
|
140
|
+
ctx?.setSudoPassword?.(null);
|
|
141
|
+
// If a previously cached password expired/failed, don't count it against user's interactive attempts
|
|
142
|
+
if (!promptedNow) {
|
|
143
|
+
attempt -= 1;
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
const remaining = maxAttempts - (attempt + 1);
|
|
147
|
+
if (remaining > 0) {
|
|
148
|
+
ctx?.log?.(
|
|
149
|
+
"error",
|
|
150
|
+
`⚠ Sudo password incorrect! Please try again (${remaining} attempt${remaining > 1 ? "s" : ""} remaining).`
|
|
151
|
+
);
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
ctx?.log?.("error", "✖ Sudo authentication failed after 3 incorrect password attempts.");
|
|
155
|
+
throw new Error("sudo authentication failed after 3 incorrect password attempts.");
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Password verified! Cache it for the session and run the actual command
|
|
159
|
+
ctx?.setSudoPassword?.(pw);
|
|
160
|
+
const askpass = createEphemeralAskpass(pw, { oneShot: false });
|
|
161
|
+
ctx?.setBusy?.("Running sudo command...");
|
|
162
|
+
let res;
|
|
163
|
+
try {
|
|
164
|
+
const sudoEnv = {
|
|
165
|
+
...env,
|
|
166
|
+
SUDO_ASKPASS: askpass.scriptFile,
|
|
167
|
+
DEBIAN_FRONTEND: env?.DEBIAN_FRONTEND || "noninteractive",
|
|
168
|
+
};
|
|
169
|
+
res = await spawnShell(rewritten, {
|
|
170
|
+
cwd,
|
|
171
|
+
timeout,
|
|
172
|
+
signal: ctx?.signal,
|
|
173
|
+
env: sudoEnv,
|
|
174
|
+
onData,
|
|
175
|
+
});
|
|
176
|
+
} finally {
|
|
177
|
+
askpass.cleanup();
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
if (res.aborted) return "Command aborted by user.";
|
|
181
|
+
const scrub = (s) => (pw ? String(s).split(pw).join("[REDACTED]") : String(s));
|
|
182
|
+
const combined = scrub([res.stdout, res.stderr].filter(Boolean).join("\n").trim());
|
|
183
|
+
|
|
184
|
+
if (res.code !== 0 && AUTH_FAIL_RE.test(combined)) {
|
|
185
|
+
ctx?.setSudoPassword?.(null);
|
|
186
|
+
if (attempt + 1 < maxAttempts) {
|
|
187
|
+
ctx?.log?.("error", "⚠ Sudo password incorrect! Please try again.");
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
throw new Error("sudo authentication failed (incorrect password).");
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
if (res.timedOut) {
|
|
194
|
+
return capOutput(`Command timed out after ${Math.round(timeout / 1000)}s:\n${combined}`.trim());
|
|
195
|
+
}
|
|
196
|
+
if (res.code === 0) {
|
|
197
|
+
return capOutput(combined || "(sudo command exited 0 with no output)");
|
|
198
|
+
}
|
|
199
|
+
return capOutput(`Exit ${res.code ?? "error"}:\n${combined}`);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
throw new Error("sudo authentication failed.");
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
module.exports = {
|
|
206
|
+
AUTH_FAIL_RE,
|
|
207
|
+
rewriteSudoForAskpass,
|
|
208
|
+
createEphemeralAskpass,
|
|
209
|
+
canRunPasswordlessSudo,
|
|
210
|
+
verifySudoPassword,
|
|
211
|
+
runWithSudo,
|
|
212
|
+
};
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { spawn } = require("node:child_process");
|
|
4
|
+
const { scrubChildEnv, killProcessGroup } = require("./exec");
|
|
5
|
+
|
|
6
|
+
const MAX_LOG_CHARS = 64000;
|
|
7
|
+
|
|
8
|
+
class BackgroundTaskManager {
|
|
9
|
+
constructor({ onChange = null } = {}) {
|
|
10
|
+
this.tasks = new Map();
|
|
11
|
+
this.seq = 0;
|
|
12
|
+
this.onChange = onChange;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
startTask(command, { cwd = process.cwd(), env = null } = {}) {
|
|
16
|
+
this.seq += 1;
|
|
17
|
+
const id = String(this.seq);
|
|
18
|
+
const child = spawn("sh", ["-c", command], {
|
|
19
|
+
cwd,
|
|
20
|
+
env: env || scrubChildEnv(process.env),
|
|
21
|
+
detached: process.platform !== "win32",
|
|
22
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
const task = {
|
|
26
|
+
id,
|
|
27
|
+
pid: child.pid,
|
|
28
|
+
command: String(command),
|
|
29
|
+
cwd,
|
|
30
|
+
startedAt: new Date().toISOString(),
|
|
31
|
+
endedAt: null,
|
|
32
|
+
status: "running",
|
|
33
|
+
exitCode: null,
|
|
34
|
+
output: "",
|
|
35
|
+
_child: child,
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const appendOut = (chunk) => {
|
|
39
|
+
task.output += chunk.toString("utf8");
|
|
40
|
+
if (task.output.length > MAX_LOG_CHARS) {
|
|
41
|
+
task.output = task.output.slice(-MAX_LOG_CHARS);
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
child.stdout?.on("data", appendOut);
|
|
46
|
+
child.stderr?.on("data", appendOut);
|
|
47
|
+
child.on("close", (code) => {
|
|
48
|
+
if (task.status === "running") {
|
|
49
|
+
task.status = "exited";
|
|
50
|
+
}
|
|
51
|
+
task.exitCode = code;
|
|
52
|
+
task.endedAt = new Date().toISOString();
|
|
53
|
+
task._child = null;
|
|
54
|
+
this.onChange?.();
|
|
55
|
+
});
|
|
56
|
+
child.on("error", (err) => {
|
|
57
|
+
task.output += `\n[error: ${err.message}]`;
|
|
58
|
+
task.status = "exited";
|
|
59
|
+
task.exitCode = 1;
|
|
60
|
+
task.endedAt = new Date().toISOString();
|
|
61
|
+
task._child = null;
|
|
62
|
+
this.onChange?.();
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
this.tasks.set(id, task);
|
|
66
|
+
this.onChange?.();
|
|
67
|
+
return this.serializeTask(task);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
serializeTask(task) {
|
|
71
|
+
return {
|
|
72
|
+
id: task.id,
|
|
73
|
+
pid: task.pid,
|
|
74
|
+
command: task.command,
|
|
75
|
+
startedAt: task.startedAt,
|
|
76
|
+
endedAt: task.endedAt,
|
|
77
|
+
status: task.status,
|
|
78
|
+
exitCode: task.exitCode,
|
|
79
|
+
output: task.output,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
listTasks() {
|
|
84
|
+
return [...this.tasks.values()].map((t) => this.serializeTask(t));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
activeCount() {
|
|
88
|
+
let count = 0;
|
|
89
|
+
for (const t of this.tasks.values()) {
|
|
90
|
+
if (t.status === "running") count += 1;
|
|
91
|
+
}
|
|
92
|
+
return count;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
getTask(id) {
|
|
96
|
+
const t = this.tasks.get(String(id));
|
|
97
|
+
return t ? this.serializeTask(t) : null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
killTask(id) {
|
|
101
|
+
const t = this.tasks.get(String(id));
|
|
102
|
+
if (!t) return false;
|
|
103
|
+
if (t.status === "running" && t._child) {
|
|
104
|
+
t.status = "killed";
|
|
105
|
+
killProcessGroup(t._child, "SIGTERM");
|
|
106
|
+
setTimeout(() => {
|
|
107
|
+
if (t._child) killProcessGroup(t._child, "SIGKILL");
|
|
108
|
+
}, 300).unref?.();
|
|
109
|
+
this.onChange?.();
|
|
110
|
+
return true;
|
|
111
|
+
}
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
killAll() {
|
|
116
|
+
for (const t of this.tasks.values()) {
|
|
117
|
+
if (t.status === "running" && t._child) {
|
|
118
|
+
t.status = "killed";
|
|
119
|
+
killProcessGroup(t._child, "SIGTERM");
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
module.exports = {
|
|
126
|
+
BackgroundTaskManager,
|
|
127
|
+
};
|