@bolt-cli/cli 0.0.0-stage → 0.12.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 +350 -0
- package/lib/api.js +243 -0
- package/lib/bootstrap.js +292 -0
- package/lib/browser.js +136 -0
- package/lib/cancel.js +153 -0
- package/lib/checkpoints.js +67 -0
- package/lib/cli.js +2536 -0
- package/lib/completion.js +77 -0
- package/lib/config.js +59 -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/tools.js +624 -0
- package/lib/ui.js +749 -0
- package/lib/watch.js +698 -0
- package/package.json +39 -6
- package/templates/README.md +44 -0
- package/templates/aslr-offset-probe.sh +96 -0
- package/templates/crash-offset-pattern.sh +81 -0
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Shell completions for bolt. Static word lists only — no subprocesses,
|
|
3
|
+
// no filesystem access. Emitted to stdout so callers can redirect:
|
|
4
|
+
// bolt completion bash >> ~/.bashrc
|
|
5
|
+
const COMMANDS = ["run", "build", "login", "signin", "auth", "balance", "session", "doctor", "completion", "export", "undo", "help"];
|
|
6
|
+
const FLAGS = [
|
|
7
|
+
"--target", "-t", "--mode", "-m", "--agent", "--tools", "--dry-run", "--allow-all",
|
|
8
|
+
"--max-iters", "-p", "--print", "--file", "-f", "--evidence", "--session", "-s",
|
|
9
|
+
"--continue", "-c", "--title", "--out", "-o", "--format", "--output", "--budget",
|
|
10
|
+
"--url", "--no-browser", "--help", "-h",
|
|
11
|
+
];
|
|
12
|
+
const AGENTS = ["sweep", "probe", "build", "plan", "validate", "triage"];
|
|
13
|
+
const MODES = ["offensive", "defensive"];
|
|
14
|
+
const FORMATS = ["text", "json", "md"];
|
|
15
|
+
|
|
16
|
+
function bash() {
|
|
17
|
+
return `# bolt bash completion — add with: bolt completion bash >> ~/.bashrc
|
|
18
|
+
_bolt_complete() {
|
|
19
|
+
local cur prev cmds
|
|
20
|
+
cmds="${COMMANDS.join(" ")}"
|
|
21
|
+
if [[ $COMP_CWORD -eq 1 ]]; then COMPREPLY=($(compgen -W "$cmds" -- "$cur")); return; fi
|
|
22
|
+
prev="\${COMP_WORDS[COMP_CWORD-1]}"; cur="\${COMP_WORDS[COMP_CWORD]}"
|
|
23
|
+
case "$prev" in
|
|
24
|
+
--agent) COMPREPLY=($(compgen -W "${AGENTS.join(" ")}" -- "$cur")); return;;
|
|
25
|
+
--mode|-m) COMPREPLY=($(compgen -W "${MODES.join(" ")}" -- "$cur")); return;;
|
|
26
|
+
--format) COMPREPLY=($(compgen -W "${FORMATS.join(" ")}" -- "$cur")); return;;
|
|
27
|
+
run|build|-p|--print) COMPREPLY=($(compgen -W "${FLAGS.join(" ")}" -- "$cur")); return;;
|
|
28
|
+
esac
|
|
29
|
+
COMPREPLY=($(compgen -W "${FLAGS.join(" ")}" -- "$cur"));
|
|
30
|
+
}
|
|
31
|
+
complete -F _bolt_complete bolt
|
|
32
|
+
`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function zsh() {
|
|
36
|
+
return `# bolt zsh completion — add with: bolt completion zsh >> ~/.zshrc
|
|
37
|
+
#compdef bolt
|
|
38
|
+
_bolt() {
|
|
39
|
+
local -a cmds=( ${COMMANDS.map((c) => `'${c}'`).join(" ")} )
|
|
40
|
+
_arguments -C '1:command:->cmd' '*:option:->opt'
|
|
41
|
+
case $state in
|
|
42
|
+
cmd) _describe 'command' cmds ;;
|
|
43
|
+
opt) _values 'option' ${FLAGS.map((f) => `'${f}'`).join(" ")} ;;
|
|
44
|
+
esac
|
|
45
|
+
}
|
|
46
|
+
compdef _bolt bolt
|
|
47
|
+
`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function fish() {
|
|
51
|
+
const cmds = COMMANDS.map((c) => `complete -c bolt -n '__fish_use_subcommand' -f -a ${c}`).join("\n");
|
|
52
|
+
const flags = FLAGS.map((f) => `complete -c bolt -f -l ${f.replace(/^-+/, "")}`).join("\n");
|
|
53
|
+
return `# bolt fish completion — add with: bolt completion fish > ~/.config/fish/completions/bolt.fish\n${cmds}\n${flags}\n`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function powershell() {
|
|
57
|
+
return `# bolt PowerShell completion — add with: bolt completion powershell >> $PROFILE
|
|
58
|
+
Register-ArgumentCompleter -Native -CommandName bolt -ScriptBlock {
|
|
59
|
+
param($wordToComplete, $commandAst, $cursorPosition)
|
|
60
|
+
$cmds = @(${COMMANDS.map((c) => `'${c}'`).join(", ")})
|
|
61
|
+
$cmds | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object {
|
|
62
|
+
[System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
`;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function completion(shell) {
|
|
69
|
+
const s = String(shell || "").toLowerCase();
|
|
70
|
+
if (s === "bash") return bash();
|
|
71
|
+
if (s === "zsh") return zsh();
|
|
72
|
+
if (s === "fish") return fish();
|
|
73
|
+
if (s === "powershell" || s === "pwsh") return powershell();
|
|
74
|
+
throw new Error(`Unknown shell "${shell}". Use: bash | zsh | fish | powershell.`);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
module.exports = { completion, COMMANDS, FLAGS };
|
package/lib/config.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Config + auth storage: ~/.bolt/config.json { url, token, expiresAt, email }
|
|
3
|
+
// First run talks to production (Bolt's own subdomain; same deployment as the
|
|
4
|
+
// apex); local dev and self-hosted backends opt in explicitly with --url or
|
|
5
|
+
// BOLT_URL (or a previous signin, which is saved). The email is shown in the
|
|
6
|
+
// welcome card and injected into prompts as Terminal context so "which
|
|
7
|
+
// account is this session" is answerable without any tool call.
|
|
8
|
+
const PRODUCTION_URL = "https://bolt.beerasafe.com";
|
|
9
|
+
const fs = require("fs");
|
|
10
|
+
const os = require("os");
|
|
11
|
+
const path = require("path");
|
|
12
|
+
|
|
13
|
+
function dir() {
|
|
14
|
+
return path.join(os.homedir(), ".bolt");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function file() {
|
|
18
|
+
return path.join(dir(), "config.json");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function load() {
|
|
22
|
+
try {
|
|
23
|
+
const raw = fs.readFileSync(file(), "utf8");
|
|
24
|
+
const cfg = JSON.parse(raw);
|
|
25
|
+
return {
|
|
26
|
+
url: (cfg.url || process.env.BOLT_URL || PRODUCTION_URL).replace(/\/$/, ""),
|
|
27
|
+
token: cfg.token || process.env.BOLT_TOKEN || "",
|
|
28
|
+
expiresAt: cfg.expiresAt || "",
|
|
29
|
+
email: cfg.email || "",
|
|
30
|
+
};
|
|
31
|
+
} catch {
|
|
32
|
+
return {
|
|
33
|
+
url: (process.env.BOLT_URL || PRODUCTION_URL).replace(/\/$/, ""),
|
|
34
|
+
token: process.env.BOLT_TOKEN || "",
|
|
35
|
+
expiresAt: "",
|
|
36
|
+
email: "",
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function save(cfg) {
|
|
42
|
+
fs.mkdirSync(dir(), { recursive: true, mode: 0o700 });
|
|
43
|
+
const data = JSON.stringify(
|
|
44
|
+
{ url: cfg.url, token: cfg.token || "", expiresAt: cfg.expiresAt || "", email: cfg.email || "" },
|
|
45
|
+
null,
|
|
46
|
+
2,
|
|
47
|
+
);
|
|
48
|
+
fs.writeFileSync(file(), data, { mode: 0o600 });
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function clear() {
|
|
52
|
+
try {
|
|
53
|
+
fs.unlinkSync(file());
|
|
54
|
+
} catch {
|
|
55
|
+
// already logged out
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
module.exports = { load, save, clear, file, PRODUCTION_URL };
|
package/lib/doctor.js
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// bolt doctor: pre-flight environment checks with fix hints.
|
|
3
|
+
// Zero deps. Never throws — every check reports {name, ok, detail}.
|
|
4
|
+
// `overrides` exists so tests can fake the environment without touching
|
|
5
|
+
// the real home directory or network.
|
|
6
|
+
const fs = require("fs");
|
|
7
|
+
const os = require("os");
|
|
8
|
+
const path = require("path");
|
|
9
|
+
|
|
10
|
+
function checkNode() {
|
|
11
|
+
const major = Number.parseInt(process.versions.node.split(".")[0], 10);
|
|
12
|
+
const ok = Number.isFinite(major) && major >= 18;
|
|
13
|
+
return { name: "node", ok, detail: ok ? `node ${process.versions.node} (>= 18)` : `node ${process.versions.node} is too old — install Node 18+` };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function checkConfig(home = os.homedir()) {
|
|
17
|
+
const file = path.join(home, ".bolt", "config.json");
|
|
18
|
+
try {
|
|
19
|
+
const raw = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
20
|
+
if (raw && raw.token) return { name: "auth", ok: true, detail: `signed in (${raw.url || "saved backend"})` };
|
|
21
|
+
return { name: "auth", ok: false, detail: "no token saved — run: bolt login" };
|
|
22
|
+
} catch {
|
|
23
|
+
return { name: "auth", ok: false, detail: "not signed in — run: bolt login" };
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function checkPermissions(home = os.homedir()) {
|
|
28
|
+
const file = path.join(home, ".bolt", "permissions.json");
|
|
29
|
+
try {
|
|
30
|
+
fs.accessSync(file, fs.constants.R_OK);
|
|
31
|
+
return { name: "permissions", ok: true, detail: "always-allow store readable" };
|
|
32
|
+
} catch {
|
|
33
|
+
return { name: "permissions", ok: true, detail: "no always-allow store yet (first approval creates it)" };
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function checkClipboard(platform = process.platform) {
|
|
38
|
+
const known =
|
|
39
|
+
platform === "darwin" || platform === "win32"
|
|
40
|
+
? true
|
|
41
|
+
: (() => {
|
|
42
|
+
for (const dir of ["/usr/bin", "/bin", "/usr/local/bin"]) {
|
|
43
|
+
for (const bin of ["xclip", "xsel", "wl-copy"]) {
|
|
44
|
+
try {
|
|
45
|
+
fs.accessSync(path.join(dir, bin));
|
|
46
|
+
return true;
|
|
47
|
+
} catch {
|
|
48
|
+
// keep looking
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return false;
|
|
53
|
+
})();
|
|
54
|
+
return {
|
|
55
|
+
name: "clipboard",
|
|
56
|
+
ok: true,
|
|
57
|
+
detail: known ? "copy support available (/copy works)" : "no clipboard tool found — /copy will fail (install xclip, xsel, or wl-clipboard)",
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function checkWSL(platform = process.platform, exec) {
|
|
62
|
+
if (platform !== "win32") return { name: "wsl", ok: true, detail: "not Windows — native shell" };
|
|
63
|
+
let available = false;
|
|
64
|
+
try {
|
|
65
|
+
if (exec) {
|
|
66
|
+
exec();
|
|
67
|
+
available = true;
|
|
68
|
+
} else {
|
|
69
|
+
require("node:child_process").execSync("wsl.exe --status", { stdio: "ignore", timeout: 5000, windowsHide: true });
|
|
70
|
+
available = true;
|
|
71
|
+
}
|
|
72
|
+
} catch {
|
|
73
|
+
available = false;
|
|
74
|
+
}
|
|
75
|
+
return {
|
|
76
|
+
name: "wsl",
|
|
77
|
+
ok: true,
|
|
78
|
+
detail: available ? "WSL available — bash runs via Linux guest" : "no WSL — bash runs via cmd.exe (install WSL for nmap/gobuster)",
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function checkBackend(url, timeoutMs = 5000, fetchFn) {
|
|
83
|
+
const target = String(url || "").replace(/\/$/, "");
|
|
84
|
+
if (!target) return { name: "backend", ok: false, detail: "no backend URL — run: bolt login" };
|
|
85
|
+
const run = fetchFn || fetch;
|
|
86
|
+
try {
|
|
87
|
+
const controller = new AbortController();
|
|
88
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
89
|
+
try {
|
|
90
|
+
await run(`${target}/api/auth/providers`, { signal: controller.signal });
|
|
91
|
+
return { name: "backend", ok: true, detail: `reachable at ${target}` };
|
|
92
|
+
} finally {
|
|
93
|
+
clearTimeout(timer);
|
|
94
|
+
}
|
|
95
|
+
} catch {
|
|
96
|
+
return { name: "backend", ok: false, detail: `cannot reach ${target} — for production run: bolt login --url https://bolt.beerasafe.com` };
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function runDoctor({ url, home, platform, exec, fetchFn } = {}) {
|
|
101
|
+
const checks = [checkNode(), checkConfig(home), checkPermissions(home), checkClipboard(platform), checkWSL(platform, exec)];
|
|
102
|
+
checks.push(await checkBackend(url, 5000, fetchFn));
|
|
103
|
+
return checks;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function formatDoctor(checks) {
|
|
107
|
+
return checks.map((c) => `${c.ok ? "ok " : "fail"} ${c.name} — ${c.detail}`).join("\n");
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
module.exports = { runDoctor, formatDoctor, checkNode, checkConfig, checkBackend };
|
package/lib/export.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Session export: markdown for humans, JSON for scripts, SARIF for CI.
|
|
3
|
+
// SARIF output is a minimal valid run (version 2.1.0) so findings can ride
|
|
4
|
+
// the GitHub code-scanning / CI path. Heuristic: response lines mentioning
|
|
5
|
+
// FINDINGS/LOCATION become results; otherwise one informational result per
|
|
6
|
+
// turn keeps the file non-empty and honest.
|
|
7
|
+
const fs = require("fs");
|
|
8
|
+
|
|
9
|
+
function toMarkdown(sess) {
|
|
10
|
+
const lines = [`# bolt session ${sess.id}`, "", `Title: ${sess.title || "untitled"}`, ""];
|
|
11
|
+
(sess.turns || []).forEach((t, i) => {
|
|
12
|
+
lines.push(`## turn ${i + 1} [${t.mode || "offensive"}] ${t.at || ""}`);
|
|
13
|
+
if (t.target) lines.push(`target: ${t.target}`);
|
|
14
|
+
lines.push("", `Q: ${t.prompt || ""}`, "", `${t.response || ""}`, "");
|
|
15
|
+
if (t.tools && t.tools.length) lines.push(`tools: ${t.tools.map((x) => x.tool).join(", ")}`, "");
|
|
16
|
+
});
|
|
17
|
+
return lines.join("\n");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function sarifResults(sess) {
|
|
21
|
+
const results = [];
|
|
22
|
+
(sess.turns || []).forEach((t, i) => {
|
|
23
|
+
const text = String(t.response || "");
|
|
24
|
+
const hits = text.split("\n").filter((l) => /FINDINGS|LOCATION|EVIDENCE/i.test(l)).slice(0, 20);
|
|
25
|
+
if (!hits.length) {
|
|
26
|
+
results.push({
|
|
27
|
+
ruleId: "bolt/note",
|
|
28
|
+
level: "note",
|
|
29
|
+
message: { text: `turn ${i + 1}: no structured findings (see session)` },
|
|
30
|
+
locations: [{ physicalLocation: { artifactLocation: { uri: `session-turn-${i + 1}` } } }],
|
|
31
|
+
});
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
hits.forEach((h) => {
|
|
35
|
+
results.push({
|
|
36
|
+
ruleId: "bolt/finding",
|
|
37
|
+
level: "warning",
|
|
38
|
+
message: { text: h.trim().slice(0, 500) },
|
|
39
|
+
locations: [{ physicalLocation: { artifactLocation: { uri: `session-turn-${i + 1}` } } }],
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
return results;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function toSarif(sess) {
|
|
47
|
+
return JSON.stringify(
|
|
48
|
+
{
|
|
49
|
+
version: "2.1.0",
|
|
50
|
+
$schema: "https://json.schemastore.org/sarif-2.1.0.json",
|
|
51
|
+
runs: [
|
|
52
|
+
{
|
|
53
|
+
tool: { driver: { name: "bolt", version: "1.0", informationUri: "https://bolt.beerasafe.com" } },
|
|
54
|
+
results: sarifResults(sess),
|
|
55
|
+
},
|
|
56
|
+
],
|
|
57
|
+
},
|
|
58
|
+
null,
|
|
59
|
+
2,
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function exportSession(sess, format) {
|
|
64
|
+
const f = String(format || "md").toLowerCase();
|
|
65
|
+
if (f === "json") return JSON.stringify(sess, null, 2);
|
|
66
|
+
if (f === "sarif") return toSarif(sess);
|
|
67
|
+
if (f === "md" || f === "markdown") return toMarkdown(sess);
|
|
68
|
+
throw new Error(`Unknown export format "${format}". Use: md | json | sarif.`);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function writeExport(sess, format, dest) {
|
|
72
|
+
const text = exportSession(sess, format);
|
|
73
|
+
fs.writeFileSync(dest, text + "\n");
|
|
74
|
+
return dest;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
module.exports = { exportSession, writeExport, toMarkdown, toSarif };
|
package/lib/history.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Persistent REPL history: ~/.bolt/history (mode 600).
|
|
3
|
+
//
|
|
4
|
+
// node:readline keeps history in memory only, so every CLI restart used to
|
|
5
|
+
// mean amnesia. This module loads the last N lines on startup (newest-first,
|
|
6
|
+
// matching readline's `history` order) and appends each accepted line.
|
|
7
|
+
// Conventions borrowed from shells: blank lines are skipped, and a line with
|
|
8
|
+
// a leading space is never saved (privacy hatch for pasted secrets).
|
|
9
|
+
// Never throws.
|
|
10
|
+
const fs = require("fs");
|
|
11
|
+
const os = require("os");
|
|
12
|
+
const path = require("path");
|
|
13
|
+
const redact = require("./redact");
|
|
14
|
+
|
|
15
|
+
const MAX_LINES = 500;
|
|
16
|
+
|
|
17
|
+
function file(target) {
|
|
18
|
+
if (target) return target;
|
|
19
|
+
return path.join(os.homedir(), ".bolt", "history");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Returns saved lines newest-first, capped at `limit`. Missing or corrupt
|
|
23
|
+
// files read as empty history.
|
|
24
|
+
function load(target, limit = 100) {
|
|
25
|
+
let raw;
|
|
26
|
+
try {
|
|
27
|
+
raw = fs.readFileSync(file(target), "utf8");
|
|
28
|
+
} catch {
|
|
29
|
+
return [];
|
|
30
|
+
}
|
|
31
|
+
return raw
|
|
32
|
+
.split("\n")
|
|
33
|
+
.map((line) => line.replace(/\r$/, ""))
|
|
34
|
+
.filter((line) => line.trim().length > 0)
|
|
35
|
+
.slice(-limit)
|
|
36
|
+
.reverse();
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Decides whether a raw input line belongs in history. Exported for tests.
|
|
40
|
+
function keepable(line) {
|
|
41
|
+
const s = String(line ?? "");
|
|
42
|
+
if (!s.trim()) return false;
|
|
43
|
+
if (s.startsWith(" ") || s.startsWith("\t")) return false;
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Appends one line and trims the file to MAX_LINES. No-op for unkeepable
|
|
48
|
+
// lines. Returns true when the line was saved.
|
|
49
|
+
//
|
|
50
|
+
// REPL prompts can carry pasted secrets, and the history file is long-lived
|
|
51
|
+
// (synced, backed up, grepped). The line is scrubbed before the write, so
|
|
52
|
+
// recalling it later shows the safe form. Pair with the leading-space hatch
|
|
53
|
+
// (keepable) to keep a line out entirely.
|
|
54
|
+
function append(line, target) {
|
|
55
|
+
if (!keepable(line)) return false;
|
|
56
|
+
const target_ = file(target);
|
|
57
|
+
const clean = redact.redact(String(line).trimEnd()).text;
|
|
58
|
+
if (!clean.trim()) return false;
|
|
59
|
+
try {
|
|
60
|
+
fs.mkdirSync(path.dirname(target_), { recursive: true, mode: 0o700 });
|
|
61
|
+
fs.appendFileSync(target_, `${clean}\n`, { mode: 0o600 });
|
|
62
|
+
} catch {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
try {
|
|
66
|
+
const lines = fs.readFileSync(target_, "utf8").split("\n");
|
|
67
|
+
// Split leaves a trailing "" after the final newline; keep the file to
|
|
68
|
+
// MAX_LINES real lines plus that terminator.
|
|
69
|
+
if (lines.length - 1 > MAX_LINES) {
|
|
70
|
+
fs.writeFileSync(target_, `${lines.slice(lines.length - 1 - MAX_LINES).join("\n")}`, { mode: 0o600 });
|
|
71
|
+
}
|
|
72
|
+
} catch {
|
|
73
|
+
// Trimming is hygiene; the append already landed.
|
|
74
|
+
}
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
module.exports = { MAX_LINES, file, load, keepable, append };
|
package/lib/memory.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Project memory: BOLT.md auto-load.
|
|
3
|
+
//
|
|
4
|
+
// `/init` writes a BOLT.md describing the project, but nothing used to read
|
|
5
|
+
// it back — the agent started every run with amnesia. This module closes the
|
|
6
|
+
// loop: the project BOLT.md (found by walking up from the cwd) plus an
|
|
7
|
+
// optional global ~/.bolt/BOLT.md are loaded once per command/session and
|
|
8
|
+
// appended to the prompt as a memory block. Explicit flags and prompt text
|
|
9
|
+
// always win over memory (it travels as context, not instructions).
|
|
10
|
+
//
|
|
11
|
+
// Zero deps: node:fs, node:os, node:path only. Never throws.
|
|
12
|
+
const fs = require("fs");
|
|
13
|
+
const os = require("os");
|
|
14
|
+
const path = require("path");
|
|
15
|
+
|
|
16
|
+
const PROJECT_FILE = "BOLT.md";
|
|
17
|
+
const MAX_PROJECT_CHARS = 8000;
|
|
18
|
+
const MAX_GLOBAL_CHARS = 4000;
|
|
19
|
+
|
|
20
|
+
// Markers that identify a project root. The walk stops at the first
|
|
21
|
+
// directory containing any of these. Note: ~/.bolt is deliberately NOT a
|
|
22
|
+
// marker — otherwise every unmarked directory under home would resolve to
|
|
23
|
+
// home itself instead of the working directory.
|
|
24
|
+
const ROOT_MARKERS = [".git", "package.json", "pyproject.toml", "go.mod", "Cargo.toml", "Cargo.lock", "pom.xml", "Gemfile", PROJECT_FILE];
|
|
25
|
+
|
|
26
|
+
function findProjectRoot(startDir) {
|
|
27
|
+
const start = path.resolve(startDir || process.cwd());
|
|
28
|
+
let dir = start;
|
|
29
|
+
const home = os.homedir();
|
|
30
|
+
for (;;) {
|
|
31
|
+
for (const marker of ROOT_MARKERS) {
|
|
32
|
+
try {
|
|
33
|
+
fs.accessSync(path.join(dir, marker));
|
|
34
|
+
return dir;
|
|
35
|
+
} catch {
|
|
36
|
+
// not here, keep looking upward
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const parent = path.dirname(dir);
|
|
40
|
+
// No markers anywhere up to the fs root or the home directory: the
|
|
41
|
+
// working directory itself is the project (never claim / or ~).
|
|
42
|
+
if (parent === dir || dir === home) return start;
|
|
43
|
+
dir = parent;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function readCapped(file, max) {
|
|
48
|
+
let content;
|
|
49
|
+
try {
|
|
50
|
+
content = fs.readFileSync(file, "utf8");
|
|
51
|
+
} catch {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
if (!content.trim()) return null;
|
|
55
|
+
const trimmed = content.trim();
|
|
56
|
+
if (trimmed.length <= max) return { text: trimmed, truncated: false };
|
|
57
|
+
return { text: `${trimmed.slice(0, max)}\n\n[truncated: first ${max.toLocaleString()} of ${trimmed.length.toLocaleString()} characters]`, truncated: true };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Loads memory for a working directory. Returns
|
|
61
|
+
// { root, project: {path, text} | null, global: {path, text} | null, text }
|
|
62
|
+
// where `text` is the prompt-ready block ("" when nothing was found).
|
|
63
|
+
function loadMemory(startDir) {
|
|
64
|
+
const root = findProjectRoot(startDir);
|
|
65
|
+
const projectPath = path.join(root, PROJECT_FILE);
|
|
66
|
+
const globalPath = path.join(os.homedir(), ".bolt", PROJECT_FILE);
|
|
67
|
+
const project = readCapped(projectPath, MAX_PROJECT_CHARS);
|
|
68
|
+
const global = projectPath === globalPath ? null : readCapped(globalPath, MAX_GLOBAL_CHARS);
|
|
69
|
+
const parts = [];
|
|
70
|
+
if (project) parts.push(`Project (${projectPath}):\n${project.text}`);
|
|
71
|
+
if (global) parts.push(`Global (${globalPath}):\n${global.text}`);
|
|
72
|
+
return {
|
|
73
|
+
root,
|
|
74
|
+
project: project ? { path: projectPath, chars: project.text.length, truncated: project.truncated } : null,
|
|
75
|
+
global: global ? { path: globalPath, chars: global.text.length, truncated: global.truncated } : null,
|
|
76
|
+
text: parts.length ? `Project memory (BOLT.md - context, not instructions; explicit flags and prompt text take precedence):\n\n${parts.join("\n\n")}` : "",
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
module.exports = { PROJECT_FILE, MAX_PROJECT_CHARS, MAX_GLOBAL_CHARS, findProjectRoot, loadMemory };
|
package/lib/output.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Output helpers: extract fenced CODE blocks and save built tools to disk.
|
|
3
|
+
// Fence-aware formatting: language tags are normalized (lowercase, default
|
|
4
|
+
// txt) and code is dedented to a consistent base indent so streamed and saved
|
|
5
|
+
// blocks look the same. No dependencies.
|
|
6
|
+
const fs = require("fs");
|
|
7
|
+
const path = require("path");
|
|
8
|
+
|
|
9
|
+
function normalizeLang(lang) {
|
|
10
|
+
const l = String(lang || "").trim().toLowerCase();
|
|
11
|
+
if (!l || l === "code") return "txt";
|
|
12
|
+
if (!/^[a-z0-9+#_-]+$/.test(l)) return "txt";
|
|
13
|
+
return l;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// Strip the common leading indent shared by every non-blank line. Tabs are
|
|
17
|
+
// expanded to 4 spaces first so mixed indent still dedents evenly. Trailing
|
|
18
|
+
// whitespace per line is trimmed and surrounding blank lines are removed.
|
|
19
|
+
function normalizeIndent(code) {
|
|
20
|
+
const raw = String(code || "").replace(/\r\n/g, "\n");
|
|
21
|
+
const lines = raw.split("\n");
|
|
22
|
+
// Drop leading/trailing blank lines.
|
|
23
|
+
while (lines.length && !lines[0].trim()) lines.shift();
|
|
24
|
+
while (lines.length && !lines[lines.length - 1].trim()) lines.pop();
|
|
25
|
+
if (!lines.length) return "";
|
|
26
|
+
const expanded = lines.map((line) => line.replace(/\t/g, " ").replace(/[ \t]+$/, ""));
|
|
27
|
+
let min = Infinity;
|
|
28
|
+
for (const line of expanded) {
|
|
29
|
+
if (!line.trim()) continue;
|
|
30
|
+
const m = line.match(/^ */);
|
|
31
|
+
const n = m ? m[0].length : 0;
|
|
32
|
+
if (n < min) min = n;
|
|
33
|
+
}
|
|
34
|
+
if (!Number.isFinite(min)) min = 0;
|
|
35
|
+
return expanded.map((line) => (line.trim() ? line.slice(min) : "")).join("\n");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Render a block for display with a clear fence header. Line numbers are
|
|
39
|
+
// opt-in (default off) so the text stays copy-pasteable. Plain hyphens only.
|
|
40
|
+
function formatCodeBlock(block, { lineNumbers = false } = {}) {
|
|
41
|
+
const lang = normalizeLang(block && block.lang);
|
|
42
|
+
const code = normalizeIndent(block && block.code);
|
|
43
|
+
const name = block && block.filename ? ` - ${block.filename}` : "";
|
|
44
|
+
const header = `\`\`\`${lang}${name}`;
|
|
45
|
+
if (!lineNumbers) return `${header}\n${code}\n\`\`\``;
|
|
46
|
+
const numbered = code.split("\n").map((line, i) => `${String(i + 1).padStart(3, " ")} | ${line}`).join("\n");
|
|
47
|
+
return `${header}\n${numbered}\n\`\`\``;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function extractCodeBlocks(markdown) {
|
|
51
|
+
const blocks = [];
|
|
52
|
+
const fence = /```([^\s`]*)\s*\n([\s\S]*?)```/g;
|
|
53
|
+
let m;
|
|
54
|
+
let i = 0;
|
|
55
|
+
while ((m = fence.exec(markdown)) !== null) {
|
|
56
|
+
i += 1;
|
|
57
|
+
const lang = normalizeLang(m[1]);
|
|
58
|
+
const code = normalizeIndent(m[2]);
|
|
59
|
+
if (!code.trim()) continue;
|
|
60
|
+
const before = markdown.slice(0, m.index).split("\n").filter(Boolean).slice(-3).join(" ");
|
|
61
|
+
const fileHit = (before.match(/([\w.-]+\.(?:nse|lua|py|sh|js|go|rb|yaml|yml))/i) || [])[1];
|
|
62
|
+
const ext = lang === "lua" ? "nse" : lang === "txt" ? "txt" : lang || "txt";
|
|
63
|
+
blocks.push({ lang, filename: fileHit || `script-${i}.${ext}`, code });
|
|
64
|
+
if (blocks.length >= 6) break;
|
|
65
|
+
}
|
|
66
|
+
return blocks;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function saveTools(blocks, outDir) {
|
|
70
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
71
|
+
const saved = [];
|
|
72
|
+
const seen = new Set();
|
|
73
|
+
for (const b of blocks) {
|
|
74
|
+
let name = b.filename;
|
|
75
|
+
let n = 1;
|
|
76
|
+
while (seen.has(name)) {
|
|
77
|
+
n += 1;
|
|
78
|
+
name = b.filename.replace(/(\.[^.]+)?$/, `-${n}$1`);
|
|
79
|
+
}
|
|
80
|
+
seen.add(name);
|
|
81
|
+
const dest = path.join(outDir, name);
|
|
82
|
+
fs.writeFileSync(dest, b.code + "\n");
|
|
83
|
+
saved.push(dest);
|
|
84
|
+
}
|
|
85
|
+
return saved;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
module.exports = { extractCodeBlocks, saveTools, normalizeLang, normalizeIndent, formatCodeBlock };
|