@bolt-cli/cli 0.0.0-stage → 0.13.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 +75 -0
- package/README.md +155 -2
- package/bin/bolt.js +21 -0
- package/lib/agent.js +361 -0
- package/lib/api.js +246 -0
- package/lib/bootstrap.js +292 -0
- package/lib/browser.js +152 -0
- package/lib/cancel.js +153 -0
- package/lib/checkpoints.js +67 -0
- package/lib/cli.js +2637 -0
- package/lib/completion.js +77 -0
- package/lib/config.js +80 -0
- package/lib/doctor.js +110 -0
- package/lib/export.js +77 -0
- package/lib/history.js +78 -0
- package/lib/memory.js +80 -0
- package/lib/output.js +88 -0
- package/lib/permissions.js +167 -0
- package/lib/present.js +181 -0
- package/lib/redact.js +56 -0
- package/lib/session.js +153 -0
- package/lib/toolparse.js +752 -0
- package/lib/tools.js +606 -0
- package/lib/ui.js +783 -0
- package/lib/updatecheck.js +114 -0
- package/lib/watch.js +698 -0
- package/package.json +36 -6
- package/templates/README.md +44 -0
- package/templates/aslr-offset-probe.sh +96 -0
- package/templates/crash-offset-pattern.sh +81 -0
package/lib/tools.js
ADDED
|
@@ -0,0 +1,606 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Local tools for the bolt agent loop (Claude Code / opencode style).
|
|
3
|
+
//
|
|
4
|
+
// The model asks for tool calls with fenced blocks:
|
|
5
|
+
//
|
|
6
|
+
// ```tool
|
|
7
|
+
// {"tool": "read", "path": "src/app.ts", "limit": 80}
|
|
8
|
+
// ```
|
|
9
|
+
//
|
|
10
|
+
// Reads, file search and globbing run freely; writes, edits and shell
|
|
11
|
+
// commands need operator approval (once, or for the session), and a small
|
|
12
|
+
// blocklist of destructive commands is always refused. Writes, edits and
|
|
13
|
+
// the shell working directory are sandboxed to the project root (the cwd
|
|
14
|
+
// the CLI started in); ../ escapes and absolute paths outside it are
|
|
15
|
+
// refused. Zero deps: node:fs, node:path, node:child_process only.
|
|
16
|
+
const fs = require("fs");
|
|
17
|
+
const path = require("path");
|
|
18
|
+
const { execFile } = require("node:child_process");
|
|
19
|
+
const bootstrap = require("./bootstrap");
|
|
20
|
+
const checkpoints = require("./checkpoints");
|
|
21
|
+
const toolparse = require("./toolparse");
|
|
22
|
+
|
|
23
|
+
// Tool names and the per-turn block cap live in toolparse.js (the parser
|
|
24
|
+
// validates against them); re-exported here for every existing consumer.
|
|
25
|
+
const { TOOL_NAMES, MAX_TOOL_BLOCKS } = toolparse;
|
|
26
|
+
const MAX_READ_CHARS = 12_000;
|
|
27
|
+
const MAX_RESULT_CHARS = 4_000;
|
|
28
|
+
const BASH_TIMEOUT_MS = 120_000;
|
|
29
|
+
// Always refused, no approval path: destroying the machine or the disk is
|
|
30
|
+
// never a legitimate step of an investigation or a build.
|
|
31
|
+
const BLOCKED_COMMAND = [
|
|
32
|
+
/\bmkfs\b/i,
|
|
33
|
+
/\bdd\b[^|;&]*\bof=\/dev\//i,
|
|
34
|
+
/:\(\)\s*\{\s*:|:&\s*\};:/,
|
|
35
|
+
/\b(shutdown|reboot|halt|poweroff)\b/i,
|
|
36
|
+
/\bchmod\s+(-R\s+)?(777|a\+w)\s+\//,
|
|
37
|
+
/\bchown\s+-R\b[^|;&]*\s+\//,
|
|
38
|
+
/>\s*\/dev\/sd[a-z]/i,
|
|
39
|
+
/\bdiskpart\b/i,
|
|
40
|
+
/\bformat\s+[a-z]:/i,
|
|
41
|
+
];
|
|
42
|
+
|
|
43
|
+
// Read-only commands that run without asking. Everything else bash goes
|
|
44
|
+
// through approval; anything matching BLOCKED_COMMAND is refused outright.
|
|
45
|
+
const SAFE_COMMAND = [
|
|
46
|
+
/^(ls|pwd|whoami|date|echo|true)\b/,
|
|
47
|
+
/^node\s+--version$/,
|
|
48
|
+
/^npm\s+--version$/,
|
|
49
|
+
/^git\s+(status|diff|diff\s+--stat|log|show)\b/,
|
|
50
|
+
];
|
|
51
|
+
|
|
52
|
+
// Legacy fence-only parser, kept for callers/tests that only need
|
|
53
|
+
// {calls, errors}. The real extraction is model-agnostic (fences, XML tool
|
|
54
|
+
// tags, bare JSON, think stripping) — see toolparse.extractToolCalls.
|
|
55
|
+
function parseToolBlocks(text) {
|
|
56
|
+
const { calls, errors } = toolparse.extractToolCalls(text);
|
|
57
|
+
return { calls, errors };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function describeCall(call) {
|
|
61
|
+
switch (call.tool) {
|
|
62
|
+
case "read":
|
|
63
|
+
return `read ${call.path || "(missing path)"}`;
|
|
64
|
+
case "glob":
|
|
65
|
+
return `glob ${call.pattern || "(missing pattern)"}`;
|
|
66
|
+
case "grep":
|
|
67
|
+
return `grep ${call.pattern || "(missing pattern)"}${call.path ? ` in ${call.path}` : ""}`;
|
|
68
|
+
case "list":
|
|
69
|
+
return `list ${call.path || "."}`;
|
|
70
|
+
case "write":
|
|
71
|
+
return `write ${call.path || "(missing path)"} (${(call.content || "").length} chars)`;
|
|
72
|
+
case "edit":
|
|
73
|
+
return `edit ${call.path || "(missing path)"}`;
|
|
74
|
+
case "ask": {
|
|
75
|
+
const q = String(call.question || "").slice(0, 80);
|
|
76
|
+
const n = Array.isArray(call.options) ? call.options.length : 0;
|
|
77
|
+
return `ask "${q || "(missing question)"}" (${n} options)`;
|
|
78
|
+
}
|
|
79
|
+
case "bash": {
|
|
80
|
+
const via = process.platform === "win32" && detectWSL() ? " [via WSL]" : "";
|
|
81
|
+
return `bash $ ${call.command || "(missing command)"}${via}`;
|
|
82
|
+
}
|
|
83
|
+
default:
|
|
84
|
+
return String(call.tool);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// ---------------------------------------------------------------- ask_user
|
|
89
|
+
|
|
90
|
+
// Validates an `ask` tool call: {tool:"ask", question, options[], allowCustom?}.
|
|
91
|
+
// The model uses this when it needs the operator to choose before it can
|
|
92
|
+
// continue (scope, target, strategy) - Claude Code style. Returns {ok, question,
|
|
93
|
+
// options} with options capped and trimmed.
|
|
94
|
+
function normalizeAskCall(call) {
|
|
95
|
+
const question = String((call && call.question) || "").trim();
|
|
96
|
+
const raw = Array.isArray(call && call.options) ? call.options : [];
|
|
97
|
+
const options = raw
|
|
98
|
+
.map((o) => String(o ?? "").trim())
|
|
99
|
+
.filter(Boolean)
|
|
100
|
+
.slice(0, 6);
|
|
101
|
+
if (!question) return { ok: false, error: "ask needs a question" };
|
|
102
|
+
if (options.length < 2) return { ok: false, error: "ask needs at least 2 options" };
|
|
103
|
+
return { ok: true, question, options, allowCustom: call && call.allowCustom !== false };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Project sandbox: writes, edits and the shell live under the directory the
|
|
107
|
+
// CLI started in. path.resolve collapses ../ first, so the prefix check
|
|
108
|
+
// below catches traversal escapes; the comparison is case-insensitive on
|
|
109
|
+
// Windows where the filesystem is.
|
|
110
|
+
function resolveInRoot(root, input) {
|
|
111
|
+
if (typeof input !== "string" || !input.trim()) return { ok: false, error: "missing path" };
|
|
112
|
+
const resolved = path.resolve(root, input);
|
|
113
|
+
const lower = process.platform === "win32" ? resolved.toLowerCase() : resolved;
|
|
114
|
+
const base = process.platform === "win32" ? root.toLowerCase() : root;
|
|
115
|
+
if (lower !== base && !lower.startsWith(base.endsWith(path.sep) ? base : base + path.sep)) {
|
|
116
|
+
return { ok: false, error: `outside project root (${root})` };
|
|
117
|
+
}
|
|
118
|
+
return { ok: true, path: resolved };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function truncate(text, max = MAX_RESULT_CHARS) {
|
|
122
|
+
const s = String(text ?? "");
|
|
123
|
+
return s.length > max ? `${s.slice(0, max)}\n…(truncated, ${s.length} chars total)` : s;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* @-mentions: "@src/app.ts" in a prompt inlines that file as evidence. Only
|
|
128
|
+
* names that resolve to a real file are attached — emails and literal @words
|
|
129
|
+
* pass through untouched. The prompt text itself is left as typed so the
|
|
130
|
+
* reference stays readable; content travels as evidence.
|
|
131
|
+
*/
|
|
132
|
+
function resolveMentions(text, root, { maxFiles = 3, maxChars = MAX_READ_CHARS } = {}) {
|
|
133
|
+
const files = [];
|
|
134
|
+
const parts = [];
|
|
135
|
+
const seen = new Set();
|
|
136
|
+
const pattern = /(^|\s)@([^\s@]+)/g;
|
|
137
|
+
let m;
|
|
138
|
+
while ((m = pattern.exec(String(text || ""))) !== null && files.length < maxFiles) {
|
|
139
|
+
const name = m[2].replace(/[.,;:!?)]+$/, "");
|
|
140
|
+
if (!name || seen.has(name)) continue;
|
|
141
|
+
const full = path.resolve(root, name);
|
|
142
|
+
let stat;
|
|
143
|
+
try {
|
|
144
|
+
stat = fs.statSync(full);
|
|
145
|
+
} catch {
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
if (!stat.isFile()) continue;
|
|
149
|
+
let content;
|
|
150
|
+
try {
|
|
151
|
+
content = fs.readFileSync(full, "utf8");
|
|
152
|
+
} catch {
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
if (!content.trim()) continue;
|
|
156
|
+
seen.add(name);
|
|
157
|
+
files.push(name);
|
|
158
|
+
parts.push(`--- ${name} ---\n${content.slice(0, maxChars)}`);
|
|
159
|
+
}
|
|
160
|
+
return { files, evidence: parts.join("\n\n") };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function readFile(filePath, offset, limit) {
|
|
164
|
+
let content;
|
|
165
|
+
try {
|
|
166
|
+
content = fs.readFileSync(filePath, "utf8");
|
|
167
|
+
} catch {
|
|
168
|
+
return { ok: false, summary: "cannot read file", detail: `Cannot read ${filePath}.` };
|
|
169
|
+
}
|
|
170
|
+
const lines = content.split("\n");
|
|
171
|
+
const start = Math.max(0, Number(offset) || 0);
|
|
172
|
+
const end = limit ? start + Math.max(1, Number(limit)) : lines.length;
|
|
173
|
+
const slice = lines.slice(start, end).join("\n").slice(0, MAX_READ_CHARS);
|
|
174
|
+
return { ok: true, summary: `${lines.length} lines`, detail: start > 0 || end < lines.length ? `(lines ${start + 1}-${Math.min(end, lines.length)} of ${lines.length})\n${slice}` : slice };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function globFiles(root, pattern) {
|
|
178
|
+
if (typeof pattern !== "string" || !pattern.trim()) return { ok: false, summary: "missing pattern", detail: "glob needs a pattern like \"src/**/*.ts\"." };
|
|
179
|
+
// Minimal glob: ** (any depth), * (within a segment), ? (one char).
|
|
180
|
+
const escaped = pattern.split("/").map((seg) => {
|
|
181
|
+
if (seg === "**") return "**";
|
|
182
|
+
return seg.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]");
|
|
183
|
+
});
|
|
184
|
+
const regex = new RegExp(`^${escaped.join("/").replace(/\*\*\/\*\*/g, ".*").replace(/\/\*\*(\/|$)/g, "($1.*)?").replace(/^\*\*$/, ".*")}$`);
|
|
185
|
+
const hits = [];
|
|
186
|
+
const walk = (dir, rel) => {
|
|
187
|
+
let entries;
|
|
188
|
+
try {
|
|
189
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
190
|
+
} catch {
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
for (const entry of entries) {
|
|
194
|
+
if (entry.name === "node_modules" || entry.name === ".git" || entry.name === ".next") continue;
|
|
195
|
+
const relPath = rel ? `${rel}/${entry.name}` : entry.name;
|
|
196
|
+
if (entry.isDirectory()) {
|
|
197
|
+
if (hits.length < 200) walk(path.join(dir, entry.name), relPath);
|
|
198
|
+
} else if (regex.test(relPath)) {
|
|
199
|
+
hits.push(relPath);
|
|
200
|
+
if (hits.length >= 200) return;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
walk(root, "");
|
|
205
|
+
return { ok: true, summary: `${hits.length} match${hits.length === 1 ? "" : "es"}`, detail: hits.join("\n") || "(no matches)" };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function grepFiles(root, pattern, startPath) {
|
|
209
|
+
if (typeof pattern !== "string" || !pattern.trim()) return { ok: false, summary: "missing pattern", detail: "grep needs a pattern." };
|
|
210
|
+
let regex;
|
|
211
|
+
try {
|
|
212
|
+
regex = new RegExp(pattern, "i");
|
|
213
|
+
} catch {
|
|
214
|
+
return { ok: false, summary: "bad pattern", detail: `Cannot compile regex: ${pattern}` };
|
|
215
|
+
}
|
|
216
|
+
const base = startPath ? resolveInRoot(root, startPath) : { ok: true, path: root };
|
|
217
|
+
if (!base.ok) return { ok: false, summary: "bad path", detail: base.error };
|
|
218
|
+
const hits = [];
|
|
219
|
+
const walk = (dir) => {
|
|
220
|
+
let entries;
|
|
221
|
+
try {
|
|
222
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
223
|
+
} catch {
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
for (const entry of entries) {
|
|
227
|
+
if (entry.name === "node_modules" || entry.name === ".git" || entry.name === ".next") continue;
|
|
228
|
+
const full = path.join(dir, entry.name);
|
|
229
|
+
if (entry.isDirectory()) {
|
|
230
|
+
if (hits.length < 100) walk(full);
|
|
231
|
+
} else if (/\.(ts|tsx|js|jsx|mjs|cjs|json|md|py|sh|yml|yaml|toml|txt|tsbuildinfo|css|html)$/i.test(entry.name)) {
|
|
232
|
+
let content;
|
|
233
|
+
try {
|
|
234
|
+
content = fs.readFileSync(full, "utf8");
|
|
235
|
+
} catch {
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
const lines = content.split("\n");
|
|
239
|
+
for (let i = 0; i < lines.length && hits.length < 100; i += 1) {
|
|
240
|
+
if (regex.test(lines[i])) hits.push(`${path.relative(root, full).replace(/\\/g, "/")}:${i + 1}: ${lines[i].trim().slice(0, 160)}`);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
if (hits.length >= 100) return;
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
try {
|
|
247
|
+
const stat = fs.statSync(base.path);
|
|
248
|
+
if (stat.isFile()) {
|
|
249
|
+
const lines = fs.readFileSync(base.path, "utf8").split("\n");
|
|
250
|
+
lines.forEach((line, i) => {
|
|
251
|
+
if (regex.test(line) && hits.length < 100) hits.push(`${path.relative(root, base.path).replace(/\\/g, "/")}:${i + 1}: ${line.trim().slice(0, 160)}`);
|
|
252
|
+
});
|
|
253
|
+
} else walk(base.path);
|
|
254
|
+
} catch {
|
|
255
|
+
return { ok: false, summary: "cannot search", detail: `Cannot search ${startPath || root}.` };
|
|
256
|
+
}
|
|
257
|
+
return { ok: true, summary: `${hits.length} hit${hits.length === 1 ? "" : "s"}`, detail: hits.join("\n") || "(no matches)" };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function applyEdit(root, filePath, oldString, newString) {
|
|
261
|
+
if (typeof oldString !== "string" || !oldString) return { ok: false, summary: "missing oldString", detail: "edit needs oldString and newString." };
|
|
262
|
+
if (typeof newString !== "string") return { ok: false, summary: "missing newString", detail: "edit needs oldString and newString." };
|
|
263
|
+
const target = resolveInRoot(root, filePath);
|
|
264
|
+
if (!target.ok) return { ok: false, summary: "refused", detail: target.error };
|
|
265
|
+
checkpoints.saveBackup(root, target.path);
|
|
266
|
+
let content;
|
|
267
|
+
try {
|
|
268
|
+
content = fs.readFileSync(target.path, "utf8");
|
|
269
|
+
} catch {
|
|
270
|
+
return { ok: false, summary: "cannot read file", detail: `Cannot read ${filePath}.` };
|
|
271
|
+
}
|
|
272
|
+
const first = content.indexOf(oldString);
|
|
273
|
+
if (first === -1) return { ok: false, summary: "no match", detail: "oldString not found in file." };
|
|
274
|
+
if (content.indexOf(oldString, first + 1) !== -1) {
|
|
275
|
+
return { ok: false, summary: "ambiguous", detail: "oldString matches multiple places; include more context to make it unique." };
|
|
276
|
+
}
|
|
277
|
+
const updated = content.slice(0, first) + newString + content.slice(first + oldString.length);
|
|
278
|
+
try {
|
|
279
|
+
fs.writeFileSync(target.path, updated);
|
|
280
|
+
} catch {
|
|
281
|
+
return { ok: false, summary: "write failed", detail: `Cannot write ${filePath}.` };
|
|
282
|
+
}
|
|
283
|
+
return { ok: true, summary: "edited", detail: `Edited ${filePath}.` };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function writeFile(root, filePath, content) {
|
|
287
|
+
const target = resolveInRoot(root, filePath);
|
|
288
|
+
if (!target.ok) return { ok: false, summary: "refused", detail: target.error };
|
|
289
|
+
checkpoints.saveBackup(root, target.path);
|
|
290
|
+
try {
|
|
291
|
+
fs.mkdirSync(path.dirname(target.path), { recursive: true });
|
|
292
|
+
fs.writeFileSync(target.path, String(content ?? ""));
|
|
293
|
+
} catch {
|
|
294
|
+
return { ok: false, summary: "write failed", detail: `Cannot write ${filePath}.` };
|
|
295
|
+
}
|
|
296
|
+
return { ok: true, summary: "written", detail: `Wrote ${filePath} (${String(content ?? "").length} chars).` };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function bashBlocked(command) {
|
|
300
|
+
return BLOCKED_COMMAND.some((re) => re.test(command || ""));
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function bashSafe(command) {
|
|
304
|
+
const trimmed = (command || "").trim();
|
|
305
|
+
return SAFE_COMMAND.some((re) => re.test(trimmed));
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// ---------------------------------------------------------------- WSL
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Which shell a bash call should run through (pure, testable):
|
|
312
|
+
* sh - posix host
|
|
313
|
+
* wsl - Windows host with WSL installed (Linux tooling lives here)
|
|
314
|
+
* cmd-install-wsl - Windows host without WSL, but the command IS the WSL
|
|
315
|
+
* installer: executes on the host itself (approval-gated
|
|
316
|
+
* like every install), then the cache is re-probed
|
|
317
|
+
* wsl-missing - Windows host without WSL: refuse cheaply and hand back
|
|
318
|
+
* the install hint instead of running degraded cmd.exe
|
|
319
|
+
* shells (where nmap, gcc and every offensive tool are
|
|
320
|
+
* absent anyway).
|
|
321
|
+
*/
|
|
322
|
+
function resolveShell(command, opts = {}) {
|
|
323
|
+
const platform = opts.platform || process.platform;
|
|
324
|
+
if (platform !== "win32") return { mode: "sh" };
|
|
325
|
+
const wslPresent = opts.wsl === undefined ? detectWSL() : Boolean(opts.wsl);
|
|
326
|
+
if (wslPresent) return { mode: "wsl" };
|
|
327
|
+
if (bootstrap.isWSLInstallCommand(command)) return { mode: "cmd-install-wsl", installCmd: String(command).trim() };
|
|
328
|
+
return { mode: "wsl-missing", needsInstall: { tool: "wsl", installCmd: bootstrap.WSL_DEFAULT_INSTALL_CMD } };
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// ---------------------------------------------------------------- WSL
|
|
332
|
+
|
|
333
|
+
// Cached WSL probe. win32 only: runs `wsl.exe --status` once and remembers
|
|
334
|
+
// the answer. opts.platform / opts.exec exist so tests can fake the OS
|
|
335
|
+
// without spawning processes. Never throws.
|
|
336
|
+
let _wslCache;
|
|
337
|
+
function resetWSLCache() {
|
|
338
|
+
_wslCache = undefined;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function detectWSL(opts = {}) {
|
|
342
|
+
const platform = opts.platform || process.platform;
|
|
343
|
+
if (platform !== "win32") return false;
|
|
344
|
+
if (_wslCache !== undefined && !opts.platform && !opts.exec) return _wslCache;
|
|
345
|
+
let available = false;
|
|
346
|
+
try {
|
|
347
|
+
if (opts.exec) {
|
|
348
|
+
opts.exec();
|
|
349
|
+
available = true;
|
|
350
|
+
} else {
|
|
351
|
+
const { execSync } = require("node:child_process");
|
|
352
|
+
execSync("wsl.exe --status", { stdio: "ignore", timeout: 5000, windowsHide: true });
|
|
353
|
+
available = true;
|
|
354
|
+
}
|
|
355
|
+
} catch {
|
|
356
|
+
available = false;
|
|
357
|
+
}
|
|
358
|
+
if (!opts.platform && !opts.exec) _wslCache = available;
|
|
359
|
+
return available;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// Translate a Windows path (C:\foo\bar or C:/foo/bar) to its WSL mount
|
|
363
|
+
// (/mnt/c/foo/bar). POSIX paths pass through with backslashes fixed.
|
|
364
|
+
function toWSLPath(winPath) {
|
|
365
|
+
if (typeof winPath !== "string" || !winPath) return winPath;
|
|
366
|
+
const slashy = winPath.replace(/\\/g, "/");
|
|
367
|
+
const drive = slashy.match(/^([A-Za-z]):\/(.*)$/);
|
|
368
|
+
if (drive) return `/mnt/${drive[1].toLowerCase()}/${drive[2]}`;
|
|
369
|
+
const bare = slashy.match(/^([A-Za-z]):(.*)$/);
|
|
370
|
+
if (bare) {
|
|
371
|
+
const rest = String(bare[2] || "").replace(/^\//, "");
|
|
372
|
+
return `/mnt/${bare[1].toLowerCase()}/${rest}`;
|
|
373
|
+
}
|
|
374
|
+
return slashy;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function quoteWSL(s) {
|
|
378
|
+
return `'${String(s).replace(/'/g, `'\\''`)}'`;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// Attach a needsInstall hint when bash output signals a missing binary
|
|
382
|
+
// that we know how to install. Installer strings already passed the
|
|
383
|
+
// BLOCKED_COMMAND guard before they are attached. Inside WSL the guest is
|
|
384
|
+
// Linux, so the hint uses apt even though the host is Windows.
|
|
385
|
+
function attachInstallHint(command, detail, viaWSL) {
|
|
386
|
+
const suggestion = bootstrap.parseMissingTool(command, detail, viaWSL ? "apt" : undefined);
|
|
387
|
+
if (!suggestion) return null;
|
|
388
|
+
if (bashBlocked(suggestion.installCmd)) return null;
|
|
389
|
+
return suggestion;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
function runBash(root, command, workdir) {
|
|
393
|
+
const base = workdir ? resolveInRoot(root, workdir) : { ok: true, path: root };
|
|
394
|
+
if (!base.ok) return Promise.resolve({ ok: false, summary: "refused", detail: base.error });
|
|
395
|
+
const shell = resolveShell(command);
|
|
396
|
+
const useWSL = shell.mode === "wsl";
|
|
397
|
+
// Windows host without WSL: do not degrade to cmd.exe silently - Linux
|
|
398
|
+
// tooling (and everything the platform is for) lives in WSL there. Hand
|
|
399
|
+
// back the install hint so the agent proposes the installer, which runs
|
|
400
|
+
// through the ordinary approval gate ("terminal asks first"). The install
|
|
401
|
+
// command itself escapes this branch, executes on the host, and resets the
|
|
402
|
+
// cached probe so later calls route through WSL once it exists.
|
|
403
|
+
if (shell.mode === "wsl-missing") {
|
|
404
|
+
return Promise.resolve({
|
|
405
|
+
ok: false,
|
|
406
|
+
summary: "WSL missing",
|
|
407
|
+
detail: `WSL is not installed on this Windows machine, so Linux tooling (nmap, gcc, the works) is unavailable. To enable it, emit {"tool": "bash", "command": ${JSON.stringify(shell.needsInstall.installCmd)}} and ask the operator first - installing WSL needs explicit approval, elevated privileges, and one restart of the machine.`,
|
|
408
|
+
needsInstall: shell.needsInstall,
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
// Pre-flight: the agent proposed a known tool that is not installed.
|
|
412
|
+
// Return the install hint without spawning a doomed shell. Skipped when
|
|
413
|
+
// routing via WSL: host PATH says nothing about the Linux guest, so let
|
|
414
|
+
// the WSL shell itself report the miss and hint at an apt install.
|
|
415
|
+
const preTool = bootstrap.extractToolFromCommand(command);
|
|
416
|
+
if (preTool && !useWSL) {
|
|
417
|
+
const found = bootstrap.findEntry(preTool);
|
|
418
|
+
if (found && !bootstrap.isAvailable(preTool)) {
|
|
419
|
+
const suggestion = bootstrap.suggestInstall(preTool);
|
|
420
|
+
if (suggestion && !bashBlocked(suggestion.installCmd)) {
|
|
421
|
+
return Promise.resolve({
|
|
422
|
+
ok: false,
|
|
423
|
+
summary: "tool missing",
|
|
424
|
+
detail: `Command "${preTool}" was not found on this machine. Propose "${suggestion.installCmd}" to install it (needs operator approval).`,
|
|
425
|
+
needsInstall: suggestion,
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
return new Promise((resolve) => {
|
|
431
|
+
let file;
|
|
432
|
+
let args;
|
|
433
|
+
if (useWSL) {
|
|
434
|
+
const linuxCwd = toWSLPath(base.path);
|
|
435
|
+
const wrapped = `cd ${quoteWSL(linuxCwd)} && ${command}`;
|
|
436
|
+
file = "wsl.exe";
|
|
437
|
+
args = ["-e", "sh", "-c", wrapped];
|
|
438
|
+
} else {
|
|
439
|
+
file = process.platform === "win32" ? "cmd.exe" : "sh";
|
|
440
|
+
args = process.platform === "win32" ? ["/d", "/s", "/c", command] : ["-c", command];
|
|
441
|
+
}
|
|
442
|
+
const child = execFile(file, args, {
|
|
443
|
+
cwd: base.path,
|
|
444
|
+
timeout: BASH_TIMEOUT_MS,
|
|
445
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
446
|
+
windowsHide: true,
|
|
447
|
+
});
|
|
448
|
+
let out = "";
|
|
449
|
+
let errOut = "";
|
|
450
|
+
if (child.stdout) child.stdout.on("data", (c) => { out += c; });
|
|
451
|
+
if (child.stderr) child.stderr.on("data", (c) => { errOut += c; });
|
|
452
|
+
child.on("error", (error) => resolve({ ok: false, summary: "failed to start", detail: truncate(error.message) }));
|
|
453
|
+
child.on("close", (code, signal) => {
|
|
454
|
+
// A just-finished WSL install invalidates the cached probe: from the
|
|
455
|
+
// next call the shell routes through WSL instead of cmd.exe.
|
|
456
|
+
if (code === 0 && shell.mode === "cmd-install-wsl") resetWSLCache();
|
|
457
|
+
const combined = (out + (errOut ? `\n[stderr]\n${errOut}` : "")).trim();
|
|
458
|
+
if (code === 0) return resolve({ ok: true, summary: useWSL ? "exit 0 [via WSL]" : "exit 0", detail: truncate(combined) || "(no output)" });
|
|
459
|
+
const detail = truncate(combined) || "(no output)";
|
|
460
|
+
const needsInstall = attachInstallHint(command, detail, useWSL);
|
|
461
|
+
const result = { ok: false, summary: signal ? `killed (${signal})` : `exit ${code}`, detail };
|
|
462
|
+
if (needsInstall) result.needsInstall = needsInstall;
|
|
463
|
+
return resolve(result);
|
|
464
|
+
});
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* Approval policy. Reads, searches and `ask` run free; writes, edits and
|
|
470
|
+
* shell commands ask unless the operator allowed the tool for the session,
|
|
471
|
+
* allowed it always (persisted in ~/.bolt/permissions.json), or passed
|
|
472
|
+
* --allow-all. Without an asker (piped output, --print) mutations are denied
|
|
473
|
+
* rather than guessed — the model is told so and works around it.
|
|
474
|
+
*
|
|
475
|
+
* Asker decisions: "allow" (once), "session" (rest of this session),
|
|
476
|
+
* "always" (persisted across sessions), anything else denies.
|
|
477
|
+
*/
|
|
478
|
+
async function checkApproval(call, ctx) {
|
|
479
|
+
const context = ctx || {};
|
|
480
|
+
if (call.tool === "read" || call.tool === "glob" || call.tool === "grep" || call.tool === "list") return { allowed: true };
|
|
481
|
+
if (call.tool === "ask") {
|
|
482
|
+
const norm = normalizeAskCall(call);
|
|
483
|
+
if (!norm.ok) return { allowed: false, reason: `bad ask block: ${norm.error}` };
|
|
484
|
+
return { allowed: true };
|
|
485
|
+
}
|
|
486
|
+
if (call.tool === "bash" && bashBlocked(call.command)) {
|
|
487
|
+
return { allowed: false, reason: "refused: destructive command (no approval path)" };
|
|
488
|
+
}
|
|
489
|
+
// Persistent "always" approvals (per tool-key) survive restarts.
|
|
490
|
+
try {
|
|
491
|
+
const permissions = require("./permissions");
|
|
492
|
+
const store = context.alwaysStore || context.permissions || null;
|
|
493
|
+
if (store && permissions.isAlwaysAllowed(store, call)) return { allowed: true };
|
|
494
|
+
} catch {
|
|
495
|
+
// A corrupt store never blocks the loop.
|
|
496
|
+
}
|
|
497
|
+
// Installer commands always need an explicit yes - never silent, never
|
|
498
|
+
// covered by --allow-all or a session-wide approval.
|
|
499
|
+
if (call.tool === "bash" && bootstrap.isInstallCommand(call.command)) {
|
|
500
|
+
if (typeof context.ask !== "function") {
|
|
501
|
+
return { allowed: false, reason: "denied: installs need explicit approval (non-interactive session)" };
|
|
502
|
+
}
|
|
503
|
+
const decision = await context.ask(call);
|
|
504
|
+
if (decision === "allow") return { allowed: true };
|
|
505
|
+
persistAlwaysDecision(context, call, decision);
|
|
506
|
+
return { allowed: false, reason: "denied by operator" };
|
|
507
|
+
}
|
|
508
|
+
if (context.allowAll) return { allowed: true };
|
|
509
|
+
if (context.sessionAllowed && context.sessionAllowed.has(call.tool)) return { allowed: true };
|
|
510
|
+
if (call.tool === "bash" && bashSafe(call.command)) return { allowed: true };
|
|
511
|
+
if (typeof context.ask !== "function") {
|
|
512
|
+
return { allowed: false, reason: "denied: non-interactive session cannot approve mutations" };
|
|
513
|
+
}
|
|
514
|
+
const decision = await context.ask(call);
|
|
515
|
+
if ((decision === "session" || decision === "always") && context.sessionAllowed) context.sessionAllowed.add(call.tool);
|
|
516
|
+
persistAlwaysDecision(context, call, decision);
|
|
517
|
+
if (decision === "allow" || decision === "session" || decision === "always") return { allowed: true };
|
|
518
|
+
return { allowed: false, reason: "denied by operator" };
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// Persists an "always" decision to ~/.bolt/permissions.json via the ctx's
|
|
522
|
+
// saver (or directly). Failures are silent: persistence is convenience.
|
|
523
|
+
function persistAlwaysDecision(ctx, call, decision) {
|
|
524
|
+
if (decision !== "always") return;
|
|
525
|
+
try {
|
|
526
|
+
const permissions = require("./permissions");
|
|
527
|
+
if (typeof ctx.persistAlways === "function") {
|
|
528
|
+
ctx.persistAlways(call);
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
if (ctx.alwaysStore) {
|
|
532
|
+
const next = permissions.allowAlways(ctx.alwaysStore, call);
|
|
533
|
+
ctx.alwaysStore.always = next.always;
|
|
534
|
+
permissions.save(next);
|
|
535
|
+
}
|
|
536
|
+
} catch {
|
|
537
|
+
// ignore
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
function listDir(root, input) {
|
|
542
|
+
const target = input ? resolveInRoot(root, input) : { ok: true, path: root };
|
|
543
|
+
if (!target.ok) return { ok: false, summary: "refused", detail: target.error };
|
|
544
|
+
let entries;
|
|
545
|
+
try {
|
|
546
|
+
entries = fs.readdirSync(target.path, { withFileTypes: true });
|
|
547
|
+
} catch {
|
|
548
|
+
return { ok: false, summary: "cannot list", detail: `Cannot list ${input || "."}.` };
|
|
549
|
+
}
|
|
550
|
+
const lines = entries
|
|
551
|
+
.filter((e) => !e.name.startsWith(".") || e.name === ".env.example")
|
|
552
|
+
.slice(0, 200)
|
|
553
|
+
.map((e) => (e.isDirectory() ? `${e.name}/` : e.name));
|
|
554
|
+
return { ok: true, summary: `${lines.length} entries`, detail: lines.join("\n") || "(empty)" };
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
async function executeCall(call, ctx) {
|
|
558
|
+
const root = ctx.root || process.cwd();
|
|
559
|
+
switch (call.tool) {
|
|
560
|
+
case "read": {
|
|
561
|
+
if (!call.path) return { ok: false, summary: "missing path", detail: "read needs a path." };
|
|
562
|
+
// Reads are not sandboxed: they change nothing. Every call is still
|
|
563
|
+
// printed, so exfiltration-by-reading happens in the open.
|
|
564
|
+
return readFile(path.resolve(root, call.path), call.offset, call.limit);
|
|
565
|
+
}
|
|
566
|
+
case "glob":
|
|
567
|
+
return globFiles(root, call.pattern);
|
|
568
|
+
case "grep":
|
|
569
|
+
return grepFiles(root, call.pattern, call.path);
|
|
570
|
+
case "list":
|
|
571
|
+
return listDir(root, call.path);
|
|
572
|
+
case "write":
|
|
573
|
+
return writeFile(root, call.path, call.content);
|
|
574
|
+
case "edit":
|
|
575
|
+
return applyEdit(root, call.path, call.oldString, call.newString);
|
|
576
|
+
case "bash":
|
|
577
|
+
return runBash(root, call.command, call.workdir);
|
|
578
|
+
case "ask":
|
|
579
|
+
// `ask` never executes here - the agent loop intercepts it and prompts
|
|
580
|
+
// the operator with a dropdown. Reaching this means non-interactive use.
|
|
581
|
+
return { ok: false, summary: "cannot ask", detail: "ask needs an interactive terminal; pick a default and continue." };
|
|
582
|
+
default:
|
|
583
|
+
return { ok: false, summary: "unknown tool", detail: `Unknown tool "${call.tool}".` };
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
module.exports = {
|
|
588
|
+
TOOL_NAMES,
|
|
589
|
+
MAX_TOOL_BLOCKS,
|
|
590
|
+
parseToolBlocks,
|
|
591
|
+
describeCall,
|
|
592
|
+
normalizeAskCall,
|
|
593
|
+
resolveInRoot,
|
|
594
|
+
resolveMentions,
|
|
595
|
+
bashBlocked,
|
|
596
|
+
bashSafe,
|
|
597
|
+
detectWSL,
|
|
598
|
+
resetWSLCache,
|
|
599
|
+
resolveShell,
|
|
600
|
+
toWSLPath,
|
|
601
|
+
checkApproval,
|
|
602
|
+
executeCall,
|
|
603
|
+
listDir,
|
|
604
|
+
runBash,
|
|
605
|
+
truncate,
|
|
606
|
+
};
|