kovence-cli 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+
3
+ const path = require("node:path");
4
+ const { AGENT_MODES } = require("../settings/schema");
5
+
6
+ /**
7
+ * Parse CLI flags strictly, rejecting unknown flags, missing option values, and invalid numbers.
8
+ */
9
+ function parseArgs(argv) {
10
+ const opts = {
11
+ model: "",
12
+ provider: "",
13
+ prompt: "",
14
+ system: "",
15
+ mode: "",
16
+ autoApprove: null,
17
+ toolsEnabled: null,
18
+ autoSummarize: null,
19
+ temperature: null,
20
+ maxTokens: null,
21
+ session: "",
22
+ newSession: "",
23
+ continueLatest: false,
24
+ addDirs: [],
25
+ plain: false,
26
+ json: false,
27
+ noSession: false,
28
+ debug: false,
29
+ doctor: false,
30
+ help: false,
31
+ version: false,
32
+ };
33
+ const positional = [];
34
+
35
+ const takeValue = (i, flag) => {
36
+ if (i + 1 >= argv.length) {
37
+ throw new Error(`Option '${flag}' requires a value.`);
38
+ }
39
+ return argv[i + 1];
40
+ };
41
+
42
+ for (let i = 0; i < argv.length; i++) {
43
+ const a = argv[i];
44
+ if (a === "--") {
45
+ positional.push(...argv.slice(i + 1));
46
+ break;
47
+ }
48
+ if (a === "-h" || a === "--help") opts.help = true;
49
+ else if (a === "-v" || a === "--version") opts.version = true;
50
+ else if (a === "-a" || a === "--auto") opts.autoApprove = true;
51
+ else if (a === "--no-tools") opts.toolsEnabled = false;
52
+ else if (a === "--no-summary") opts.autoSummarize = false;
53
+ else if (a === "--plain") opts.plain = true;
54
+ else if (a === "--json") opts.json = true;
55
+ else if (a === "--no-session") opts.noSession = true;
56
+ else if (a === "--debug") opts.debug = true;
57
+ else if (a === "-c" || a === "--continue") opts.continueLatest = true;
58
+ else if (a === "-m" || a === "--model") {
59
+ opts.model = takeValue(i, a);
60
+ i++;
61
+ } else if (a === "--provider") {
62
+ opts.provider = takeValue(i, a);
63
+ i++;
64
+ } else if (a === "-p" || a === "--prompt") {
65
+ opts.prompt = takeValue(i, a);
66
+ i++;
67
+ } else if (a === "-s" || a === "--system") {
68
+ opts.system = takeValue(i, a);
69
+ i++;
70
+ } else if (a === "--mode") {
71
+ const val = takeValue(i, a);
72
+ i++;
73
+ if (!AGENT_MODES.includes(val)) {
74
+ throw new Error(`Invalid --mode '${val}'. Valid modes: ${AGENT_MODES.join(", ")}.`);
75
+ }
76
+ opts.mode = val;
77
+ } else if (a === "--add-dir") {
78
+ const dir = takeValue(i, a);
79
+ i++;
80
+ opts.addDirs.push(path.resolve(process.cwd(), dir));
81
+ } else if (a === "-t" || a === "--temp") {
82
+ const raw = takeValue(i, a);
83
+ i++;
84
+ const num = Number(raw);
85
+ if (!Number.isFinite(num) || num < 0 || num > 2) {
86
+ throw new Error(`Invalid temperature '${raw}'. Expected 0.0 to 2.0.`);
87
+ }
88
+ opts.temperature = num;
89
+ } else if (a === "--max-tokens") {
90
+ const raw = takeValue(i, a);
91
+ i++;
92
+ const num = Number.parseInt(raw, 10);
93
+ if (!/^\d+$/.test(raw) || num < 1) {
94
+ throw new Error(`Invalid --max-tokens '${raw}'. Expected positive integer.`);
95
+ }
96
+ opts.maxTokens = num;
97
+ } else if (a === "--session") {
98
+ opts.session = takeValue(i, a);
99
+ i++;
100
+ } else if (a === "--new-session") {
101
+ opts.newSession = takeValue(i, a);
102
+ i++;
103
+ } else if (a.startsWith("-")) {
104
+ throw new Error(`Unknown option '${a}'. Run with --help to see supported flags.`);
105
+ } else {
106
+ positional.push(a);
107
+ }
108
+ }
109
+ if (positional[0] === "doctor" && !opts.prompt) {
110
+ opts.doctor = true;
111
+ positional.shift();
112
+ }
113
+ if (!opts.prompt && positional.length) opts.prompt = positional.join(" ");
114
+ return opts;
115
+ }
116
+
117
+ function getHelpText() {
118
+ return `Kovence CLI (https://kovence.com)
119
+ Usage: kovence [options] [prompt] (or: kovence-cli / node nd.js)
120
+
121
+ CLI Options:
122
+ --provider <name> Use configured OpenAI/Anthropic provider
123
+ -m, --model <name> Override model (CLI > session > settings > provider)
124
+ -p, --prompt <text> Non-interactive prompt (clean answer on stdout)
125
+ -s, --system <text> Override system prompt
126
+ --mode <mode> Agent mode: default | accept-edits | plan | auto
127
+ -a, --auto Alias for --mode auto
128
+ --add-dir <path> Grant workspace access to an extra directory (repeatable)
129
+ --no-tools Disable tool calling (chat only)
130
+ --no-summary Skip post-response session memory summarization
131
+ --plain Use plain scrollback REPL instead of full-screen TUI
132
+ --json Emit structured JSON result in -p headless mode
133
+ --no-session Run without persisting session history to disk
134
+ --debug Enable verbose debug tracing
135
+ doctor Run environment, tools & provider connectivity checks
136
+ -t, --temp <num> Sampling temperature (0.0-2.0)
137
+ --max-tokens <num> Max completion tokens
138
+ --session <name> Resume/use a specific saved session
139
+ -c, --continue Resume the most recent session
140
+ --new-session <name> Start a fresh session with given name (default: auto new session)
141
+ -v, --version Show version
142
+ -h, --help Show help
143
+
144
+ Harness Commands:
145
+ /help Show all commands
146
+ /mode [mode] Open mode picker or switch (default|accept-edits|plan|auto)
147
+ /settings Open interactive Settings panel (Ctrl+,)
148
+ /set <key> <value> Update persisted setting directly
149
+ /api [subcmd] Open provider picker or list/add/use/rm
150
+ /model [name] Open model picker or switch & save model
151
+ /sessions [subcmd] Open session picker (Ctrl+S) or list/new/switch/delete
152
+ /new [name] Create fresh isolated session (Ctrl+N)
153
+ /save <name> Rename and save current session
154
+ /undo Rollback the last file edit/write/delete checkpoint
155
+ /init Generate KOVENCE.md project guide
156
+ /retry Retry the last failed or aborted prompt
157
+ /history [n] Show last n messages from session history
158
+ /memory [subcmd] Inspect/manage session & global memory
159
+ /todos Show session task checklist
160
+ /compact Compact older turns into session summary memory
161
+ /stats Show context size, TTFT, generation speed & token usage
162
+ /copy Copy last AI response (Ctrl+Y)
163
+ /select Toggle native terminal selection (F2)
164
+ /clear Clear current session history
165
+ /exit Quit Kovence CLI`;
166
+ }
167
+
168
+ module.exports = {
169
+ parseArgs,
170
+ getHelpText,
171
+ };
@@ -0,0 +1,326 @@
1
+ "use strict";
2
+
3
+ const { AGENT_MODES, loadGlobalMemory } = require("../../store");
4
+ const { C, promptLine, promptSecret, promptConfirm } = require("../../ui");
5
+ const { getContextLabel } = require("../commands/handlers");
6
+
7
+ function createPlainSink(interactive, { headless = false, jsonMode = false } = {}) {
8
+ return {
9
+ isTui: false,
10
+ interactive,
11
+ headless,
12
+ log(kind, text) {
13
+ if (jsonMode) {
14
+ if (kind === "error") console.error(text);
15
+ return;
16
+ }
17
+ if (headless) {
18
+ if (kind === "error") console.error(`${C.red}${text}${C.reset}`);
19
+ else if (kind === "tool") console.error(`${C.dim}${text}${C.reset}`);
20
+ else if (kind === "assistant") console.log(text);
21
+ return;
22
+ }
23
+ if (kind === "error") console.error(`${C.red}${text}${C.reset}`);
24
+ else if (kind === "tool" || kind === "meta") console.log(`${C.dim}${text}${C.reset}`);
25
+ else console.log(text);
26
+ },
27
+ clear() {},
28
+ setBusy() {},
29
+ syncStatus() {},
30
+ startThinking(prefix = "Kovence: ", label = "Thinking") {
31
+ if (jsonMode) {
32
+ return {
33
+ stop() {},
34
+ write() {},
35
+ end() {},
36
+ };
37
+ }
38
+ if (headless || !process.stdout.isTTY) {
39
+ if (!headless && prefix) process.stdout.write(prefix);
40
+ return {
41
+ stop() {},
42
+ write(tok) {
43
+ process.stdout.write(tok);
44
+ },
45
+ end(hasText) {
46
+ if (hasText) process.stdout.write("\n");
47
+ },
48
+ };
49
+ }
50
+ const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
51
+ const dots = [" ", ". ", ".. ", "..."];
52
+ let tick = 0;
53
+ let stopped = false;
54
+ const render = () => {
55
+ const symbol = frames[tick % frames.length];
56
+ const blink = dots[Math.floor(tick / 2) % dots.length];
57
+ process.stdout.write(
58
+ `\r\x1b[K${C.cyan}${prefix}${C.reset}${C.yellow}${symbol} ${label}${blink}${C.reset}`
59
+ );
60
+ tick++;
61
+ };
62
+ render();
63
+ const timer = setInterval(render, 100);
64
+ return {
65
+ stop(keepPrefix = true) {
66
+ if (stopped) return;
67
+ stopped = true;
68
+ clearInterval(timer);
69
+ process.stdout.write(keepPrefix ? `\r\x1b[K${C.cyan}${prefix}${C.reset}` : "\r\x1b[K");
70
+ },
71
+ write(tok) {
72
+ process.stdout.write(tok);
73
+ },
74
+ end(hasText) {
75
+ if (hasText) process.stdout.write("\n");
76
+ },
77
+ };
78
+ },
79
+ confirm: (label) => (interactive ? promptConfirm(`${C.yellow}${label}${C.reset}`) : Promise.resolve("n")),
80
+ askPrompt: (label) => (interactive ? promptLine(label, []) : Promise.resolve("")),
81
+ askPassword: interactive ? (label) => promptSecret(label) : null,
82
+ startProgress(initialText = "") {
83
+ if (jsonMode || headless || !process.stdout.isTTY) {
84
+ return { update() {}, done() {} };
85
+ }
86
+ if (initialText) process.stdout.write(`\r\x1b[K${C.yellow}${initialText}${C.reset}`);
87
+ return {
88
+ update(text) {
89
+ process.stdout.write(`\r\x1b[K${C.yellow}${text}${C.reset}`);
90
+ },
91
+ done(finalText) {
92
+ process.stdout.write(`\r\x1b[K${C.green}${finalText}${C.reset}\n`);
93
+ },
94
+ };
95
+ },
96
+ };
97
+ }
98
+
99
+ function addTuiBanner(tui, state) {
100
+ const gCount = loadGlobalMemory(state.paths).length;
101
+ tui.addBlock(
102
+ "brand-cyan",
103
+ [
104
+ "",
105
+ " ██╗ ██╗ ██████╗ ██╗ ██╗███████╗███╗ ██╗ ██████╗███████╗",
106
+ " ██║ ██╔╝██╔═══██╗██║ ██║██╔════╝████╗ ██║██╔════╝██╔════╝",
107
+ " █████╔╝ ██║ ██║██║ ██║█████╗ ██╔██╗ ██║██║ █████╗ ",
108
+ ].join("\n")
109
+ );
110
+ tui.addBlock(
111
+ "brand-magenta",
112
+ [
113
+ " ██╔═██╗ ██║ ██║╚██╗ ██╔╝██╔══╝ ██║╚██╗██║██║ ██╔══╝ ",
114
+ " ██║ ██╗╚██████╔╝ ╚████╔╝ ███████╗██║ ╚████║╚██████╗███████╗",
115
+ " ╚═╝ ╚═╝ ╚═════╝ ╚═══╝ ╚══════╝╚═╝ ╚═══╝ ╚═════╝╚══════╝",
116
+ ].join("\n")
117
+ );
118
+ tui.addBlock(
119
+ "system",
120
+ `Kovence CLI · https://kovence.com\nAPI: ${state.provider.name} [${state.provider.type}] · Model: ${state.model}\nMode: ${state.settings.agentMode} · Session: ${state.session.id} (${state.session.history.length} msgs, ${getContextLabel(state)}, globalMem: ${gCount})\n`
121
+ );
122
+ }
123
+
124
+ function createTuiSink(tui, state) {
125
+ return {
126
+ isTui: true,
127
+ interactive: true,
128
+ headless: false,
129
+ log(kind, text) {
130
+ tui.addBlock(kind, text);
131
+ },
132
+ setInput(text) {
133
+ tui.setInput(text);
134
+ },
135
+ clear() {
136
+ tui.clearBlocks();
137
+ addTuiBanner(tui, state);
138
+ },
139
+ setBusy(label) {
140
+ tui.setStatus({ busyLabel: label, isBusy: Boolean(state.isBusy || label), queueLen: state.queue.length });
141
+ },
142
+ syncStatus() {
143
+ tui.setStatus({
144
+ sessionId: state.session.id,
145
+ provider: state.provider.name,
146
+ providerType: state.provider.type,
147
+ model: state.model,
148
+ ctxText: getContextLabel(state),
149
+ agentMode: state.settings.agentMode,
150
+ colorScheme: state.settings.colorScheme || "amber",
151
+ tools: state.settings.toolsEnabled,
152
+ auto: state.settings.agentMode === "auto",
153
+ showTips: state.settings.showTips !== false,
154
+ showActiveTasks: state.settings.showActiveTasks !== false,
155
+ activeBgTasks: state.bgTasks?.activeCount?.() || 0,
156
+ activeTodos: (state.session?.todos || []).filter((t) => t.status !== "done").length,
157
+ notifications: state.settings.notifications !== false,
158
+ isBusy: Boolean(state.isBusy),
159
+ queueLen: state.queue.length,
160
+ });
161
+ },
162
+ notify() {
163
+ if (state.settings?.notifications !== false && process.stdout.isTTY) {
164
+ process.stdout.write("\x07");
165
+ }
166
+ },
167
+ startThinking(_prefix = "Kovence: ", label = "Thinking") {
168
+ const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
169
+ const dots = [" ", ". ", ".. ", "..."];
170
+ let tick = 0;
171
+ let stopped = false;
172
+ const block = tui.addBlock("thinking", `⠋ ${label} `);
173
+ const timer = setInterval(() => {
174
+ tick++;
175
+ const symbol = frames[tick % frames.length];
176
+ const blink = dots[Math.floor(tick / 2) % dots.length];
177
+ tui.updateBlock(block, `${symbol} ${label}${blink}`);
178
+ }, 100);
179
+
180
+ return {
181
+ stop(keepForStream = true) {
182
+ if (stopped) return;
183
+ stopped = true;
184
+ clearInterval(timer);
185
+ if (keepForStream) {
186
+ block.kind = "assistant";
187
+ tui.updateBlock(block, "");
188
+ } else {
189
+ const idx = tui.blocks.indexOf(block);
190
+ if (idx !== -1) tui.blocks.splice(idx, 1);
191
+ tui.scheduleRender();
192
+ }
193
+ },
194
+ write(tok) {
195
+ tui.appendBlock(block, tok);
196
+ },
197
+ end() {},
198
+ };
199
+ },
200
+ confirm: (label) => tui.askModal(label, false),
201
+ askPrompt: (label) => tui.askModal(label, false),
202
+ askPassword: (label) => tui.askModal(label, true),
203
+ openSettings: () => tui.openSettings(),
204
+ openPermissions: () => {
205
+ tui.settingsScreen = null;
206
+ tui.openManagePermissions();
207
+ },
208
+ async openChoicePicker(title, items, currentId = "") {
209
+ if (!items || !items.length) return "";
210
+ const initialIdx = Math.max(
211
+ 0,
212
+ items.findIndex((x) => x.id === currentId)
213
+ );
214
+ const res = await tui.openPicker(title, items, {
215
+ initialIdx,
216
+ hint: "↑/↓ select · Enter apply · Esc close",
217
+ });
218
+ return res?.action === "select" ? res.item?.id || "" : "";
219
+ },
220
+ async openModePicker(currentMode) {
221
+ const modeMeta = [
222
+ { id: "default", desc: "Ask confirmation for file edits, downloads & commands" },
223
+ { id: "accept-edits", desc: "Auto-approve file edits; confirm commands & downloads" },
224
+ { id: "plan", desc: "Research & plan only (all mutations blocked)" },
225
+ { id: "auto", desc: "Auto-allow tools & sudo (1-time session sudo password)" },
226
+ ];
227
+ const items = modeMeta.map((m) => ({
228
+ type: "mode",
229
+ id: m.id,
230
+ label: `${m.id === currentMode ? "● " : " "}${m.id}`,
231
+ desc: m.desc,
232
+ }));
233
+ const initialIdx = Math.max(
234
+ 0,
235
+ modeMeta.findIndex((m) => m.id === currentMode)
236
+ );
237
+ const res = await tui.openPicker("Select Agent Mode (Shift+Tab)", items, {
238
+ initialIdx,
239
+ hint: "↑/↓ select · Enter apply · Esc close",
240
+ });
241
+ return res?.action === "select" ? res.item?.id || "" : "";
242
+ },
243
+ startProgress(initialText = "") {
244
+ const block = tui.addBlock("tool", initialText || "⬇ Starting download...");
245
+ return {
246
+ update(text) {
247
+ tui.updateBlock(block, text);
248
+ },
249
+ done(finalText) {
250
+ tui.updateBlock(block, finalText || block.text);
251
+ },
252
+ };
253
+ },
254
+ startToolCall(label, { collapsible = true, expanded = false } = {}) {
255
+ const block = tui.addBlock("tool", label, {
256
+ collapsible,
257
+ expanded,
258
+ details: [],
259
+ statusLine: "running...",
260
+ });
261
+ const details = [];
262
+ let lastUpdateAt = 0;
263
+
264
+ return {
265
+ block,
266
+ pushOutput(rawChunk) {
267
+ const cleaned = String(rawChunk || "")
268
+ .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, "")
269
+ .replace(/\x1b\[[0-9;?=<>]*[a-zA-Z~]/g, "");
270
+ const parts = cleaned.split(/\r?\n/);
271
+ for (const part of parts) {
272
+ // If a line contains \r progress updates, keep the final segment of that line
273
+ const crSegments = part
274
+ .split("\r")
275
+ .map((s) => s.trim())
276
+ .filter(Boolean);
277
+ if (!crSegments.length) continue;
278
+ const lastSeg = crSegments[crSegments.length - 1];
279
+ if (part.includes("\r") && details.length > 0) {
280
+ details[details.length - 1] = lastSeg;
281
+ } else {
282
+ details.push(lastSeg);
283
+ if (details.length > 80) details.shift();
284
+ }
285
+ }
286
+ if (!details.length) return;
287
+ const latest = details[details.length - 1];
288
+ const now = Date.now();
289
+ if (now - lastUpdateAt >= 80) {
290
+ lastUpdateAt = now;
291
+ tui.setBlockDetails(block, [...details], latest);
292
+ } else {
293
+ block.details = [...details];
294
+ block.statusLine = latest;
295
+ }
296
+ },
297
+ finish(fullOutputText = "", isError = false) {
298
+ if (!details.length && fullOutputText) {
299
+ const fallbackLines = String(fullOutputText)
300
+ .split(/\r?\n/)
301
+ .map((l) => l.trimEnd())
302
+ .filter(Boolean)
303
+ .slice(-60);
304
+ details.push(...fallbackLines);
305
+ }
306
+ const summaryLine = isError
307
+ ? String(fullOutputText || "failed").split(/\r?\n/)[0]
308
+ : details[details.length - 1] || String(fullOutputText || "done").split(/\r?\n/)[0];
309
+ tui.setBlockDetails(block, [...details], summaryLine);
310
+ },
311
+ };
312
+ },
313
+ };
314
+ }
315
+
316
+ function nextAgentMode(currentMode) {
317
+ const idx = Math.max(0, AGENT_MODES.indexOf(currentMode));
318
+ return AGENT_MODES[(idx + 1) % AGENT_MODES.length];
319
+ }
320
+
321
+ module.exports = {
322
+ createPlainSink,
323
+ addTuiBanner,
324
+ createTuiSink,
325
+ nextAgentMode,
326
+ };