@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
package/LICENSE
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
PROPRIETARY LICENSE
|
|
2
|
+
Copyright (C) 2026 BeeraSafe. All rights reserved.
|
|
3
|
+
|
|
4
|
+
This software and its associated products, including without limitation the
|
|
5
|
+
Bolt and Rampart platforms (collectively, the "Software"), are proprietary and
|
|
6
|
+
confidential works of BeeraSafe.
|
|
7
|
+
|
|
8
|
+
1. NO LICENSE GRANTED
|
|
9
|
+
|
|
10
|
+
Except as expressly stated in a separate written agreement signed by
|
|
11
|
+
BeeraSafe, no rights of any kind are granted to you. The Software is made
|
|
12
|
+
available solely for your internal, non-production evaluation and for running
|
|
13
|
+
the services you operate on BeeraSafe's hosted platform. All rights not
|
|
14
|
+
expressly granted are reserved by BeeraSafe.
|
|
15
|
+
|
|
16
|
+
2. RESTRICTIONS
|
|
17
|
+
|
|
18
|
+
You may not, and may not permit any third party to:
|
|
19
|
+
|
|
20
|
+
a. copy, reproduce, duplicate, mirror, or otherwise redistribute the
|
|
21
|
+
Software, in whole or in part, in any form;
|
|
22
|
+
b. modify, adapt, translate, reverse engineer, decompile, or disassemble
|
|
23
|
+
the Software, or attempt to derive its source code;
|
|
24
|
+
c. create derivative works based on the Software;
|
|
25
|
+
d. sell, rent, lease, sublicense, lend, or otherwise transfer the Software
|
|
26
|
+
or any right in it, to any person or entity;
|
|
27
|
+
e. use the Software to build, operate, market, or offer a competing
|
|
28
|
+
product, service, or platform;
|
|
29
|
+
f. claim, represent, or hold out the Software, or any portion of it, as
|
|
30
|
+
your own work, product, trade secret, or intellectual property;
|
|
31
|
+
g. remove, obscure, or alter any copyright, trademark, or other proprietary
|
|
32
|
+
notice included in or with the Software;
|
|
33
|
+
h. use the Software in violation of any applicable law or regulation.
|
|
34
|
+
|
|
35
|
+
3. OWNERSHIP
|
|
36
|
+
|
|
37
|
+
The Software, including all copies, modifications, and derivative works
|
|
38
|
+
thereof, is and shall remain the sole and exclusive property of BeeraSafe.
|
|
39
|
+
This license does not transfer to you any title or ownership interest in the
|
|
40
|
+
Software or in any intellectual property it embodies.
|
|
41
|
+
|
|
42
|
+
4. TRADEMARKS
|
|
43
|
+
|
|
44
|
+
"BeeraSafe", "Bolt", "Rampart", and related names, logos, and service marks
|
|
45
|
+
are trademarks of BeeraSafe and may not be used, reproduced, or imitated
|
|
46
|
+
without BeeraSafe's prior written permission, including in connection with any
|
|
47
|
+
product, service, or claim that implies affiliation with or endorsement by
|
|
48
|
+
BeeraSafe.
|
|
49
|
+
|
|
50
|
+
5. NO WARRANTY
|
|
51
|
+
|
|
52
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
53
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
54
|
+
FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT. THE ENTIRE RISK AS TO
|
|
55
|
+
THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU.
|
|
56
|
+
|
|
57
|
+
6. LIMITATION OF LIABILITY
|
|
58
|
+
|
|
59
|
+
IN NO EVENT SHALL BEERASAFE BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER
|
|
60
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM,
|
|
61
|
+
OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OF OR OTHER DEALINGS IN
|
|
62
|
+
THE SOFTWARE.
|
|
63
|
+
|
|
64
|
+
7. TERMINATION
|
|
65
|
+
|
|
66
|
+
This license is effective until terminated. It will terminate automatically
|
|
67
|
+
without notice if you breach any of its terms. Upon termination you must cease
|
|
68
|
+
all use of the Software and destroy all copies in your possession. Sections 3,
|
|
69
|
+
4, 5, 6, and 8 survive termination.
|
|
70
|
+
|
|
71
|
+
8. GOVERNING LAW
|
|
72
|
+
|
|
73
|
+
This license shall be governed by and construed in accordance with the laws
|
|
74
|
+
applicable to BeeraSafe's principal place of business, without regard to its
|
|
75
|
+
conflict-of-law provisions.
|
package/README.md
CHANGED
|
@@ -1,3 +1,156 @@
|
|
|
1
|
-
#
|
|
1
|
+
# bolt CLI
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Authorized testing + tool-building from your terminal or VS Code integrated terminal. Zero dependencies, Node 18+. Single backend (Bolt) only: no providers, no model picker — every run bills your token balance like the workspace.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install -g @bolt-cli/cli
|
|
9
|
+
bolt --help
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
From this repo (contributors — `./cli` is the CLI folder in the repo root):
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install -g ./cli
|
|
16
|
+
bolt --help
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Or without installing:
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
npx @bolt-cli/cli run "get admin endpoints on subdomains of tesla.com" --target tesla.com
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
VS Code: open the integrated terminal (`Ctrl+``) and use the same commands. No extension needed.
|
|
26
|
+
|
|
27
|
+
## Auth (once)
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
bolt signin
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
That is the whole flow: `bolt login` (or `bolt signin`, same thing) shows a short code like `WDJB-MJHT` and opens your browser, you enter the code and approve there, and the terminal picks up its token by itself. No password is ever typed into the shell. Already signed in on the web? The browser opens with the code prefilled — one approval and the terminal is done.
|
|
34
|
+
|
|
35
|
+
If the browser is on another machine (SSH session), add `--no-browser`: it prints the link and code instead of opening anything, so you approve wherever your browser lives. No port forwarding is ever needed.
|
|
36
|
+
|
|
37
|
+
`--no-browser` prints the link and code instead of opening them. First run talks to production with zero configuration; `bolt signin --url <app>` (or `BOLT_URL`) only for local dev or self-hosted, otherwise it defaults to your last login.
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
bolt auth status
|
|
41
|
+
bolt auth logout
|
|
42
|
+
bolt balance
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
How the hand-off works, and why it is safe to run on a shared machine:
|
|
46
|
+
|
|
47
|
+
- The terminal shows a short code and polls for approval — nothing listens on your machine, so there is no local port to attack.
|
|
48
|
+
- Your browser lands on a code-entry page showing which account is approving. Nothing is granted until you approve.
|
|
49
|
+
- Approving mints exactly one token for the polling terminal: the grant is consumed atomically, so a second approval or a replayed poll cannot double-mint.
|
|
50
|
+
- The code expires after 10 minutes and works once.
|
|
51
|
+
|
|
52
|
+
Stores a long-lived token at `~/.bolt/config.json` (mode 600). The server mints it at `POST /api/cli/device/token` once the browser approves; send it back as `Authorization: Bearer`. Env overrides: `BOLT_URL`, `BOLT_TOKEN`.
|
|
53
|
+
|
|
54
|
+
There is no password path: a typed password is shell history and visible in the process list, so `bolt signin` is the only sign-in. On a headless machine, add `--no-browser` and open the printed URL yourself (see the port-forwarding note above).
|
|
55
|
+
|
|
56
|
+
## Use Bolt to build tools
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
# Single autonomous run: AI chains subdomain + HTTP checks itself
|
|
60
|
+
bolt run "get admin endpoints on subdomains of tesla.com" --target tesla.com
|
|
61
|
+
|
|
62
|
+
# Build mode: extracts fenced CODE blocks and saves each file
|
|
63
|
+
bolt build "nmap NSE script to detect exposed admin logins" --target tesla.com --out ./bolt-out
|
|
64
|
+
|
|
65
|
+
# Defensive
|
|
66
|
+
bolt run "triage this alert: impossible-travel sign-in" --mode defensive --evidence ./alert.json
|
|
67
|
+
|
|
68
|
+
# Agent loop on a one-shot run: the model reads, searches, edits and runs shell
|
|
69
|
+
bolt run "refactor src/auth.ts to use the new session store" --tools
|
|
70
|
+
|
|
71
|
+
# Print mode: headless agent run, final answer only (mutations denied unless --allow-all)
|
|
72
|
+
bolt -p "what does this repo do?"
|
|
73
|
+
|
|
74
|
+
# Machine-readable output for CI: JSON on stdout, answer saved to a file
|
|
75
|
+
bolt run "get admin endpoints" --target tesla.com --format json --output out.json
|
|
76
|
+
|
|
77
|
+
# Refuse before spending when the prompt is bigger than N input tokens
|
|
78
|
+
bolt run "triage this dump" --mode defensive -f big.log --budget 8000
|
|
79
|
+
|
|
80
|
+
# Dry run: show what would be sent (tokens, files, memory) — spends nothing,
|
|
81
|
+
# touches no network, needs no login
|
|
82
|
+
bolt run "get admin endpoints on subdomains of tesla.com" --target tesla.com --tools --dry-run
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
`bolt build` saves `*.nse`, `*.py`, `*.sh`, etc. into `--out` (default `./bolt-out`) so you can run them from your own Kali/WSL. Bolt does read-only checks server-side; it writes scripts, you execute them.
|
|
86
|
+
|
|
87
|
+
## Health, completions, export, undo
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
bolt doctor # node, auth, backend, WSL, clipboard
|
|
91
|
+
bolt completion bash >> ~/.bashrc # bash|zsh|fish|powershell
|
|
92
|
+
bolt export <id> --format sarif --output findings.sarif # md|json|sarif
|
|
93
|
+
bolt undo src/auth.ts # restore last agent backup of a file
|
|
94
|
+
bolt help run # per-command help
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Every `write`/`edit` is backed up under `~/.bolt/backups/` (last 10 per file) before it lands. `sarif` export is GitHub code-scanning compatible for CI.
|
|
98
|
+
|
|
99
|
+
Press **Esc** during any run to stop it — the session is saved, no need to kill the terminal. Running out of tokens stops the run at once with your balance and the top-up link; it never spins forever.
|
|
100
|
+
|
|
101
|
+
Colors and glyphs follow your terminal: full color on a TTY, plain text on pipes and CI so logs and `--format json > file` stay parseable. Git Bash, Windows Terminal, and VS Code are detected even without a TTY. Override either way with `FORCE_COLOR=1|2|3` (force on) or `NO_COLOR=1` (force off).
|
|
102
|
+
|
|
103
|
+
## Interactive mode (opencode-style)
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
bolt
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Bare `bolt` opens an interactive agent on the Bolt backend only — no providers, no model picker. It reads, lists, and searches your project freely, and asks before editing files or running shell commands. Type `/` then Enter to browse commands: arrow keys pick where the terminal supports them, otherwise every row has a number — type it to run, `/text` to narrow, anything else to cancel. Tab completes, and `@path` attaches a file inline (Tab completes paths). `/agents` lists task agents, `/agent <name>` arms one for the next prompt, `/init` explores the project and writes `BOLT.md`, `/resume` picks a saved session back up, `/sessions` lists them in a picker with ages, `/retry` re-runs the last prompt, `/export` saves the session (`md|json|sarif`), `/undo <path>` restores a file, `/doctor` runs pre-flight checks, `/tools` toggles local tools, `/allow-all` skips every approval, `/permissions` manages always-allowed tools, `/status` shows the session dashboard, `?` (or `/keys`) shows the keyboard cheat sheet, and `/help <cmd>` explains one command. Also: `/help`, `/models`, `/mode`, `/target`, `/file`, `/clear`, `/session`, `/copy`, `/balance`, `/exit`.
|
|
110
|
+
|
|
111
|
+
Prompt history persists across restarts at `~/.bolt/history` (a leading space keeps a line out of the file — handy for pasted secrets). End a line with `\` to continue a long task on the next line. Answers render as terminal markdown (headings, bold, code, quotes, lists), and every tool call reports its elapsed time. When the model needs you to decide, it opens a dropdown; the last row is always "Type a custom answer…" so free text stays possible.
|
|
112
|
+
|
|
113
|
+
## Project memory (BOLT.md)
|
|
114
|
+
|
|
115
|
+
`/init` writes a `BOLT.md` describing the project — and every run after that actually reads it back. The CLI walks up from your working directory to the project root (`.git`, `package.json`, …) and loads `./BOLT.md` plus an optional global `~/.bolt/BOLT.md` as context on every turn. Explicit flags and prompt text always take precedence over memory. `/init` refreshes it mid-session, no restart needed.
|
|
116
|
+
|
|
117
|
+
## Tools & permissions
|
|
118
|
+
|
|
119
|
+
The agent loop works like Claude Code: the model requests local tools, the terminal executes them, results feed the next turn (up to 8 iterations, `--max-iters N` to change that).
|
|
120
|
+
|
|
121
|
+
| tool | what it does | approval |
|
|
122
|
+
|---|---|---|
|
|
123
|
+
| `read` | read any file | never asked |
|
|
124
|
+
| `list` | list a directory | never asked |
|
|
125
|
+
| `glob` | find files (`src/**/*.ts`) | never asked |
|
|
126
|
+
| `grep` | search contents (regex) | never asked |
|
|
127
|
+
| `write` | create/overwrite a file | asked (once or for the session) |
|
|
128
|
+
| `edit` | exact-match replacement | asked (once or for the session) |
|
|
129
|
+
| `bash` | shell command (120s cap) | asked, unless read-only (`git status`, `ls`, …) |
|
|
130
|
+
|
|
131
|
+
Two hard rules, no overrides: writes, edits and the shell stay inside the directory you started `bolt` in (`../` escapes refused), and destructive commands (`mkfs`, `dd` to devices, fork bombs, shutdown, `chmod -R 777 /`, …) are refused outright. Raw tool JSON never litters the transcript — calls render as status lines. Without a TTY (`-p`, pipes) mutations are denied unless you pass `--allow-all`, which approves everything without asking.
|
|
132
|
+
|
|
133
|
+
Secrets never leave the machine by accident: likely secrets (AWS keys, GitHub/Slack tokens, private keys, `password = "…"` assignments in configs) are scrubbed from prompts and tool results before sending — the terminal tells you how many it redacted, and the model is told not to ask for them back.
|
|
134
|
+
|
|
135
|
+
Scrubbed at rest, too, so sessions stay safe to sync, back up, and paste into support tickets: session files (`~/.bolt/sessions/`) store the redacted form of prompts, responses, and titles, and `session show` prints the count per turn. REPL history (`~/.bolt/history`) stores the scrubbed line as well. All Bolt state (config, sessions, history, permissions) is mode 600 under mode-700 directories.
|
|
136
|
+
|
|
137
|
+
One thing scrubbing cannot fix: `bolt run "…"` with a secret typed inline is visible in shell history and the process list before anything runs. The CLI warns when argv looks like it contains a secret — pipe via stdin or use `--file` / `@-mentions` to keep it out of both.
|
|
138
|
+
|
|
139
|
+
## Sessions
|
|
140
|
+
|
|
141
|
+
```bash
|
|
142
|
+
bolt run "..." --title "tesla admin hunt" # named session
|
|
143
|
+
bolt run "..." -c # continue latest
|
|
144
|
+
bolt run "..." -s <id> # continue one session
|
|
145
|
+
bolt session list | show <id> | delete <id> | new
|
|
146
|
+
bolt export <id> --format sarif --output findings.sarif # md|json|sarif
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
`--file` is repeatable (`-f a.eml -f b.log`); `--evidence` is an alias. Context from the last 6 turns travels with each continued run.
|
|
150
|
+
|
|
151
|
+
## Uninstall / logout
|
|
152
|
+
|
|
153
|
+
```bash
|
|
154
|
+
bolt auth logout
|
|
155
|
+
npm uninstall -g @bolt-cli/cli
|
|
156
|
+
```
|
package/bin/bolt.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
// bolt — terminal CLI for Bolt authorized testing.
|
|
4
|
+
// Zero dependencies: Node 18+ built-ins only.
|
|
5
|
+
const path = require("path");
|
|
6
|
+
|
|
7
|
+
async function main() {
|
|
8
|
+
const { run } = require(path.join(__dirname, "..", "lib", "cli.js"));
|
|
9
|
+
await run(process.argv.slice(2));
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
main().catch((err) => {
|
|
13
|
+
const message = err && err.message ? err.message : String(err);
|
|
14
|
+
try {
|
|
15
|
+
const ui = require(path.join(__dirname, "..", "lib", "ui.js"));
|
|
16
|
+
ui.err(`bolt: ${message}`);
|
|
17
|
+
} catch {
|
|
18
|
+
console.error(`bolt: ${message}`);
|
|
19
|
+
}
|
|
20
|
+
process.exit(1);
|
|
21
|
+
});
|
package/lib/agent.js
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// The agent loop: multi-turn tool use in the style of Claude Code / opencode.
|
|
3
|
+
//
|
|
4
|
+
// The Bolt backend is a text-in/text-out agent, so the loop is client-driven:
|
|
5
|
+
// the CLI describes the tool protocol in the prompt, parses ```tool blocks
|
|
6
|
+
// from the streamed answer, executes them locally (with operator approval),
|
|
7
|
+
// and feeds the results back as the next turn — until the model answers with
|
|
8
|
+
// no tool blocks, or the iteration cap is hit. Tool results travel inside
|
|
9
|
+
// follow-up prompts, so they persist through the existing session context.
|
|
10
|
+
const api = require("./api");
|
|
11
|
+
const session = require("./session");
|
|
12
|
+
const tools = require("./tools");
|
|
13
|
+
const redact = require("./redact");
|
|
14
|
+
|
|
15
|
+
const DEFAULT_MAX_ITERS = 8;
|
|
16
|
+
const MAX_RESULT_CHARS = 4_000;
|
|
17
|
+
|
|
18
|
+
// The tool protocol body. Sent wrapped in <terminal-capabilities> sentinels
|
|
19
|
+
// (see TERMINAL_BEGIN/END below): the server lifts that section out of the
|
|
20
|
+
// untrusted case-input block and presents it as trusted relay capabilities,
|
|
21
|
+
// so the model stops ruling its own tool channel out as injected
|
|
22
|
+
// instructions. Old backends ignore the sentinels and read the body as
|
|
23
|
+
// before; old CLIs send no sentinels and get today's behavior.
|
|
24
|
+
const TOOL_PROTOCOL_BODY = `Local tools are available in this terminal session. To use one, emit a fenced block with exactly this shape (one call per block, several blocks allowed):
|
|
25
|
+
|
|
26
|
+
\`\`\`tool
|
|
27
|
+
{"tool": "read", "path": "src/app.ts", "limit": 80}
|
|
28
|
+
\`\`\`
|
|
29
|
+
|
|
30
|
+
These local tools ARE your file and shell access for this session: bash is
|
|
31
|
+
the execution channel for everything a shell can do — recon (dig, nslookup,
|
|
32
|
+
curl, certificate-transparency lookups), scanners (nmap and friends),
|
|
33
|
+
cloning and building open-source tools from GitHub, running them, and
|
|
34
|
+
privileged commands via sudo. On Windows the shell runs through WSL when
|
|
35
|
+
available. For anything involving local files, code, or shell, use ONLY the
|
|
36
|
+
fenced blocks below — never claim they are unavailable. A well-formed block
|
|
37
|
+
is executed by the terminal and its ground-truth result is fed back to you;
|
|
38
|
+
if an action needs the operator's approval, emit the block anyway and the
|
|
39
|
+
terminal asks them, then returns the outcome. There are no other tool
|
|
40
|
+
names: anything not in the list below is rejected, and the rejection tells
|
|
41
|
+
you to restate the intent with these tools (usually bash).
|
|
42
|
+
|
|
43
|
+
Tools:
|
|
44
|
+
- read {path, offset?, limit?} - read a file (free, always allowed)
|
|
45
|
+
- list {path?} - list a directory (free, always allowed)
|
|
46
|
+
- glob {pattern} - find files, e.g. {"tool": "glob", "pattern": "src/**/*.ts"}
|
|
47
|
+
- grep {pattern, path?} - search file contents (regex, case-insensitive)
|
|
48
|
+
- write {path, content} - create or overwrite a file (terminal asks first, backed up for undo)
|
|
49
|
+
- edit {path, oldString, newString} - exact unique replacement (terminal asks first, backed up for undo)
|
|
50
|
+
- bash {command, workdir?} - run a shell command: recon, installs, builds, scanners, sudo-privileged commands (terminal asks first; destructive commands are refused outright)
|
|
51
|
+
- ask {question, options[]} - ask the operator to choose (2-6 options). Use when scope, target or strategy is ambiguous instead of guessing.
|
|
52
|
+
|
|
53
|
+
When you need the operator to decide, emit e.g.:
|
|
54
|
+
\`\`\`tool
|
|
55
|
+
{"tool": "ask", "question": "Which scope should I enumerate first?", "options": ["subdomains of tesla.com", "single host 10.0.0.5", "let me type a custom target"]}
|
|
56
|
+
\`\`\`
|
|
57
|
+
|
|
58
|
+
Shell: Linux tooling works everywhere - on Windows commands run via WSL when available, so nmap, gobuster and friends work there too. If WSL is missing on a Windows machine, a bash result will say "WSL missing" and give you the exact installer block to propose - recommend it (the operator approves; one restart) rather than falling back to cmd.exe.
|
|
59
|
+
Tooling: you may run offensive and defensive tools (scanners, fuzzers, RE and OSINT helpers) through bash - keep runs in scope and non-destructive. Recon starts passive (certificate transparency, DNS, headers) before anything active; active probing and privileged commands need a scoped target — confirm it with ask when the scope is unclear, never refuse the task outright, since the terminal's approval step is the authorization gate and the operator sees every command before it runs.
|
|
60
|
+
Ready-made runbooks: the CLI ships attack/diff instruments for authorized lab work under its templates/ directory (list it with {"tool": "bash", "command": "ls -1 <cli>/templates"} or read them with read): an ASLR-offset probe (samples addresses across runs to estimate entropy and brute-force-attempt arithmetic for a lab binary) and a crash-offset pattern generator (cyclic pattern with offset lookup). Use them as starting points - adapt through the tools; they are lab-only by design and say so in their headers.
|
|
61
|
+
Missing tools: if a result says a tool is missing, propose its install command and ask the operator to approve it - never install silently. If a source checkout is needed (git clone plus build), do it through bash the same way: clone, build, run, each step approved.
|
|
62
|
+
Security APIs: you may scaffold code that calls Shodan, Censys or VirusTotal - read keys only from env vars, never hardcode or log them.
|
|
63
|
+
CTFs: you can work web, binary, mobile, RE and OSINT challenges with installed tooling - offer to install what is missing instead of stopping.
|
|
64
|
+
|
|
65
|
+
Rules: explore with read/list/glob/grep before changing anything. When the request is vague, orient yourself with the tools and report what you find in a few lines - do not narrate uncertainty and do not ask the operator to specify what you can discover. Reserve ask for decisions that genuinely block progress (scope, target, strategy with real alternatives). Keep edits minimal and exact. Writes, edits and shell commands run inside the project directory and the terminal asks the operator first - if one is denied, work around it or explain what to run by hand. Every write/edit is backed up first (bolt undo <path> restores). After tool results come back, continue the task; when finished, answer normally with no tool blocks. Never invent tool results. Never claim the local tools are unavailable: results labelled TOOL_RESULTS prove the channel works.`;
|
|
66
|
+
|
|
67
|
+
// Sentinel envelope for the protocol body. The server strips this section
|
|
68
|
+
// out of the untrusted case input and re-attaches it as trusted relay
|
|
69
|
+
// capabilities (see splitTerminalCapabilities in src/lib/ai/ai.ts).
|
|
70
|
+
const TERMINAL_BEGIN = "<terminal-capabilities>";
|
|
71
|
+
const TERMINAL_END = "</terminal-capabilities>";
|
|
72
|
+
const TOOL_PROTOCOL = `${TERMINAL_BEGIN}\n${TOOL_PROTOCOL_BODY}\n${TERMINAL_END}`;
|
|
73
|
+
|
|
74
|
+
function truncateResult(text, max = MAX_RESULT_CHARS) {
|
|
75
|
+
const s = String(text ?? "");
|
|
76
|
+
return s.length > max ? `${s.slice(0, max)}\n…(truncated, ${s.length} chars total)` : s;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Token efficiency for multi-iteration runs, two rules that always hold:
|
|
80
|
+
//
|
|
81
|
+
// 1. Big results are summed, not truncated cold: keep the head (where most
|
|
82
|
+
// tool output's signal lives) and the tail (where compilers and scanners
|
|
83
|
+
// put the verdict), elide the middle. A 4,000-char cap that cuts the tail
|
|
84
|
+
// lost the summary line of every long build.
|
|
85
|
+
// 2. Byte-identical repeats collapse: in a long loop (recon query re-run,
|
|
86
|
+
// the same file read twice) the model already has the full result on the
|
|
87
|
+
// thread - a second copy only burns tokens. "seenDetails" carries the
|
|
88
|
+
// already-delivered set across iterations of one run.
|
|
89
|
+
function summarizeDetail(detail, seenDetails = null) {
|
|
90
|
+
let s = String(detail ?? "");
|
|
91
|
+
if (s.length > 2000) {
|
|
92
|
+
s = `${s.slice(0, 1500)}\n…[middle elided, ${s.length - 1800} chars]…\n${s.slice(-300)}`;
|
|
93
|
+
}
|
|
94
|
+
if (seenDetails) {
|
|
95
|
+
if (seenDetails.has(s)) {
|
|
96
|
+
return `${s.split("\n")[0] || "(result)"}\n…(byte-identical result already delivered this run - read it from the earlier turn; re-run the tool with narrower arguments if you need fresh output)`;
|
|
97
|
+
}
|
|
98
|
+
seenDetails.add(s);
|
|
99
|
+
}
|
|
100
|
+
return s;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function buildAgentPrompt({ target, objective, evidence, history, memory, session, account }) {
|
|
104
|
+
return `${api.buildPrompt({ target, objective, evidence, history, memory, session, account })}\n\n${TOOL_PROTOCOL}`;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function buildFollowup({ iteration, calls, results, errors = [], seenDetails = null }) {
|
|
108
|
+
const lines = [`TOOL_RESULTS for iteration ${iteration} (ground truth from this terminal - do not invent, continue the task):`];
|
|
109
|
+
for (let i = 0; i < calls.length; i += 1) {
|
|
110
|
+
const call = calls[i];
|
|
111
|
+
const result = results[i] || { ok: false, summary: "no result", detail: "" };
|
|
112
|
+
const status = result.ok ? "OK" : `FAILED (${result.summary || "error"})`;
|
|
113
|
+
lines.push(`- ${tools.describeCall(call)} -> ${status}:\n${summarizeDetail(result.detail, seenDetails)}`);
|
|
114
|
+
if (result && result.needsInstall) {
|
|
115
|
+
const n = result.needsInstall;
|
|
116
|
+
lines.push(` Missing tool "${n.tool}". To install, emit {"tool": "bash", "command": ${JSON.stringify(n.installCmd)}} and ask the operator first - installs need explicit approval, never install silently.`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
// Rejected blocks are fed back, not swallowed: without this the model
|
|
120
|
+
// repeats unknown tool names, concludes the channel is broken, and refuses
|
|
121
|
+
// work the terminal could have done. Every rejection restates the fix —
|
|
122
|
+
// translate the intent into the eight tools above (recon via bash).
|
|
123
|
+
for (const error of errors) {
|
|
124
|
+
lines.push(`- BLOCK REJECTED (${error.error || "bad block"}): ${truncateResult(error.raw || "", 200)}`);
|
|
125
|
+
}
|
|
126
|
+
if (errors.length) {
|
|
127
|
+
lines.push("Those blocks named tools that do not exist here. Restate each intent with the eight tools above — DNS, HTTP, subdomain, and port work all go through bash (dig, nslookup, curl, nmap), never a bespoke tool name — then continue the task.");
|
|
128
|
+
}
|
|
129
|
+
lines.push("Continue with the next step, using more tools if needed, or give the final answer with no tool blocks.");
|
|
130
|
+
// Restated every turn on purpose: without it the model reverts to refusing
|
|
131
|
+
// local work it already performed. These results prove the channel works.
|
|
132
|
+
lines.push("Local terminal tools (read, list, glob, grep, write, edit, bash, ask via ```tool blocks) remain available this turn - files, shell, recon, installs, and privileged commands through bash, with operator approval where needed. Never claim the local tools are unavailable.");
|
|
133
|
+
return lines.join("\n");
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Scrub likely secrets from an outbound prompt. Returns { prompt, redactions }.
|
|
137
|
+
// The model is told when scrubbing happened so it never asks for the secrets
|
|
138
|
+
// back; the caller surfaces the count to the operator via a `redacted` event.
|
|
139
|
+
function scrubOutbound(prompt) {
|
|
140
|
+
const r = redact.redact(prompt);
|
|
141
|
+
if (!r.count) return { prompt: r.text, redactions: 0 };
|
|
142
|
+
return {
|
|
143
|
+
prompt: `${r.text}\n\n(Note: ${r.count} possible secret${r.count === 1 ? " was" : "s were"} redacted from this context before sending. Do not ask for secrets; work around them.)`,
|
|
144
|
+
redactions: r.count,
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Runs the loop. `stream` is {begin,write,end,elapsed} (or null when silent).
|
|
150
|
+
* `events` receives {type:"call",call,approved}, {type:"result",call,result}
|
|
151
|
+
* and {type:"ask",call,options} / {type:"answer",call,answer} so the caller
|
|
152
|
+
* can render tool activity and dropdown questions. `policy` is
|
|
153
|
+
* {allowAll, sessionAllowed:Set, ask, askQuestion, alwaysStore, persistAlways}
|
|
154
|
+
* (see tools.checkApproval). `signal` aborts the in-flight generation
|
|
155
|
+
* (Esc/Ctrl-C via lib/cancel.js). Resolves {text, done, iters, toolCalls,
|
|
156
|
+
* cancelled}.
|
|
157
|
+
*/
|
|
158
|
+
async function runAgentLoop({ cfg, objective, mode, target, evidence, sess, stream, events, policy, maxIters = DEFAULT_MAX_ITERS, memory = "", signal, session: sessionId, account }) {
|
|
159
|
+
const emit = (event) => {
|
|
160
|
+
try {
|
|
161
|
+
if (typeof events === "function") events(event);
|
|
162
|
+
} catch {
|
|
163
|
+
// Rendering must never break the loop.
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
const scrub = (text) => {
|
|
167
|
+
const r = scrubOutbound(text);
|
|
168
|
+
if (r.redactions > 0) emit({ type: "redacted", count: r.redactions });
|
|
169
|
+
return r.prompt;
|
|
170
|
+
};
|
|
171
|
+
const ctx = () => ({ session: sessionId || (sess ? sess.id : ""), account: account || (cfg && cfg.email) || "" });
|
|
172
|
+
let prompt = scrub(buildAgentPrompt({ target, objective, evidence, history: sess ? session.contextBlock(sess) : "", memory, ...ctx() }));
|
|
173
|
+
let text = "";
|
|
174
|
+
let done = null;
|
|
175
|
+
let iters = 0;
|
|
176
|
+
let cancelled = false;
|
|
177
|
+
const toolCalls = [];
|
|
178
|
+
// Byte-identical tool results across the run collapse to a pointer line
|
|
179
|
+
// instead of repeating in full (see summarizeDetail). Bounded: only results
|
|
180
|
+
// are tracked, keyed by content, cleared when the run ends.
|
|
181
|
+
const seenDetails = new Set();
|
|
182
|
+
const askPolicy = {
|
|
183
|
+
allowAll: Boolean(policy && policy.allowAll),
|
|
184
|
+
sessionAllowed: (policy && policy.sessionAllowed) || new Set(),
|
|
185
|
+
ask: policy ? policy.ask : null,
|
|
186
|
+
askQuestion: policy ? policy.askQuestion : null,
|
|
187
|
+
alwaysStore: policy ? policy.alwaysStore || policy.permissions || null : null,
|
|
188
|
+
persistAlways: policy ? policy.persistAlways : null,
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
while (iters < maxIters) {
|
|
192
|
+
if (signal && signal.aborted) {
|
|
193
|
+
cancelled = true;
|
|
194
|
+
break;
|
|
195
|
+
}
|
|
196
|
+
iters += 1;
|
|
197
|
+
if (stream) stream.begin();
|
|
198
|
+
const collected = [];
|
|
199
|
+
let turn;
|
|
200
|
+
try {
|
|
201
|
+
turn = await api.streamGenerate({
|
|
202
|
+
url: cfg.url,
|
|
203
|
+
token: cfg.token,
|
|
204
|
+
prompt,
|
|
205
|
+
mode,
|
|
206
|
+
onToken: (token) => {
|
|
207
|
+
collected.push(token);
|
|
208
|
+
if (stream) stream.write(token);
|
|
209
|
+
},
|
|
210
|
+
signal,
|
|
211
|
+
});
|
|
212
|
+
} catch (error) {
|
|
213
|
+
if (stream) {
|
|
214
|
+
try {
|
|
215
|
+
if (typeof stream.cancel === "function") stream.cancel();
|
|
216
|
+
else stream.end();
|
|
217
|
+
} catch {
|
|
218
|
+
// Teardown must never mask the original error.
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
if (error && (error.code === "CANCELLED" || (signal && signal.aborted))) {
|
|
222
|
+
cancelled = true;
|
|
223
|
+
text = collected.join("");
|
|
224
|
+
break;
|
|
225
|
+
}
|
|
226
|
+
throw error;
|
|
227
|
+
}
|
|
228
|
+
if (stream) stream.end();
|
|
229
|
+
text = collected.join("");
|
|
230
|
+
done = turn.done;
|
|
231
|
+
|
|
232
|
+
const { calls, errors } = tools.parseToolBlocks(text);
|
|
233
|
+
const results = [];
|
|
234
|
+
for (const call of calls) {
|
|
235
|
+
// `ask` is a question for the operator, not a machine call: it never
|
|
236
|
+
// needs approval, it opens a dropdown and feeds the answer back.
|
|
237
|
+
if (call.tool === "ask") {
|
|
238
|
+
const norm = tools.normalizeAskCall(call);
|
|
239
|
+
if (!norm.ok) {
|
|
240
|
+
const bad = { ok: false, summary: "bad ask", detail: norm.error };
|
|
241
|
+
results.push(bad);
|
|
242
|
+
toolCalls.push({ tool: "ask", ok: false, summary: norm.error });
|
|
243
|
+
emit({ type: "result", call, result: bad });
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
emit({ type: "ask", call, question: norm.question, options: norm.options });
|
|
247
|
+
let answer = "";
|
|
248
|
+
if (typeof askPolicy.askQuestion === "function") {
|
|
249
|
+
try {
|
|
250
|
+
answer = await askPolicy.askQuestion({ question: norm.question, options: norm.options, allowCustom: norm.allowCustom });
|
|
251
|
+
} catch {
|
|
252
|
+
answer = "";
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
if (!answer) {
|
|
256
|
+
const failed = { ok: false, summary: "no answer", detail: "The operator did not answer. Continue with your best guess or explain what you need." };
|
|
257
|
+
results.push(failed);
|
|
258
|
+
toolCalls.push({ tool: "ask", ok: false, summary: "no answer" });
|
|
259
|
+
emit({ type: "result", call, result: failed });
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
const answered = { ok: true, summary: `answered: ${answer}`, detail: `Operator chose: ${answer}\nQuestion was: ${norm.question}` };
|
|
263
|
+
results.push(answered);
|
|
264
|
+
toolCalls.push({ tool: "ask", ok: true, summary: answer });
|
|
265
|
+
emit({ type: "answer", call, answer });
|
|
266
|
+
emit({ type: "result", call, result: answered });
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
const approval = await tools.checkApproval(call, askPolicy);
|
|
270
|
+
emit({ type: "call", call, approved: approval.allowed, reason: approval.reason || "" });
|
|
271
|
+
let result;
|
|
272
|
+
if (!approval.allowed) {
|
|
273
|
+
result = { ok: false, summary: "not approved", detail: approval.reason || "The operator did not approve this call." };
|
|
274
|
+
} else {
|
|
275
|
+
try {
|
|
276
|
+
result = await tools.executeCall(call, { root: process.cwd(), allowAll: askPolicy.allowAll, sessionAllowed: askPolicy.sessionAllowed, ask: askPolicy.ask });
|
|
277
|
+
} catch (error) {
|
|
278
|
+
result = { ok: false, summary: "crashed", detail: String((error && error.message) || error) };
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
result.detail = truncateResult(result.detail);
|
|
282
|
+
results.push(result);
|
|
283
|
+
toolCalls.push({ tool: call.tool, path: call.path || "", command: call.command || "", ok: result.ok, summary: result.summary });
|
|
284
|
+
emit({ type: "result", call, result });
|
|
285
|
+
}
|
|
286
|
+
for (const error of errors) {
|
|
287
|
+
toolCalls.push({ tool: "(parse error)", ok: false, summary: error.error });
|
|
288
|
+
emit({ type: "result", call: { tool: "(parse error)" }, result: { ok: false, summary: error.error, detail: error.raw } });
|
|
289
|
+
}
|
|
290
|
+
if (sess) {
|
|
291
|
+
session.appendTurn(sess, {
|
|
292
|
+
prompt: iters === 1 ? objective : `[tool follow-up ${iters}]`,
|
|
293
|
+
response: text,
|
|
294
|
+
mode,
|
|
295
|
+
target,
|
|
296
|
+
tools: calls.map((call, i) => ({ tool: call.tool, ok: results[i] ? results[i].ok : false })),
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
// Rejected blocks still deserve a follow-up turn: the model must see the
|
|
300
|
+
// rejection and restate its intent, or it concludes the channel is broken
|
|
301
|
+
// and refuses work the terminal could have done. maxIters still bounds us.
|
|
302
|
+
if (!calls.length && !errors.length) break;
|
|
303
|
+
|
|
304
|
+
if (signal && signal.aborted) {
|
|
305
|
+
cancelled = true;
|
|
306
|
+
break;
|
|
307
|
+
}
|
|
308
|
+
prompt = scrub(buildFollowup({ iteration: iters, calls, results, errors, seenDetails }));
|
|
309
|
+
}
|
|
310
|
+
return { text, done, iters, toolCalls, cancelled };
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Line filter that hides raw ```tool / ```ask blocks from the visible stream.
|
|
315
|
+
* Tool activity is rendered separately as status cards (see the caller's event
|
|
316
|
+
* handler), so the JSON the model emits for the machine never clutters what
|
|
317
|
+
* the human reads. Unclosed fences are swallowed, never leaked.
|
|
318
|
+
*/
|
|
319
|
+
function toolFenceWriter(write) {
|
|
320
|
+
let buf = "";
|
|
321
|
+
let inFence = false;
|
|
322
|
+
const flushLine = (line) => {
|
|
323
|
+
const trimmed = line.trim();
|
|
324
|
+
if (!inFence && /^```(tool|ask)(\s|$)/.test(trimmed)) {
|
|
325
|
+
inFence = true;
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
if (inFence) {
|
|
329
|
+
if (/^```\s*$/.test(trimmed)) inFence = false;
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
write(`${line}\n`);
|
|
333
|
+
};
|
|
334
|
+
return {
|
|
335
|
+
write(text) {
|
|
336
|
+
if (!text) return;
|
|
337
|
+
buf += text;
|
|
338
|
+
const parts = buf.split("\n");
|
|
339
|
+
buf = parts.pop() ?? "";
|
|
340
|
+
for (const part of parts) flushLine(part);
|
|
341
|
+
},
|
|
342
|
+
end() {
|
|
343
|
+
if (buf) flushLine(buf);
|
|
344
|
+
buf = "";
|
|
345
|
+
inFence = false;
|
|
346
|
+
},
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
module.exports = { TOOL_PROTOCOL, TOOL_PROTOCOL_BODY, TERMINAL_BEGIN, TERMINAL_END, DEFAULT_MAX_ITERS, buildAgentPrompt, buildFollowup, runAgentLoop, truncateResult, summarizeDetail, toolFenceWriter, scrubOutbound };
|