@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.
@@ -0,0 +1,167 @@
1
+ "use strict";
2
+ // Persistent permission store for the bolt agent loop.
3
+ //
4
+ // Claude Code / opencode remember "allow always" decisions across sessions.
5
+ // Session-only approvals live in memory (a Set passed around the loop); this
6
+ // module persists the "always" tier to ~/.bolt/permissions.json so a tool the
7
+ // operator trusts never asks again. File mode 600, same as the auth token.
8
+ //
9
+ // Stored shape: { version: 1, always: { "<tool-key>": true } }
10
+ // Tool keys are stable strings: "bash:git status", "edit", "write", ...
11
+ // Bash keys include the command's first word so `git status` can be always
12
+ // allowed without always allowing every shell command.
13
+ const fs = require("fs");
14
+ const os = require("os");
15
+ const path = require("path");
16
+
17
+ const VERSION = 1;
18
+
19
+ function dir() {
20
+ return path.join(os.homedir(), ".bolt");
21
+ }
22
+
23
+ function file() {
24
+ return path.join(dir(), "permissions.json");
25
+ }
26
+
27
+ // ---------------------------------------------------------------- keys
28
+
29
+ // Stable key for an always-allow entry. Bash is keyed by its first word
30
+ // (after sudo stripping) so "always allow git status" does not mean "always
31
+ // allow rm -rf". Reads/glob/grep never need keys (always free).
32
+ function keyForCall(call) {
33
+ if (!call || typeof call.tool !== "string") return "";
34
+ if (call.tool === "bash") {
35
+ const first = String(call.command || "").trim().split(/\s+/).filter(Boolean)[0] || "";
36
+ const lower = first.toLowerCase();
37
+ if (lower === "sudo") {
38
+ const second = String(call.command || "").trim().split(/\s+/).filter(Boolean)[1] || "";
39
+ return `bash:sudo ${String(second).toLowerCase()}`;
40
+ }
41
+ return `bash:${lower}`;
42
+ }
43
+ return call.tool;
44
+ }
45
+
46
+ // ---------------------------------------------------------------- elevation
47
+
48
+ const ELEVATED_PATTERNS = [
49
+ /^\s*sudo\b/i,
50
+ /^\s*doas\b/i,
51
+ /^\s*runas\b/i,
52
+ /\bapt(-get)?\s+(install|remove|purge|upgrade|dist-upgrade)\b/i,
53
+ /\bapt\s+install\b/i,
54
+ /\bdnf\s+(install|remove|upgrade)\b/i,
55
+ /\byum\s+(install|remove)\b/i,
56
+ /\bbrew\s+(install|uninstall)\b/i,
57
+ /\bchoco\s+(install|uninstall)\b/i,
58
+ /\bscoop\s+(install|uninstall)\b/i,
59
+ /\bpip\s+install\b/i,
60
+ /\bnpm\s+(install\s+-g|uninstall\s+-g|install\s+--global)\b/i,
61
+ /^\s*install\b/i,
62
+ /\bsystemctl\b/i,
63
+ /\bservice\b/i,
64
+ /\bnet\s+(start|stop)\b/i,
65
+ /\bsetx\b/i,
66
+ /\bchmod\s+.*\s+\/etc\b/,
67
+ /\bchown\b.*\s+\//,
68
+ />\s*\/etc\//,
69
+ />\s*\/usr\//,
70
+ /\bmount\b/i,
71
+ /\bumount\b/i,
72
+ /\bmkfs\b/i,
73
+ /\bdd\b[^|;&]*\bof=\/dev\//i,
74
+ /\bnetsh\b/i,
75
+ /\breg\s+(add|delete)\b/i,
76
+ /\btakeown\b/i,
77
+ /\bicacls\b/i,
78
+ ];
79
+
80
+ // True when a bash command needs admin / elevated privileges: an explicit
81
+ // sudo/doas prefix, a system package-manager install, a service command, or
82
+ // a write into a system directory. Used to render the elevated permission
83
+ // card (shield + warning) instead of the plain one.
84
+ function isElevatedCommand(command) {
85
+ const s = String(command || "");
86
+ if (!s.trim()) return false;
87
+ return ELEVATED_PATTERNS.some((re) => re.test(s));
88
+ }
89
+
90
+ function elevationReason(command) {
91
+ const s = String(command || "").trim();
92
+ if (/^\s*(sudo|doas)\b/i.test(s)) return "runs with administrator privileges (sudo)";
93
+ if (/\b(apt(-get)?|dnf|yum)\s+(install|remove|purge|upgrade|dist-upgrade)\b/i.test(s)) return "installs system packages (needs admin)";
94
+ if (/\b(brew|choco|scoop)\s+(install|uninstall)\b/i.test(s)) return "installs software on this machine";
95
+ if (/\b(systemctl|service|net\s+(start|stop)|netsh)\b/i.test(s)) return "controls system services (needs admin)";
96
+ if (/\b(pip\s+install|npm\s+install\s+(-g|--global))\b/i.test(s)) return "installs software globally (may need admin)";
97
+ if (isElevatedCommand(s)) return "needs administrator privileges";
98
+ return "";
99
+ }
100
+
101
+ // ---------------------------------------------------------------- store
102
+
103
+ function load(opts = {}) {
104
+ const target = opts.file || file();
105
+ try {
106
+ const raw = fs.readFileSync(target, "utf8");
107
+ const data = JSON.parse(raw);
108
+ const always = data && typeof data.always === "object" && data.always !== null ? data.always : {};
109
+ const clean = {};
110
+ for (const [k, v] of Object.entries(always)) {
111
+ if (typeof k === "string" && k && v === true) clean[k] = true;
112
+ }
113
+ return { version: VERSION, always: clean };
114
+ } catch {
115
+ return { version: VERSION, always: {} };
116
+ }
117
+ }
118
+
119
+ function save(store, opts = {}) {
120
+ const target = opts.file || file();
121
+ try {
122
+ fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
123
+ fs.writeFileSync(target, JSON.stringify({ version: VERSION, always: store.always || {} }, null, 2), { mode: 0o600 });
124
+ } catch {
125
+ // Permissions are a convenience, never a crash.
126
+ }
127
+ }
128
+
129
+ function isAlwaysAllowed(store, call) {
130
+ const key = keyForCall(call);
131
+ if (!key) return false;
132
+ return Boolean(store && store.always && store.always[key] === true);
133
+ }
134
+
135
+ function allowAlways(store, call) {
136
+ const key = keyForCall(call);
137
+ if (!key) return store;
138
+ const next = { version: VERSION, always: { ...(store.always || {}), [key]: true } };
139
+ return next;
140
+ }
141
+
142
+ function revoke(store, callOrKey) {
143
+ const key = typeof callOrKey === "string" ? callOrKey : keyForCall(callOrKey);
144
+ if (!key || !store.always || !store.always[key]) return store;
145
+ const next = { ...(store.always || {}) };
146
+ delete next[key];
147
+ return { version: VERSION, always: next };
148
+ }
149
+
150
+ function listAlways(store) {
151
+ return Object.keys((store && store.always) || {}).sort();
152
+ }
153
+
154
+ module.exports = {
155
+ VERSION,
156
+ dir,
157
+ file,
158
+ keyForCall,
159
+ isElevatedCommand,
160
+ elevationReason,
161
+ load,
162
+ save,
163
+ isAlwaysAllowed,
164
+ allowAlways,
165
+ revoke,
166
+ listAlways,
167
+ };
package/lib/present.js ADDED
@@ -0,0 +1,181 @@
1
+ "use strict";
2
+ // Presentation helpers that need to know about CLI state (turn counts, session
3
+ // ids, the agent table) as opposed to ui.js, which is state-agnostic.
4
+ const ui = require("./ui");
5
+ const cancel = require("./cancel");
6
+
7
+ // Adapts an SSE token stream to the line-buffered styler in ui.js. The spinner
8
+ // runs until the first real token arrives, then gets out of the way.
9
+ // Lifecycle-safe: end() and cancel() are idempotent, so a run that throws
10
+ // (out of tokens, Esc cancel, network failure) always stops the spinner
11
+ // instead of leaving it ticking over the error message.
12
+ function streamingWriter(sink) {
13
+ const stream = sink || ui.createStream();
14
+ // Honest label: terminals without raw mode never deliver a lone Esc, so
15
+ // promising it there is a lie the spinner repeats for the whole run.
16
+ const spinner = ui.createSpinner(cancel.canWatchKeys() ? "thinking (Esc to stop)" : "thinking");
17
+ let started = false;
18
+ let stopped = false;
19
+
20
+ const stop = (msg) => {
21
+ if (stopped) return;
22
+ stopped = true;
23
+ try {
24
+ spinner.stop(msg);
25
+ } catch {
26
+ // A progress-handle failure must never break run teardown.
27
+ }
28
+ };
29
+
30
+ return {
31
+ stream,
32
+ begin() {
33
+ if (started) return;
34
+ started = true;
35
+ stopped = false;
36
+ spinner.start();
37
+ },
38
+ write(text) {
39
+ if (!text) return;
40
+ if (started) stop();
41
+ stream.write(text);
42
+ },
43
+ end() {
44
+ if (started) stop();
45
+ stream.end();
46
+ },
47
+ cancel() {
48
+ stop();
49
+ stream.end();
50
+ },
51
+ elapsed() {
52
+ return spinner.elapsed();
53
+ },
54
+ };
55
+ }
56
+
57
+ // Footer under the answer: cost, remaining balance, elapsed, turn count.
58
+ function turnFooter({ done, elapsed, turns }) {
59
+ const parts = [];
60
+ if (done && done.tokenCost !== undefined) parts.push(`cost ${ui.c.primary(done.tokenCost)}`);
61
+ if (done && done.remainingTokens !== undefined) parts.push(`balance ${ui.c.primary(done.remainingTokens)}`);
62
+ if (elapsed) parts.push(`${ui.c.muted(`${(elapsed / 1000).toFixed(1)}s`)}`);
63
+ if (turns !== undefined) parts.push(ui.c.muted(`turn ${turns}`));
64
+ if (!parts.length) return "";
65
+ const joined = parts.join(ui.c.muted(` ${ui.GLYPH.dot} `));
66
+ // The leading rule is decoration; piped logs get the facts only.
67
+ return ui.isTTY() ? `${ui.c.border(ui.GLYPH.rule.repeat(6))} ${joined}` : joined;
68
+ }
69
+
70
+ // The prompt doubles as the status line, the way opencode keeps state visible:
71
+ // mode, target, armed agent and attachment count all live here so you never
72
+ // have to remember what you set.
73
+ function promptLine({ sid, mode, target, agent, files, balance, tools }) {
74
+ const bits = [ui.c.primary(ui.c.bold(mode))];
75
+ if (target) bits.push(ui.c.accent(target));
76
+ if (agent) bits.push(`${ui.c.muted("agent")} ${ui.c.accent(ui.c.bold(agent))}`);
77
+ if (files) bits.push(ui.c.muted(`${files} file${files === 1 ? "" : "s"}`));
78
+ if (tools !== undefined) bits.push(tools ? ui.c.success("tools") : ui.c.muted("no-tools"));
79
+ if (balance !== undefined && balance !== null) bits.push(ui.c.muted(`${balance} tok`));
80
+ bits.push(ui.c.muted(sid.slice(0, 6)));
81
+ return `${ui.c.primary(ui.GLYPH.bar)} ${bits.join(ui.c.muted(` ${ui.GLYPH.dot} `))} ${ui.c.primary(ui.GLYPH.caret)} `;
82
+ }
83
+
84
+ // Palette rows for `select()`; label is what gets typed back into the prompt.
85
+ function commandItems(commands) {
86
+ return commands.map(([cmd, desc]) => ({ label: cmd, hint: desc }));
87
+ }
88
+
89
+ function agentItems(agents) {
90
+ return Object.entries(agents).map(([name, a]) => ({
91
+ label: `/agent ${name}`,
92
+ hint: a.desc + (a.needsTarget ? " (needs /target)" : ""),
93
+ }));
94
+ }
95
+
96
+ // Combined slash palette: commands first, then agents. Each row keeps its
97
+ // brief definition in `hint` so the dropdown shows name plus meaning.
98
+ function paletteItems(commands, agents) {
99
+ return commandItems(commands).concat(agentItems(agents));
100
+ }
101
+
102
+ // Live filter-as-you-type: matches the query (with or without a leading
103
+ // slash) against both the command name and its description.
104
+ // Pure and tested - cli.js and ui.selectLive use it for the dropdown.
105
+ function filterPalette(query, commands, agents) {
106
+ const q = String(query || "").trim().replace(/^\//, "").toLowerCase();
107
+ const all = paletteItems(commands, agents);
108
+ if (!q) return all;
109
+ return all.filter((it) => `${it.label} ${it.hint || ""}`.toLowerCase().includes(q));
110
+ }
111
+
112
+ // Grouped help, opencode `?`-overlay style: commands read as four small
113
+ // menus (run, session, safety, system) instead of one flat list. Pure:
114
+ // group membership is by command base, rows keep their COMMANDS text.
115
+ const HELP_GROUPS = [
116
+ ["Run", ["/agents", "/agent", "/mode", "/target", "/file", "/init", "/retry", "/resume"]],
117
+ ["Session", ["/session", "/sessions", "/export", "/undo", "/clear", "/copy", "/balance", "/status"]],
118
+ ["Tools & safety", ["/tools", "/allow-all", "/permissions", "/templates"]],
119
+ ["System", ["/models", "/doctor", "/watch", "/keys", "/help", "/exit"]],
120
+ ];
121
+
122
+ function helpGroups(commands) {
123
+ const byBase = new Map();
124
+ for (const [cmd, desc] of commands || []) {
125
+ const base = String(cmd).split(" ")[0];
126
+ if (!byBase.has(base)) byBase.set(base, [cmd, desc]);
127
+ }
128
+ return HELP_GROUPS.map(([title, bases]) => ({
129
+ title,
130
+ rows: bases.map((b) => byBase.get(b)).filter(Boolean),
131
+ })).filter((g) => g.rows.length);
132
+ }
133
+
134
+ // One-line detail for `/help <cmd>`: the full command shape plus its
135
+ // definition, or "" when nothing matches. Pure.
136
+ function helpDetail(query, commands) {
137
+ const q = String(query || "").trim().toLowerCase().replace(/^\//, "");
138
+ if (!q) return "";
139
+ const hit = (commands || []).find(([cmd]) => String(cmd).split(" ")[0].toLowerCase() === `/${q}` || String(cmd).toLowerCase() === `/${q}`);
140
+ if (!hit) return "";
141
+ return `${ui.c.primary(ui.c.bold(hit[0]))} ${ui.c.muted(hit[1])}`;
142
+ }
143
+
144
+ // Status dashboard rows for the `/status` box: everything about the live
145
+ // session in one glance, opencode status-dialog style. All fields optional;
146
+ // missing values read as "(none)" or are skipped. Pure.
147
+ function statusLines({ sid, mode, target, agent, files, tools, balance, turns, memChars, cwd, backend } = {}) {
148
+ const rows = [];
149
+ if (sid) rows.push(`${ui.c.muted("session")} ${ui.c.primary(sid)}${turns !== undefined ? ` ${ui.c.muted(`${turns} turn${turns === 1 ? "" : "s"}`)}` : ""}`);
150
+ const run = [`${ui.c.muted("mode")} ${ui.c.primary(ui.c.bold(mode || "offensive"))}`];
151
+ run.push(`${ui.c.muted("target")} ${target ? ui.c.accent(target) : "(none)"}`);
152
+ run.push(`${ui.c.muted("agent")} ${agent ? ui.c.accent(ui.c.bold(agent)) : "(none)"}`);
153
+ rows.push(run.join(` ${ui.c.muted(ui.GLYPH.dot)} `));
154
+ const gear = [`${ui.c.muted("tools")} ${tools ? ui.c.success("on") : ui.c.muted("off")}`];
155
+ if (files !== undefined) gear.push(`${ui.c.muted("files")} ${files}`);
156
+ if (memChars) gear.push(`${ui.c.muted("memory")} ${memChars} chars`);
157
+ else if (memChars === 0) gear.push(`${ui.c.muted("memory")} none`);
158
+ rows.push(gear.join(` ${ui.c.muted(ui.GLYPH.dot)} `));
159
+ const acct = [];
160
+ if (balance !== undefined && balance !== null) acct.push(`${ui.c.muted("balance")} ${ui.c.primary(balance)} tok`);
161
+ if (backend) acct.push(`${ui.c.muted("backend")} ${backend}`);
162
+ if (acct.length) rows.push(acct.join(` ${ui.c.muted(ui.GLYPH.dot)} `));
163
+ if (cwd) rows.push(`${ui.c.muted("cwd")} ${cwd}`);
164
+ return rows;
165
+ }
166
+
167
+ // Session picker rows for `/sessions`, opencode session-list style: newest
168
+ // first, title plus turn count plus relative age in the hint, and the live
169
+ // session flagged so resuming it is never a surprise. Pure.
170
+ function sessionRows(sessions, currentId) {
171
+ return (Array.isArray(sessions) ? sessions : []).map((s) => {
172
+ const bits = [s.title || "untitled"];
173
+ bits.push(`${s.turns || 0} turn${s.turns === 1 ? "" : "s"}`);
174
+ const age = ui.relTime(s.updatedAt);
175
+ if (age) bits.push(age);
176
+ if (s.id === currentId) bits.push("current");
177
+ return { label: `/session ${s.id}`, hint: bits.join(" · "), id: s.id };
178
+ });
179
+ }
180
+
181
+ module.exports = { streamingWriter, turnFooter, promptLine, commandItems, agentItems, paletteItems, filterPalette, helpGroups, helpDetail, statusLines, sessionRows };
package/lib/redact.js ADDED
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ // Secret redaction for everything the CLI sends to the Bolt backend.
3
+ //
4
+ // Reads are intentionally un-sandboxed and evidence inlines file contents, so
5
+ // without this a `read .env` (or a pasted config) would ship live secrets to
6
+ // the server, the session file, and the billed context. redact() runs at the
7
+ // two choke points where prompts leave the machine (initial prompt assembly
8
+ // and tool-result follow-ups in lib/agent.js, plus single-shot runs in
9
+ // lib/cli.js) and replaces likely secrets with typed placeholders. Local
10
+ // files (session store, history) keep their bytes; only the wire is scrubbed.
11
+ //
12
+ // Heuristic by design: it errs toward recall over precision on obvious
13
+ // secret shapes, and leaves ordinary prose untouched. Never throws.
14
+ const PATTERNS = [
15
+ { type: "aws-key", re: /\bAKIA[0-9A-Z]{16}\b/g },
16
+ { type: "github-token", re: /\b(ghp_[A-Za-z0-9]{20,}|gho_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/g },
17
+ { type: "slack-token", re: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g },
18
+ { type: "private-key", re: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g },
19
+ // api_key = "value", API_KEY: value, authToken='...' — secrets assigned to
20
+ // key-like names in configs. Quoted values need 8+ chars; bare values need
21
+ // 12+ (so "password: required" prose survives but hunter2hunter2 does not).
22
+ // A bare key name with no separator ("the api key is required") never matches.
23
+ {
24
+ type: "assigned-secret",
25
+ re: /\b(?<name>api[_-]?key|secret|auth[_-]?token|access[_-]?token|client[_-]?secret|db[_-]?pass(?:word)?|password|passwd|pwd)(?<sep>\s*[:=]\s*)(?:"(?<dq>[^"]{8,})"|'(?<sq>[^']{8,})'|(?<bare>\S{12,}))/gi,
26
+ },
27
+ ];
28
+
29
+ // Redacts likely secrets in `text`. Returns { text, count } where count is
30
+ // the number of replacements made.
31
+ function redact(text) {
32
+ let out = String(text ?? "");
33
+ let count = 0;
34
+ for (const { type, re } of PATTERNS) {
35
+ re.lastIndex = 0;
36
+ if (type === "assigned-secret") {
37
+ out = out.replace(re, (...args) => {
38
+ const g = args[args.length - 1];
39
+ count += 1;
40
+ const value =
41
+ g.dq !== undefined ? `"[REDACTED:${type}]"` :
42
+ g.sq !== undefined ? `'[REDACTED:${type}]'` :
43
+ `[REDACTED:${type}]`;
44
+ return `${g.name}${g.sep}${value}`;
45
+ });
46
+ } else {
47
+ out = out.replace(re, () => {
48
+ count += 1;
49
+ return `[REDACTED:${type}]`;
50
+ });
51
+ }
52
+ }
53
+ return { text: out, count };
54
+ }
55
+
56
+ module.exports = { PATTERNS: PATTERNS.map((p) => p.type), redact };
package/lib/session.js ADDED
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ // Local sessions: ~/.bolt/sessions/<id>.json
3
+ // Single backend (Bolt) only: sessions store prompt history so --continue and
4
+ // the REPL can resend context. No providers, no model picker.
5
+ const fs = require("fs");
6
+ const os = require("os");
7
+ const path = require("path");
8
+ const redact = require("./redact");
9
+
10
+ function dir() {
11
+ return path.join(os.homedir(), ".bolt", "sessions");
12
+ }
13
+
14
+ function file(id) {
15
+ if (!/^[A-Za-z0-9_-]{4,64}$/.test(id)) throw new Error(`Bad session id "${id}".`);
16
+ return path.join(dir(), `${id}.json`);
17
+ }
18
+
19
+ function newId() {
20
+ return `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
21
+ }
22
+
23
+ function create(title) {
24
+ fs.mkdirSync(dir(), { recursive: true, mode: 0o700 });
25
+ const now = new Date().toISOString();
26
+ // Titles derive from argv prompts (`bolt run "<prompt>" --title ...`), which
27
+ // live in shell history and the process list - scrub before storing so a
28
+ // pasted secret never lands in the session file, `session list`, or a
29
+ // support bundle.
30
+ const clean = redact.redact(title || "untitled");
31
+ const session = {
32
+ id: newId(),
33
+ title: clean.text.slice(0, 80) || "untitled",
34
+ createdAt: now,
35
+ updatedAt: now,
36
+ turns: [],
37
+ };
38
+ save(session);
39
+ return session;
40
+ }
41
+
42
+ function load(id) {
43
+ try {
44
+ return JSON.parse(fs.readFileSync(file(id), "utf8"));
45
+ } catch {
46
+ return null;
47
+ }
48
+ }
49
+
50
+ function save(session) {
51
+ fs.mkdirSync(dir(), { recursive: true, mode: 0o700 });
52
+ session.updatedAt = new Date().toISOString();
53
+ fs.writeFileSync(file(session.id), JSON.stringify(session, null, 2), { mode: 0o600 });
54
+ return session;
55
+ }
56
+
57
+ function appendTurn(session, turn) {
58
+ // Scrub-at-rest: prompts carry pasted evidence and @-inlined files, and
59
+ // responses can echo them back. Session files get synced, backed up, and
60
+ // pasted into support tickets, and `session show` prints them to terminals
61
+ // (CI logs, screen shares) - so secrets are redacted before the write, not
62
+ // just before the network send. The model already saw the redacted form, so
63
+ // `--continue` context stays consistent. The count rides along so
64
+ // `session show` can prove the scrub happened.
65
+ const cleanPrompt = redact.redact(turn.prompt || "");
66
+ const cleanResponse = redact.redact(turn.response || "");
67
+ const redacted = cleanPrompt.count + cleanResponse.count;
68
+ session.turns.push({
69
+ prompt: cleanPrompt.text.slice(0, 4000),
70
+ response: cleanResponse.text.slice(0, 12000),
71
+ mode: turn.mode || "offensive",
72
+ target: turn.target || "",
73
+ // Tool usage rides along so resumed-context digests can say what a turn
74
+ // actually DID (`bash ok, edit ok, grep failed`) instead of plain prose.
75
+ tools: Array.isArray(turn.tools) ? turn.tools.slice(0, 8).map((t) => ({ tool: t.tool, ok: t.ok })) : [],
76
+ at: new Date().toISOString(),
77
+ redacted,
78
+ });
79
+ if (!session.title || session.title === "untitled") {
80
+ const title = redact.redact(String(turn.prompt || "untitled").replace(/\s+/g, " ").trim()).text;
81
+ session.title = title.slice(0, 80) || "untitled";
82
+ }
83
+ return save(session);
84
+ }
85
+
86
+ function list() {
87
+ let files = [];
88
+ try {
89
+ files = fs.readdirSync(dir()).filter((f) => f.endsWith(".json"));
90
+ } catch {
91
+ return [];
92
+ }
93
+ const sessions = [];
94
+ for (const f of files) {
95
+ try {
96
+ const s = JSON.parse(fs.readFileSync(path.join(dir(), f), "utf8"));
97
+ sessions.push({ id: s.id, title: s.title, turns: (s.turns || []).length, updatedAt: s.updatedAt });
98
+ } catch {
99
+ // skip corrupt entries
100
+ }
101
+ }
102
+ return sessions.sort((a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt)));
103
+ }
104
+
105
+ function latest() {
106
+ const all = list();
107
+ if (!all.length) return null;
108
+ return load(all[0].id);
109
+ }
110
+
111
+ function remove(id) {
112
+ try {
113
+ fs.unlinkSync(file(id));
114
+ return true;
115
+ } catch {
116
+ return false;
117
+ }
118
+ }
119
+
120
+ // Condensed history for the next prompt. Server is stateless, so context
121
+ // travels in the request; capped so it never crowds out the live task.
122
+ //
123
+ // Resumable context: the two most recent turns come through verbatim (up to
124
+ // per-turn caps) because that is where the live work continues; every older
125
+ // turn collapses to one digest line - what it asked, what it did (tools and
126
+ // outcomes), and one line of outcome. A five-iteration agent run resumed in a
127
+ // fresh prompt arrives as five digests plus two full turns instead of ~24k of
128
+ // replayed prose, and the working thread stays intact because the digests
129
+ // carry the decisions that produced the work.
130
+ function digestTurn(t, index, total) {
131
+ const head = (String(t.prompt || "").split("\n").map((l) => l.trim()).filter(Boolean)[0] || "").slice(0, 90);
132
+ const toolText = t.tools && t.tools.length
133
+ ? t.tools.map((x) => `${x.tool}${x.ok === false ? " failed" : " ok"}`).join(", ")
134
+ : "no tools";
135
+ const outcome = (String(t.response || "").split("\n").map((l) => l.trim()).filter(Boolean)[0] || "").slice(0, 140);
136
+ return `Turn ${index + 1} of ${total} summary: ${head} | tools: ${toolText} | outcome: ${outcome}`;
137
+ }
138
+
139
+ function contextBlock(session, maxChars = 6000) {
140
+ const turns = (session.turns || []).slice(-8);
141
+ if (!turns.length) return "";
142
+ const older = turns.slice(0, -2);
143
+ const recent = turns.slice(-2);
144
+ const total = turns.length;
145
+ const parts = [
146
+ ...older.map((t, i) => digestTurn(t, i, total)),
147
+ ...recent.map((t, i) => `Turn ${older.length + i + 1} of ${total} (mode ${t.mode}${t.target ? `, target ${t.target}` : ""}):\nQ: ${t.prompt}\nA: ${t.response.slice(0, 2000)}`),
148
+ ];
149
+ const joined = parts.join("\n\n").slice(-maxChars);
150
+ return `Previous turns in this session (most recent last; older turns summarized, latest two in full):\n${joined}`;
151
+ }
152
+
153
+ module.exports = { create, load, save, appendTurn, list, latest, remove, contextBlock };