kovence-cli 1.0.2 → 1.2.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/nd.js CHANGED
@@ -40,6 +40,7 @@ const {
40
40
  replaySessionHistory,
41
41
  } = require("./src/commands/handlers");
42
42
  const { runAgentTurn, compactSession, waitForMemorySync } = require("./src/agent/turn");
43
+ const { cleanupOldSessions } = require("./src/config/sessions");
43
44
 
44
45
  function makeAutoSessionId() {
45
46
  const d = new Date();
@@ -165,6 +166,7 @@ async function runDoctor(paths, envFallback) {
165
166
  });
166
167
  checks.push({ name: "sudo", ok: hasBin("sudo"), detail: hasBin("sudo") ? "installed" : "missing" });
167
168
  checks.push({ name: "Global config dir", ok: true, detail: paths.globalDir });
169
+ checks.push({ name: "Sessions dir", ok: true, detail: paths.sessionsDir });
168
170
  checks.push({ name: "Project .kovence dir", ok: true, detail: paths.projectDir });
169
171
 
170
172
  const provStore = loadProviders(envFallback, paths);
@@ -387,7 +389,7 @@ async function runTuiRepl(state) {
387
389
  },
388
390
  async onNewSession() {
389
391
  const rawName = (await tui.askModal("New session name (blank = auto): ", false)).trim();
390
- const id = rawName || `session-${new Date().toISOString().slice(11, 19).replace(/:/g, "")}`;
392
+ const id = rawName || makeAutoSessionId();
391
393
  state.activePrompt = "";
392
394
  state.queue.length = 0;
393
395
  state.activeAbort?.abort();
@@ -618,6 +620,14 @@ async function main() {
618
620
  session.model = model;
619
621
  if (!opts.noSession) saveSession(session, paths);
620
622
 
623
+ // Run session retention cleanup on startup (non-fatal, skip active session).
624
+ try {
625
+ const retentionDays = persistedSettings.chatHistoryRetentionDays;
626
+ cleanupOldSessions(retentionDays, paths, session.id);
627
+ } catch {
628
+ // Non-fatal: cleanup errors must never crash startup.
629
+ }
630
+
621
631
  const state = {
622
632
  paths,
623
633
  workspaceRoot: paths.cwd,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kovence-cli",
3
- "version": "1.0.2",
3
+ "version": "1.2.0",
4
4
  "description": "Kovence CLI — Fast zero-dependency multi-step AI coding-agent CLI harness",
5
5
  "license": "MIT",
6
6
  "homepage": "https://kovence-cli.kovence.com",
package/providers.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
 
3
3
  const { lookupModelCapabilities } = require("./src/config/model_registry");
4
+ const { StreamingToolArgsParser } = require("./src/agent/streaming_write");
4
5
 
5
6
  function buildProviderUrls(provider) {
6
7
  const base = String(provider?.baseUrl || "").replace(/\/+$/, "");
@@ -369,6 +370,8 @@ async function streamProviderTurn({
369
370
  let finishReason = null;
370
371
  const toolMap = new Map();
371
372
  const isAnthropic = provider.type === "anthropic";
373
+ // Per-tool streaming write parser for live 5-line window preview and dynamic file stream
374
+ const writeStreamParsers = new Map();
372
375
 
373
376
  const markFirstToken = (forText) => {
374
377
  if (firstTokenAt === null) firstTokenAt = Date.now();
@@ -378,6 +381,43 @@ async function streamProviderTurn({
378
381
  }
379
382
  };
380
383
 
384
+ let lastProgressUpdate = 0;
385
+ const updateToolProgress = () => {
386
+ if (firstTokenAt === null) firstTokenAt = Date.now();
387
+ if (printedHeader) return;
388
+ const now = Date.now();
389
+ if (now - lastProgressUpdate < 80) return;
390
+ lastProgressUpdate = now;
391
+
392
+ const activeEntry = [...toolMap.values()].pop();
393
+ const toolName = activeEntry?.function?.name || "";
394
+ const args = activeEntry?.function?.arguments || "";
395
+ const isWrite = /write_file|edit_file|multi_edit|apply_patch/.test(toolName);
396
+ const isRead = /read_file|glob_files|grep_files|file_search|list_directory/.test(toolName);
397
+
398
+ let target = "";
399
+ const m = args.match(/"(?:path|target|file)":\s*"([^"]+)"/);
400
+ if (m) {
401
+ const p = m[1];
402
+ target = p.length > 25 ? `...${p.slice(-22)}` : p;
403
+ }
404
+
405
+ const charCount = args.length;
406
+ const charSuffix = charCount > 100 ? ` (${Math.round(charCount / 100) / 10}k chars)` : "";
407
+
408
+ let label = "Thinking...";
409
+ if (isWrite) {
410
+ label = target ? `Writing ${target}${charSuffix}...` : `Writing code${charSuffix}...`;
411
+ } else if (isRead) {
412
+ label = target ? `Reading ${target}...` : `Reading codebase...`;
413
+ } else if (toolName) {
414
+ label = target ? `${toolName}(${target})...` : `Preparing ${toolName}...`;
415
+ }
416
+
417
+ streamUi.setLabel?.(label);
418
+ sink.setBusy?.(label);
419
+ };
420
+
381
421
  const mergeOpenAITools = (deltas) => {
382
422
  for (const d of deltas) {
383
423
  const idx = d.index ?? 0;
@@ -389,10 +429,70 @@ async function streamProviderTurn({
389
429
  });
390
430
  }
391
431
  const entry = toolMap.get(idx);
392
- if (d.id) entry.id = d.id;
432
+ // Detect when the LLM reuses the same slot index for a NEW sequential tool call.
433
+ // Indicators: (a) a different call id, or (b) a new function name arriving when
434
+ // the entry already had a completed arguments string (heuristic: the previous
435
+ // tool's JSON was already closed with "}").
436
+ const isNewToolOnSameIdx =
437
+ (d.id && d.id !== entry.id) || (d.function?.name && entry.function.arguments.endsWith("}"));
438
+ if (isNewToolOnSameIdx) {
439
+ if (d.id) entry.id = d.id;
440
+ entry.function.name = "";
441
+ entry.function.arguments = "";
442
+ writeStreamParsers.delete(idx);
443
+ }
393
444
  if (d.function?.name) entry.function.name += d.function.name;
394
- if (d.function?.arguments) entry.function.arguments += d.function.arguments;
445
+ if (d.function?.arguments) {
446
+ entry.function.arguments += d.function.arguments;
447
+ pumpWriteChunk(idx, d.function.arguments);
448
+ }
449
+ }
450
+ };
451
+
452
+ /**
453
+ * Called with each raw argument delta chunk for a tool call.
454
+ * When the tool is write_file/edit_file, extracts the unescaped content/replacement
455
+ * characters and target path, streaming them dynamically to sink.
456
+ */
457
+ const pumpWriteChunk = (idx, deltaChunk) => {
458
+ const entry = toolMap.get(idx);
459
+ if (!entry) return;
460
+ const tName = entry.function?.name || "";
461
+ // If we already know the tool name and it's NOT a write tool, skip entirely.
462
+ // When tName is still empty (name delta hasn't arrived yet), always create/reuse
463
+ // the parser so we don't miss early argument chunks.
464
+ if (tName && !/write_file|edit_file|multi_edit/.test(tName)) return;
465
+
466
+ let parser = writeStreamParsers.get(idx);
467
+ // If the parser already finished its content stream, it belongs to a *previous*
468
+ // tool call that happened to share the same slot index. Discard it so we start
469
+ // fresh for the new tool call. This covers models that don't send a new `id`.
470
+ if (parser && parser.contentEnded) {
471
+ writeStreamParsers.delete(idx);
472
+ parser = null;
473
+ }
474
+ if (!parser) {
475
+ parser = new StreamingToolArgsParser({
476
+ onPath: (filePath) => {
477
+ // Re-read name from live entry — it may have arrived after parser creation
478
+ const currentName = entry.function?.name || "write_file";
479
+ if (!/write_file|edit_file|multi_edit/.test(currentName)) return;
480
+ sink.preRegisterWriteBlock?.(idx, currentName, filePath);
481
+ },
482
+ onContentChunk: (unescapedChunk, filePath, _key) => {
483
+ const currentName = entry.function?.name || "write_file";
484
+ if (!/write_file|edit_file|multi_edit/.test(currentName)) return;
485
+ sink.onWriteStreamChunk?.(idx, currentName, filePath, unescapedChunk);
486
+ },
487
+ onContentEnd: (filePath, _key) => {
488
+ const currentName = entry.function?.name || "write_file";
489
+ if (!/write_file|edit_file|multi_edit/.test(currentName)) return;
490
+ sink.onWriteStreamChunkEnd?.(idx, currentName, filePath);
491
+ },
492
+ });
493
+ writeStreamParsers.set(idx, parser);
395
494
  }
495
+ parser.push(deltaChunk);
396
496
  };
397
497
 
398
498
  const handleLine = (rawLine) => {
@@ -423,23 +523,24 @@ async function streamProviderTurn({
423
523
  };
424
524
  }
425
525
  } else if (json.type === "content_block_start" && json.content_block?.type === "tool_use") {
426
- markFirstToken(false);
427
526
  const idx = json.index ?? toolMap.size;
428
527
  toolMap.set(idx, {
429
528
  id: json.content_block.id || `call_${idx}`,
430
529
  type: "function",
431
530
  function: { name: json.content_block.name || "", arguments: "" },
432
531
  });
532
+ updateToolProgress();
433
533
  } else if (json.type === "content_block_delta") {
434
534
  if (json.delta?.type === "text_delta" && json.delta.text) {
435
535
  markFirstToken(true);
436
536
  streamUi.write(json.delta.text);
437
537
  fullText += json.delta.text;
438
538
  } else if (json.delta?.type === "input_json_delta" && json.delta.partial_json) {
439
- markFirstToken(false);
440
539
  const idx = json.index ?? 0;
441
540
  const entry = toolMap.get(idx);
442
541
  if (entry) entry.function.arguments += json.delta.partial_json;
542
+ pumpWriteChunk(idx, json.delta.partial_json);
543
+ updateToolProgress();
443
544
  }
444
545
  }
445
546
  return;
@@ -450,8 +551,8 @@ async function streamProviderTurn({
450
551
  if (choice?.finish_reason) finishReason = choice.finish_reason;
451
552
  const delta = choice?.delta;
452
553
  if (delta?.tool_calls?.length) {
453
- markFirstToken(false);
454
554
  mergeOpenAITools(delta.tool_calls);
555
+ updateToolProgress();
455
556
  }
456
557
  const token = delta?.content ?? json.response ?? "";
457
558
  if (token) {
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Incremental streaming JSON parser designed for tool call argument deltas.
5
+ * Robustly extracts `path` and unescapes `content`/`replacement` chunks on the fly,
6
+ * even when escape sequences or Unicode sequences are split across chunk boundaries,
7
+ * or when `content` arrives before `path`.
8
+ */
9
+ class StreamingToolArgsParser {
10
+ constructor({ onPath, onContentChunk, onContentEnd }) {
11
+ this.onPath = onPath;
12
+ this.onContentChunk = onContentChunk;
13
+ this.onContentEnd = onContentEnd;
14
+
15
+ this.mode = "SEEK_KEY"; // SEEK_KEY | IN_KEY | AFTER_KEY | IN_VALUE_STRING | IN_VALUE_OTHER
16
+ this.keyBuf = "";
17
+ this.activeKey = "";
18
+ this.escape = false;
19
+ this.inUnicode = false;
20
+ this.unicodeBuf = "";
21
+ this.path = "";
22
+ this.pathEmitted = false;
23
+ this.contentEnded = false;
24
+ this.bufferedChunks = [];
25
+ }
26
+
27
+ push(chunk) {
28
+ if (!chunk) return;
29
+ let pending = "";
30
+ let pendingKey = "";
31
+
32
+ for (let i = 0; i < chunk.length; i++) {
33
+ const ch = chunk[i];
34
+
35
+ if (this.mode === "SEEK_KEY") {
36
+ if (ch === '"') {
37
+ this.mode = "IN_KEY";
38
+ this.keyBuf = "";
39
+ }
40
+ } else if (this.mode === "IN_KEY") {
41
+ if (ch === '"') {
42
+ this.activeKey = this.keyBuf;
43
+ this.mode = "AFTER_KEY";
44
+ } else {
45
+ this.keyBuf += ch;
46
+ }
47
+ } else if (this.mode === "AFTER_KEY") {
48
+ if (ch === ":") {
49
+ // separator; wait for quote or non-whitespace
50
+ } else if (ch === '"') {
51
+ this.mode = "IN_VALUE_STRING";
52
+ this.escape = false;
53
+ this.inUnicode = false;
54
+ } else if (!/\s/.test(ch)) {
55
+ this.mode = "IN_VALUE_OTHER";
56
+ }
57
+ } else if (this.mode === "IN_VALUE_OTHER") {
58
+ if (ch === "," || ch === "}") {
59
+ this.mode = "SEEK_KEY";
60
+ this.activeKey = "";
61
+ }
62
+ } else if (this.mode === "IN_VALUE_STRING") {
63
+ if (this.escape) {
64
+ if (this.inUnicode) {
65
+ this.unicodeBuf += ch;
66
+ if (this.unicodeBuf.length === 4) {
67
+ const code = parseInt(this.unicodeBuf, 16);
68
+ const unich = Number.isNaN(code) ? "" : String.fromCharCode(code);
69
+ if (this.activeKey === "path") {
70
+ this.path += unich;
71
+ } else if (this.activeKey === "content" || this.activeKey === "replacement") {
72
+ pending += unich;
73
+ pendingKey = this.activeKey;
74
+ }
75
+ this.escape = false;
76
+ this.inUnicode = false;
77
+ }
78
+ } else if (ch === "u") {
79
+ this.inUnicode = true;
80
+ this.unicodeBuf = "";
81
+ } else {
82
+ let decoded = ch;
83
+ if (ch === "n") decoded = "\n";
84
+ else if (ch === "r") decoded = "\r";
85
+ else if (ch === "t") decoded = "\t";
86
+ else if (ch === "b") decoded = "\b";
87
+ else if (ch === "f") decoded = "\f";
88
+ else if (ch === '"') decoded = '"';
89
+ else if (ch === "\\") decoded = "\\";
90
+ else if (ch === "/") decoded = "/";
91
+
92
+ if (this.activeKey === "path") {
93
+ this.path += decoded;
94
+ } else if (this.activeKey === "content" || this.activeKey === "replacement") {
95
+ pending += decoded;
96
+ pendingKey = this.activeKey;
97
+ }
98
+ this.escape = false;
99
+ }
100
+ } else if (ch === "\\") {
101
+ this.escape = true;
102
+ } else if (ch === '"') {
103
+ // Current string value ended
104
+ if (this.activeKey === "path") {
105
+ this._flushPath();
106
+ } else if (this.activeKey === "content" || this.activeKey === "replacement") {
107
+ if (pending.length > 0) {
108
+ this._emitContent(pending, pendingKey);
109
+ pending = "";
110
+ }
111
+ this.contentEnded = true;
112
+ this.onContentEnd?.(this.path, this.activeKey);
113
+ }
114
+ this.mode = "SEEK_KEY";
115
+ this.activeKey = "";
116
+ } else {
117
+ if (this.activeKey === "path") {
118
+ this.path += ch;
119
+ } else if (this.activeKey === "content" || this.activeKey === "replacement") {
120
+ pending += ch;
121
+ pendingKey = this.activeKey;
122
+ }
123
+ }
124
+ }
125
+ }
126
+
127
+ if (pending.length > 0) {
128
+ this._emitContent(pending, pendingKey);
129
+ }
130
+ }
131
+
132
+ _flushPath() {
133
+ if (!this.pathEmitted && this.path) {
134
+ this.pathEmitted = true;
135
+ this.onPath?.(this.path);
136
+ if (this.bufferedChunks.length > 0) {
137
+ for (const item of this.bufferedChunks) {
138
+ this.onContentChunk?.(item.chunk, this.path, item.key);
139
+ }
140
+ this.bufferedChunks = [];
141
+ }
142
+ if (this.contentEnded) {
143
+ this.onContentEnd?.(this.path, "content");
144
+ }
145
+ }
146
+ }
147
+
148
+ _emitContent(str, key) {
149
+ if (this.pathEmitted) {
150
+ this.onContentChunk?.(str, this.path, key);
151
+ } else {
152
+ this.bufferedChunks.push({ chunk: str, key });
153
+ }
154
+ }
155
+ }
156
+
157
+ module.exports = {
158
+ StreamingToolArgsParser,
159
+ };
package/src/agent/turn.js CHANGED
@@ -287,6 +287,7 @@ async function runToolCalls(state, toolCalls, sink) {
287
287
  openChoicePicker: sink.openChoicePicker,
288
288
  bgTasks: state.bgTasks || null,
289
289
  _permissionChecked: true,
290
+ streamCheckpointed: state.streamCheckpointed,
290
291
  signal: state.activeAbort?.signal || null,
291
292
  saveSession: (s) => {
292
293
  if (!state.noSession) saveSession(s, state.paths);
@@ -427,6 +428,7 @@ async function runToolCalls(state, toolCalls, sink) {
427
428
  } else {
428
429
  results[i] = { role: "tool", tool_call_id: tc.id, name, content: "Denied by user." };
429
430
  sink.log("tool", `✗ ${name}(${summary}) denied`);
431
+ sink.cleanupStreamWrite?.(i, true);
430
432
  continue;
431
433
  }
432
434
  } else if (evalRes.matchedRule && evalRes.ruleLabel) {
@@ -445,7 +447,7 @@ async function runToolCalls(state, toolCalls, sink) {
445
447
  const runOne = async () => {
446
448
  const toolUi =
447
449
  name !== "download_file" && sink.startToolCall
448
- ? sink.startToolCall(`⚙ ${name}(${summary})`, { collapsible: true })
450
+ ? sink.startToolCall(`⚙ ${name}(${summary})`, { collapsible: true, toolIdx: i })
449
451
  : null;
450
452
  if (!toolUi && name !== "download_file") {
451
453
  sink.log("tool", `⚙ ${name}(${summary})`);
@@ -453,6 +455,24 @@ async function runToolCalls(state, toolCalls, sink) {
453
455
  if (name === "download_file") {
454
456
  state.isDownloading = true;
455
457
  sink.setBusy("Downloading (commands paused)...");
458
+ } else if (name === "write_file" || name === "edit_file" || name === "multi_edit") {
459
+ const target = parsedArgs.path ? parsedArgs.path.split("/").pop() : "";
460
+ sink.setBusy(`Writing ${target || "file"}...`);
461
+ // Populate write stats for the live TUI write indicator.
462
+ if (toolUi && toolUi.startWrite) {
463
+ const writeContent =
464
+ typeof parsedArgs.content === "string"
465
+ ? parsedArgs.content
466
+ : typeof parsedArgs.replacement === "string"
467
+ ? parsedArgs.replacement
468
+ : "";
469
+ toolUi.startWrite({ filePath: parsedArgs.path || "", content: writeContent });
470
+ }
471
+ } else if (name === "read_file" || name === "glob_files" || name === "grep_files") {
472
+ const target = parsedArgs.path ? parsedArgs.path.split("/").pop() : "";
473
+ sink.setBusy(`Reading ${target || "code"}...`);
474
+ } else {
475
+ sink.setBusy(`Running ${name}...`);
456
476
  }
457
477
  try {
458
478
  const out = await executeTool(
@@ -547,7 +567,11 @@ async function runAgentTurn(state, userText, sink, options = {}) {
547
567
  .slice(0, 60);
548
568
  if (cleanTitle) {
549
569
  state.session.title = cleanTitle;
550
- if (/^session-\d{8}-\d{6}-[a-z0-9]+$/i.test(state.session.id) && state.paths) {
570
+ // Match any auto-generated session ID pattern:
571
+ // compact: session-20261119-102809-6a3
572
+ // iso-like: session-2026-11-19-10-28-09-6a3
573
+ const isAutoId = /^session-[\d][\d-]{6,}-[a-z0-9]{2,8}$/i.test(state.session.id);
574
+ if (isAutoId && state.paths) {
551
575
  const nextId = suggestSessionIdFromPrompt(userText, state.paths);
552
576
  if (state.noSession) {
553
577
  state.session.id = nextId;
@@ -576,7 +600,7 @@ async function runAgentTurn(state, userText, sink, options = {}) {
576
600
  state.activeAbort = turnAbort;
577
601
 
578
602
  try {
579
- const maxSteps = Math.max(1, Number(state.settings.maxToolSteps) || 25);
603
+ const maxSteps = Math.max(1, Number(state.settings.maxToolSteps) || 100);
580
604
  const loopDetector = new LoopDetector(3);
581
605
  for (let step = 0; step < maxSteps; step++) {
582
606
  if (turnAbort.signal.aborted) throw createAbortError();