kovence-cli 1.0.3 → 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.3",
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();
@@ -426,10 +429,70 @@ async function streamProviderTurn({
426
429
  });
427
430
  }
428
431
  const entry = toolMap.get(idx);
429
- 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
+ }
430
444
  if (d.function?.name) entry.function.name += d.function.name;
431
- 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);
432
494
  }
495
+ parser.push(deltaChunk);
433
496
  };
434
497
 
435
498
  const handleLine = (rawLine) => {
@@ -476,6 +539,7 @@ async function streamProviderTurn({
476
539
  const idx = json.index ?? 0;
477
540
  const entry = toolMap.get(idx);
478
541
  if (entry) entry.function.arguments += json.delta.partial_json;
542
+ pumpWriteChunk(idx, json.delta.partial_json);
479
543
  updateToolProgress();
480
544
  }
481
545
  }
@@ -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})`);
@@ -456,6 +458,16 @@ async function runToolCalls(state, toolCalls, sink) {
456
458
  } else if (name === "write_file" || name === "edit_file" || name === "multi_edit") {
457
459
  const target = parsedArgs.path ? parsedArgs.path.split("/").pop() : "";
458
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
+ }
459
471
  } else if (name === "read_file" || name === "glob_files" || name === "grep_files") {
460
472
  const target = parsedArgs.path ? parsedArgs.path.split("/").pop() : "";
461
473
  sink.setBusy(`Reading ${target || "code"}...`);
@@ -555,7 +567,11 @@ async function runAgentTurn(state, userText, sink, options = {}) {
555
567
  .slice(0, 60);
556
568
  if (cleanTitle) {
557
569
  state.session.title = cleanTitle;
558
- 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) {
559
575
  const nextId = suggestSessionIdFromPrompt(userText, state.paths);
560
576
  if (state.noSession) {
561
577
  state.session.id = nextId;
@@ -584,7 +600,7 @@ async function runAgentTurn(state, userText, sink, options = {}) {
584
600
  state.activeAbort = turnAbort;
585
601
 
586
602
  try {
587
- const maxSteps = Math.max(1, Number(state.settings.maxToolSteps) || 25);
603
+ const maxSteps = Math.max(1, Number(state.settings.maxToolSteps) || 100);
588
604
  const loopDetector = new LoopDetector(3);
589
605
  for (let step = 0; step < maxSteps; step++) {
590
606
  if (turnAbort.signal.aborted) throw createAbortError();
package/src/cli/sinks.js CHANGED
@@ -1,8 +1,11 @@
1
1
  "use strict";
2
2
 
3
+ const fs = require("node:fs");
4
+ const path = require("node:path");
3
5
  const { AGENT_MODES, loadGlobalMemory } = require("../../store");
4
6
  const { C, promptLine, promptSecret, promptConfirm } = require("../../ui");
5
7
  const { getContextLabel } = require("../commands/handlers");
8
+ const { recordCheckpoint, undoLastCheckpoint } = require("../tools/checkpoints");
6
9
 
7
10
  function createPlainSink(interactive, { headless = false, jsonMode = false } = {}) {
8
11
  return {
@@ -126,6 +129,9 @@ function addTuiBanner(tui, state) {
126
129
  }
127
130
 
128
131
  function createTuiSink(tui, state) {
132
+ // Maps provider tool-index -> { block, toolName } for streaming write preview
133
+ const streamWriteBlocks = new Map();
134
+
129
135
  return {
130
136
  isTui: true,
131
137
  interactive: true,
@@ -141,7 +147,11 @@ function createTuiSink(tui, state) {
141
147
  addTuiBanner(tui, state);
142
148
  },
143
149
  setBusy(label) {
144
- tui.setStatus({ busyLabel: label, isBusy: Boolean(state.isBusy || label), queueLen: state.queue.length });
150
+ tui.setStatus({
151
+ busyLabel: label,
152
+ isBusy: Boolean(state.isBusy || label),
153
+ queueLen: state.queue?.length || 0,
154
+ });
145
155
  },
146
156
  syncStatus() {
147
157
  tui.setStatus({
@@ -169,6 +179,8 @@ function createTuiSink(tui, state) {
169
179
  }
170
180
  },
171
181
  startThinking(_prefix = "Kovence: ", initialLabel = "Thinking") {
182
+ // Clear per-turn write block registry so old indices don't bleed across turns.
183
+ streamWriteBlocks.clear();
172
184
  const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
173
185
  const dots = [" ", ". ", ".. ", "..."];
174
186
  let tick = 0;
@@ -270,20 +282,86 @@ function createTuiSink(tui, state) {
270
282
  },
271
283
  };
272
284
  },
273
- startToolCall(label, { collapsible = true, expanded = false } = {}) {
285
+ startToolCall(label, { collapsible = true, expanded = false, toolIdx = null } = {}) {
274
286
  const isWrite = /write_file|edit_file|multi_edit|apply_patch/.test(label);
275
287
  const isRead = /read_file|glob_files|grep_files/.test(label);
276
- const block = tui.addBlock("tool", label, {
277
- collapsible,
278
- expanded,
279
- details: [],
280
- statusLine: isWrite ? "writing..." : isRead ? "reading..." : "running...",
281
- });
288
+
289
+ // If preRegisterWriteBlock already created a block for this tool, reuse it
290
+ const preReg = toolIdx !== null ? streamWriteBlocks.get(toolIdx) : null;
291
+ const block = preReg?.preRegistered
292
+ ? preReg.block
293
+ : tui.addBlock("tool", label, {
294
+ collapsible,
295
+ expanded,
296
+ details: [],
297
+ statusLine: isWrite ? "writing..." : isRead ? "reading..." : "running...",
298
+ });
299
+ // Update label on reused block
300
+ if (preReg?.preRegistered) {
301
+ block.text = label;
302
+ block._cache = null;
303
+ }
304
+
282
305
  const details = [];
283
306
  let lastUpdateAt = 0;
307
+ if (toolIdx !== null && isWrite) {
308
+ if (!streamWriteBlocks.has(toolIdx)) {
309
+ streamWriteBlocks.set(toolIdx, { block, toolName: label });
310
+ }
311
+ // Replay any chunks that arrived before this block was created
312
+ const pending = streamWriteBlocks.get(`pending-${toolIdx}`);
313
+ if (pending && pending.chunks.length) {
314
+ streamWriteBlocks.delete(`pending-${toolIdx}`);
315
+ for (const ch of pending.chunks) {
316
+ this.onWriteStreamChunk(toolIdx, pending.toolName || label, pending.path || "", ch);
317
+ }
318
+ }
319
+ }
284
320
 
285
321
  return {
286
322
  block,
323
+ /**
324
+ * Called once at write start with { filePath, content }.
325
+ * Populates block.writeStats so the TUI can animate and show live stats.
326
+ */
327
+ startWrite({ filePath = "", content = "" } = {}) {
328
+ // If streaming already pre-populated writeStats, just update totals with
329
+ // the final known values and keep the live previewLines.
330
+ if (block.writeStats) {
331
+ const ws = block.writeStats;
332
+ const lines = String(content || "").split(/\r?\n/);
333
+ ws.filePath = String(filePath || ws.filePath || "");
334
+ ws.dir =
335
+ ws.dir ||
336
+ (filePath ? filePath.replace(/\\/g, "/").split("/").slice(0, -1).join("/") || "." : "");
337
+ ws.totalLines = lines.length;
338
+ ws.totalChars = content.length;
339
+ // Use streaming preview if it has content, else fall back to final content
340
+ if (!ws.previewLines.length && !ws.currentPreview?.length) {
341
+ ws.previewLines = lines.filter((l) => l.trim()).slice(-5);
342
+ ws.currentPreview = ws.previewLines;
343
+ }
344
+ block._ver = (block._ver || 0) + 1;
345
+ block._cache = null;
346
+ tui.scheduleRender();
347
+ return;
348
+ }
349
+ const lines = String(content || "").split(/\r?\n/);
350
+ const dir = filePath ? filePath.replace(/\\/g, "/").split("/").slice(0, -1).join("/") || "." : "";
351
+ block.writeStats = {
352
+ filePath: String(filePath || ""),
353
+ dir: String(dir),
354
+ totalLines: lines.length,
355
+ totalChars: content.length,
356
+ startTime: Date.now(),
357
+ // 5-line rolling preview (last 5 non-blank lines)
358
+ previewLines: lines.filter((l) => l.trim()).slice(-5),
359
+ done: false,
360
+ };
361
+ block._ver = (block._ver || 0) + 1;
362
+ block._cache = null;
363
+ tui.scheduleRender();
364
+ },
287
365
  pushOutput(rawChunk) {
288
366
  const cleaned = String(rawChunk || "")
289
367
  .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, "")
@@ -316,6 +394,8 @@ function createTuiSink(tui, state) {
316
394
  }
317
395
  },
318
396
  finish(fullOutputText = "", isError = false) {
397
+ // Mark write as done so animation stops.
398
+ if (block.writeStats) block.writeStats.done = true;
319
399
  if (!details.length && fullOutputText) {
320
400
  const fallbackLines = String(fullOutputText)
321
401
  .split(/\r?\n/)
@@ -331,6 +411,291 @@ function createTuiSink(tui, state) {
331
411
  },
332
412
  };
333
413
  },
414
+ /**
415
+ * Called by providers.js as soon as the file path is known during LLM streaming.
416
+ * Creates target directory and file beforehand, registers checkpoint, and pre-registers TUI block.
417
+ * @param {number} toolIdx - provider toolMap index
418
+ * @param {string} toolName - e.g. "write_file"
419
+ * @param {string} filePath - destination file path
420
+ */
421
+ preRegisterWriteBlock(toolIdx, toolName, filePath) {
422
+ let entry = streamWriteBlocks.get(toolIdx);
423
+ if (entry?.preRegistered && entry.filePath === filePath) return;
424
+
425
+ const workspaceRoot = state.workspaceRoot || process.cwd();
426
+ const absPath = filePath
427
+ ? path.isAbsolute(filePath)
428
+ ? filePath
429
+ : path.resolve(workspaceRoot, filePath)
430
+ : "";
431
+
432
+ let fileCreated = false;
433
+ if (toolName === "write_file" && state.settings?.agentMode !== "plan" && absPath) {
434
+ try {
435
+ const targetDir = path.dirname(absPath);
436
+ fs.mkdirSync(targetDir, { recursive: true });
437
+
438
+ if (state.paths) {
439
+ if (!state.streamCheckpointed) state.streamCheckpointed = new Set();
440
+ if (!state.streamCheckpointed.has(absPath)) {
441
+ recordCheckpoint({
442
+ sessionId: state.session?.id || "default",
443
+ toolName: "write_file",
444
+ filePaths: [absPath],
445
+ paths: state.paths,
446
+ });
447
+ state.streamCheckpointed.add(absPath);
448
+ }
449
+ }
450
+
451
+ fs.writeFileSync(absPath, "", "utf8");
452
+ fileCreated = true;
453
+ } catch {}
454
+ }
455
+
456
+ const fname = filePath ? filePath.replace(/\\/g, "/").split("/").pop() : "file";
457
+ const label = `⚙ ${toolName}(${fname})`;
458
+ const dir = filePath ? filePath.replace(/\\/g, "/").split("/").slice(0, -1).join("/") || "." : "";
459
+
460
+ if (!entry) {
461
+ const rawBlock = {
462
+ kind: "tool",
463
+ text: label,
464
+ collapsible: true,
465
+ expanded: false,
466
+ details: [],
467
+ statusLine: "writing...",
468
+ _ver: 1,
469
+ _cache: null,
470
+ };
471
+ rawBlock.writeStats = {
472
+ filePath: String(filePath || ""),
473
+ dir: String(dir),
474
+ totalLines: 0,
475
+ totalChars: 0,
476
+ startTime: Date.now(),
477
+ lineBuf: "",
478
+ previewLines: [],
479
+ done: false,
480
+ };
481
+ let insertAt = tui.blocks.length;
482
+ for (let i = tui.blocks.length - 1; i >= 0; i--) {
483
+ if (tui.blocks[i].kind === "thinking") {
484
+ insertAt = i + 1;
485
+ break;
486
+ }
487
+ }
488
+ tui.blocks.splice(insertAt, 0, rawBlock);
489
+ streamWriteBlocks.set(toolIdx, {
490
+ block: rawBlock,
491
+ toolName,
492
+ filePath,
493
+ absPath,
494
+ preRegistered: true,
495
+ fileCreated,
496
+ });
497
+ } else {
498
+ // If a *different* file is being written on the same toolIdx slot (sequential
499
+ // tool calls that reuse the same index), we must fully reset the entry and
500
+ // create a brand-new TUI block so the previous file's state doesn't leak.
501
+ const isDifferentFile = entry.filePath && entry.filePath !== filePath;
502
+ if (isDifferentFile) {
503
+ // Create a fresh TUI block for the new file
504
+ const rawBlock = {
505
+ kind: "tool",
506
+ text: label,
507
+ collapsible: true,
508
+ expanded: false,
509
+ details: [],
510
+ statusLine: "writing...",
511
+ _ver: 1,
512
+ _cache: null,
513
+ };
514
+ rawBlock.writeStats = {
515
+ filePath: String(filePath || ""),
516
+ dir: String(dir),
517
+ totalLines: 0,
518
+ totalChars: 0,
519
+ startTime: Date.now(),
520
+ lineBuf: "",
521
+ previewLines: [],
522
+ done: false,
523
+ };
524
+ let insertAt = tui.blocks.length;
525
+ for (let i = tui.blocks.length - 1; i >= 0; i--) {
526
+ if (tui.blocks[i].kind === "thinking") {
527
+ insertAt = i + 1;
528
+ break;
529
+ }
530
+ }
531
+ tui.blocks.splice(insertAt, 0, rawBlock);
532
+ streamWriteBlocks.set(toolIdx, {
533
+ block: rawBlock,
534
+ toolName,
535
+ filePath,
536
+ absPath,
537
+ preRegistered: true,
538
+ fileCreated,
539
+ });
540
+ } else {
541
+ entry.filePath = filePath;
542
+ entry.absPath = absPath;
543
+ entry.fileCreated = fileCreated || entry.fileCreated;
544
+ entry.block.text = label;
545
+ if (!entry.block.writeStats) {
546
+ entry.block.writeStats = {
547
+ filePath: String(filePath || ""),
548
+ dir: String(dir),
549
+ totalLines: 0,
550
+ totalChars: 0,
551
+ startTime: Date.now(),
552
+ previewLines: [],
553
+ done: false,
554
+ };
555
+ } else {
556
+ entry.block.writeStats.filePath = String(filePath || entry.block.writeStats.filePath || "");
557
+ entry.block.writeStats.dir = String(dir || entry.block.writeStats.dir || "");
558
+ }
559
+ entry.block._cache = null;
560
+ }
561
+ }
562
+ tui.scheduleRender();
563
+ },
564
+ /**
565
+ * Called by providers.js for each unescaped chunk while the LLM streams.
566
+ * Appends dynamically to the target file on disk and updates the TUI 5-line sliding preview.
567
+ * @param {number} toolIdx - provider's toolMap index
568
+ * @param {string} toolName - e.g. "write_file"
569
+ * @param {string} filePath - destination file path
570
+ * @param {string} unescapedChunk - unescaped content chunk from LLM stream
571
+ */
572
+ onWriteStreamChunk(toolIdx, toolName, filePath, unescapedChunk) {
573
+ let entry = streamWriteBlocks.get(toolIdx);
574
+ // If the entry exists but belongs to a different file (sequential tool calls
575
+ // that reuse the same slot index), re-register to create a fresh entry/block.
576
+ if (entry && filePath && entry.filePath && entry.filePath !== filePath) {
577
+ this.preRegisterWriteBlock(toolIdx, toolName, filePath);
578
+ entry = streamWriteBlocks.get(toolIdx);
579
+ }
580
+ if (!entry && filePath) {
581
+ this.preRegisterWriteBlock(toolIdx, toolName, filePath);
582
+ entry = streamWriteBlocks.get(toolIdx);
583
+ }
584
+ if (!entry) {
585
+ const pending = streamWriteBlocks.get(`pending-${toolIdx}`) || { chunks: [], path: filePath, toolName };
586
+ pending.chunks.push(unescapedChunk);
587
+ streamWriteBlocks.set(`pending-${toolIdx}`, pending);
588
+ return;
589
+ }
590
+
591
+ const { block } = entry;
592
+ const workspaceRoot = state.workspaceRoot || process.cwd();
593
+ const absPath =
594
+ entry.absPath ||
595
+ (filePath ? (path.isAbsolute(filePath) ? filePath : path.resolve(workspaceRoot, filePath)) : "");
596
+
597
+ // If write_file, ensure created in directory and dynamically append token chunks to the file
598
+ if (toolName === "write_file" && state.settings?.agentMode !== "plan" && absPath) {
599
+ try {
600
+ if (!entry.fileCreated) {
601
+ const targetDir = path.dirname(absPath);
602
+ fs.mkdirSync(targetDir, { recursive: true });
603
+ if (state.paths) {
604
+ if (!state.streamCheckpointed) state.streamCheckpointed = new Set();
605
+ if (!state.streamCheckpointed.has(absPath)) {
606
+ recordCheckpoint({
607
+ sessionId: state.session?.id || "default",
608
+ toolName: "write_file",
609
+ filePaths: [absPath],
610
+ paths: state.paths,
611
+ });
612
+ state.streamCheckpointed.add(absPath);
613
+ }
614
+ }
615
+ fs.writeFileSync(absPath, "", "utf8");
616
+ entry.fileCreated = true;
617
+ entry.absPath = absPath;
618
+ }
619
+ // Retry append once on transient FS errors (ENOENT, EBUSY, EMFILE)
620
+ try {
621
+ fs.appendFileSync(absPath, unescapedChunk, "utf8");
622
+ } catch (appendErr) {
623
+ if (appendErr.code === "ENOENT" || appendErr.code === "EBUSY" || appendErr.code === "EMFILE") {
624
+ // Re-create file if it disappeared, then retry
625
+ try {
626
+ if (!fs.existsSync(absPath)) {
627
+ fs.mkdirSync(path.dirname(absPath), { recursive: true });
628
+ fs.writeFileSync(absPath, "", "utf8");
629
+ }
630
+ fs.appendFileSync(absPath, unescapedChunk, "utf8");
631
+ } catch {
632
+ // Silently drop chunk — final write_file handler will write full content
633
+ }
634
+ }
635
+ }
636
+ } catch {}
637
+ }
638
+
639
+ if (!block.writeStats) {
640
+ block.writeStats = {
641
+ filePath: filePath || entry.filePath || "",
642
+ dir: filePath ? filePath.replace(/\\/g, "/").split("/").slice(0, -1).join("/") || "." : "",
643
+ totalLines: 0,
644
+ totalChars: 0,
645
+ startTime: Date.now(),
646
+ lineBuf: "",
647
+ previewLines: [],
648
+ done: false,
649
+ };
650
+ }
651
+ const ws = block.writeStats;
652
+ if (ws.done) return;
653
+
654
+ ws.totalChars += unescapedChunk.length;
655
+ ws.lineBuf = (ws.lineBuf || "") + unescapedChunk;
656
+ const parts = ws.lineBuf.split(/\r?\n/);
657
+ ws.lineBuf = parts.pop();
658
+ for (const p of parts) {
659
+ if (p.trim()) ws.previewLines.push(p);
660
+ ws.totalLines++;
661
+ }
662
+ if (ws.previewLines.length > 20) {
663
+ ws.previewLines = ws.previewLines.slice(-10);
664
+ }
665
+ // Real-time visible 5-line window of last written code with auto-scroll
666
+ const activeLines = [...ws.previewLines];
667
+ if (ws.lineBuf && ws.lineBuf.trim()) activeLines.push(ws.lineBuf);
668
+ ws.currentPreview = activeLines.slice(-5);
669
+ ws.totalLines = Math.max(ws.totalLines, activeLines.length);
670
+
671
+ block._ver = (block._ver || 0) + 1;
672
+ block._cache = null;
673
+ tui.scheduleRender();
674
+ },
675
+ onWriteStreamChunkEnd(_toolIdx, _toolName, _filePath) {
676
+ // Content stream finished for this tool
677
+ },
678
+ cleanupStreamWrite(toolIdx, revert = false) {
679
+ const entry = streamWriteBlocks.get(toolIdx);
680
+ if (!entry) return;
681
+ if (revert && entry.absPath && entry.fileCreated) {
682
+ const workspaceRoot = state.workspaceRoot || process.cwd();
683
+ if (state.paths && state.streamCheckpointed?.has(entry.absPath)) {
684
+ try {
685
+ undoLastCheckpoint(state.session?.id || "default", state.paths, workspaceRoot);
686
+ state.streamCheckpointed.delete(entry.absPath);
687
+ } catch {
688
+ try {
689
+ if (fs.existsSync(entry.absPath)) fs.rmSync(entry.absPath, { force: true });
690
+ } catch {}
691
+ }
692
+ } else {
693
+ try {
694
+ if (fs.existsSync(entry.absPath)) fs.rmSync(entry.absPath, { force: true });
695
+ } catch {}
696
+ }
697
+ }
698
+ },
334
699
  };
335
700
  }
336
701
 
@@ -37,6 +37,14 @@ const { generateProjectInitDoc } = require("../agent/project_context");
37
37
  const { undoLastCheckpoint } = require("../tools/checkpoints");
38
38
  const { getHelpText } = require("../cli/args");
39
39
 
40
+ function makeAutoSessionId() {
41
+ const d = new Date();
42
+ const pad = (n) => String(n).padStart(2, "0");
43
+ const stamp = `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
44
+ const rand = Math.random().toString(36).slice(2, 5);
45
+ return `session-${stamp}-${rand}`;
46
+ }
47
+
40
48
  function getEnvFallback() {
41
49
  return {
42
50
  baseUrl: String(process.env.LITELLM_BASE_URL || "").replace(/\/+$/, ""),
@@ -630,7 +638,7 @@ async function openSessionPicker(state, tui, sink, waitForMemorySync) {
630
638
  if (res.action === "select") {
631
639
  if (res.item.type === "new") {
632
640
  const rawName = (await tui.askModal("New session name (blank = auto): ", false)).trim();
633
- const id = rawName || `session-${new Date().toISOString().slice(11, 19).replace(/:/g, "")}`;
641
+ const id = rawName || makeAutoSessionId();
634
642
  await switchToSession(state, id, true, sink, waitForMemorySync);
635
643
  return;
636
644
  }
@@ -29,15 +29,32 @@ function findProjectRoot(cwd = process.cwd()) {
29
29
  }
30
30
 
31
31
  /**
32
- * Resolve all global (~/.config/kovence) and per-project (<project>/.kovence) paths.
32
+ * Resolve the global config directory in a cross-platform way.
33
+ *
34
+ * Priority (highest to lowest):
35
+ * 1. KOVENCE_CONFIG_DIR env var (always wins, any OS)
36
+ * 2. XDG_CONFIG_HOME/kovence (Linux/macOS with XDG override)
37
+ * 3. %APPDATA%\kovence (Windows — C:\Users\<user>\AppData\Roaming\kovence)
38
+ * 4. ~/.config/kovence (Linux/macOS default)
39
+ */
40
+ function resolveGlobalConfigDir() {
41
+ if (process.env.XDG_CONFIG_HOME) {
42
+ return path.join(process.env.XDG_CONFIG_HOME, "kovence");
43
+ }
44
+ if (process.platform === "win32") {
45
+ const appData = process.env.APPDATA || path.join(os.homedir(), "AppData", "Roaming");
46
+ return path.join(appData, "kovence");
47
+ }
48
+ return path.join(os.homedir(), ".config", "kovence");
49
+ }
50
+
51
+ /**
52
+ * Resolve all global and per-project paths.
33
53
  */
34
54
  function resolvePaths(options = {}) {
35
55
  const cwd = path.resolve(options.cwd || process.cwd());
36
56
  const projectRoot = path.resolve(options.projectRoot || findProjectRoot(cwd));
37
- const xdgConfig = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
38
- const globalDir = path.resolve(
39
- options.globalDir || process.env.KOVENCE_CONFIG_DIR || path.join(xdgConfig, "kovence")
40
- );
57
+ const globalDir = path.resolve(options.globalDir || process.env.KOVENCE_CONFIG_DIR || resolveGlobalConfigDir());
41
58
  const projectDir = path.resolve(options.projectDir || path.join(projectRoot, ".kovence"));
42
59
 
43
60
  return {
@@ -45,8 +62,10 @@ function resolvePaths(options = {}) {
45
62
  projectRoot,
46
63
  globalDir,
47
64
  projectDir,
48
- sessionsDir: path.join(projectDir, "sessions"),
49
- checkpointsDir: path.join(projectDir, "checkpoints"),
65
+ // Sessions and checkpoints are always global so data never scatters
66
+ // across different working directories.
67
+ sessionsDir: path.join(globalDir, "sessions"),
68
+ checkpointsDir: path.join(globalDir, "checkpoints"),
50
69
  commandsDir: path.join(projectDir, "commands"),
51
70
  settingsFile: path.join(globalDir, "settings.json"),
52
71
  providersFile: path.join(globalDir, "providers.json"),
@@ -55,7 +74,7 @@ function resolvePaths(options = {}) {
55
74
  inputHistoryFile: path.join(globalDir, "input_history.json"),
56
75
  projectMemoryFile: path.join(projectDir, "project_memory.json"),
57
76
  projectPermissionsFile: path.join(projectDir, "permissions.json"),
58
- migrationMarkerFile: path.join(projectDir, ".migrated_from_ai_harness"),
77
+ migrationMarkerFile: path.join(globalDir, ".migrated_from_ai_harness"),
59
78
  };
60
79
  }
61
80
 
@@ -85,8 +104,10 @@ function ensureGitInfoExclude(projectRoot) {
85
104
  */
86
105
  function ensureStorageDirs(paths) {
87
106
  fs.mkdirSync(paths.globalDir, { recursive: true, mode: 0o700 });
88
- fs.mkdirSync(paths.projectDir, { recursive: true });
89
107
  fs.mkdirSync(paths.sessionsDir, { recursive: true });
108
+ fs.mkdirSync(paths.checkpointsDir, { recursive: true });
109
+ // Only create projectDir when it already exists (avoid polluting random dirs).
110
+ // Commands dir is project-local and opt-in.
90
111
  ensureGitInfoExclude(paths.projectRoot);
91
112
  }
92
113
 
@@ -157,6 +157,40 @@ function deleteSession(id, paths = resolvePaths()) {
157
157
  return true;
158
158
  }
159
159
 
160
+ /**
161
+ * Delete session files whose `updatedAt` (or `createdAt`) timestamp is older than
162
+ * `retentionDays` days. Pass 0 (or null/undefined) to skip cleanup entirely.
163
+ * Returns the number of sessions deleted.
164
+ */
165
+ function cleanupOldSessions(retentionDays, paths = resolvePaths(), activeSessionId = "") {
166
+ const days = Number(retentionDays);
167
+ if (!Number.isFinite(days) || days <= 0) return 0;
168
+ ensureStorageDirs(paths);
169
+ if (!fs.existsSync(paths.sessionsDir)) return 0;
170
+ const cutoffMs = Date.now() - days * 24 * 60 * 60 * 1000;
171
+ let deleted = 0;
172
+ const files = fs.readdirSync(paths.sessionsDir).filter((f) => f.endsWith(".json"));
173
+ for (const f of files) {
174
+ const id = f.replace(/\.json$/, "");
175
+ if (id === activeSessionId) continue; // never delete current session
176
+ const full = path.join(paths.sessionsDir, f);
177
+ try {
178
+ const data = readJsonSafe(full, null);
179
+ const stamp = data?.updatedAt || data?.createdAt || "";
180
+ if (!stamp) continue;
181
+ const ts = new Date(stamp).getTime();
182
+ if (!Number.isFinite(ts)) continue;
183
+ if (ts < cutoffMs) {
184
+ fs.unlinkSync(full);
185
+ deleted++;
186
+ }
187
+ } catch {
188
+ // Non-fatal: skip unreadable file.
189
+ }
190
+ }
191
+ return deleted;
192
+ }
193
+
160
194
  function forkSession(sourceSession, newId, paths = resolvePaths()) {
161
195
  const cleanNewId = safeId(newId);
162
196
  if (!cleanNewId) throw new Error("Invalid fork session name.");
@@ -196,6 +230,7 @@ module.exports = {
196
230
  groupSessionsByDate,
197
231
  suggestSessionIdFromPrompt,
198
232
  deleteSession,
233
+ cleanupOldSessions,
199
234
  loadInputHistory,
200
235
  saveInputHistory,
201
236
  };
@@ -24,7 +24,7 @@ const DEFAULT_SETTINGS = {
24
24
  provider: "",
25
25
  toolsEnabled: true,
26
26
  autoSummarize: true,
27
- maxToolSteps: 25,
27
+ maxToolSteps: 100,
28
28
  maxHistoryMessages: 24,
29
29
  contextWindow: 128000,
30
30
  temperature: null,
@@ -38,6 +38,7 @@ const DEFAULT_SETTINGS = {
38
38
  notifications: true,
39
39
  colorScheme: "amber",
40
40
  systemPrompt: DEFAULT_SYSTEM_PROMPT,
41
+ chatHistoryRetentionDays: 30,
41
42
  };
42
43
 
43
44
  /**
@@ -98,8 +99,8 @@ const SETTINGS_SCHEMA = [
98
99
  label: "Max Tool Steps",
99
100
  type: "integer",
100
101
  min: 1,
101
- max: 100,
102
- description: "Maximum consecutive tool-calling loop iterations per user turn (1-100).",
102
+ max: 1000,
103
+ description: "Maximum consecutive tool-calling loop iterations per user turn (1-1000).",
103
104
  },
104
105
  {
105
106
  key: "maxHistoryMessages",
@@ -194,6 +195,15 @@ const SETTINGS_SCHEMA = [
194
195
  type: "multilineString",
195
196
  description: "Base system instructions injected at the start of every request (press Enter to edit).",
196
197
  },
198
+ {
199
+ key: "chatHistoryRetentionDays",
200
+ label: "Chat History Retention (Days)",
201
+ type: "nullableInteger",
202
+ min: 0,
203
+ max: 3650,
204
+ description:
205
+ "Auto-delete sessions older than N days on startup (0 = never delete). Default: 30. Set to 'null' to disable.",
206
+ },
197
207
  {
198
208
  key: "managePermissions",
199
209
  label: "Manage Permissions",
@@ -227,6 +237,9 @@ const KEY_ALIASES = {
227
237
  show_active_tasks: "showActiveTasks",
228
238
  color_scheme: "colorScheme",
229
239
  system_prompt: "systemPrompt",
240
+ chat_history_retention: "chatHistoryRetentionDays",
241
+ chat_history_retention_days: "chatHistoryRetentionDays",
242
+ retention_days: "chatHistoryRetentionDays",
230
243
  };
231
244
 
232
245
  const PERSISTABLE_KEYS = new Set(Object.keys(DEFAULT_SETTINGS));
package/store.js CHANGED
@@ -88,6 +88,8 @@ module.exports = {
88
88
  loadInputHistory: (paths = getDefaultPaths()) => sessionsMod.loadInputHistory(paths),
89
89
  saveInputHistory: (items, paths = getDefaultPaths()) => sessionsMod.saveInputHistory(items, paths),
90
90
  deleteSession: (id, paths = getDefaultPaths()) => sessionsMod.deleteSession(id, paths),
91
+ cleanupOldSessions: (retentionDays, paths = getDefaultPaths(), activeSessionId = "") =>
92
+ sessionsMod.cleanupOldSessions(retentionDays, paths, activeSessionId),
91
93
 
92
94
  // Permissions
93
95
  loadPermissionRules: permStoreMod.loadPermissionRules,
package/tools.js CHANGED
@@ -743,7 +743,7 @@ const TOOL_HANDLERS = {
743
743
  const abs = resolvePath(filePath, root);
744
744
  assertToolFileAccess(abs, "write_file", ctx);
745
745
  const real = resolveRealWithMissingLeaf(abs);
746
- if (ctx?.paths)
746
+ if (ctx?.paths && !ctx?.streamCheckpointed?.has(real) && !ctx?.streamCheckpointed?.has(abs))
747
747
  recordCheckpoint({
748
748
  sessionId: ctx.session?.id || "default",
749
749
  toolName: "write_file",
package/tui.js CHANGED
@@ -25,8 +25,46 @@ const {
25
25
  parseSettingValue,
26
26
  } = require("./src/tui/settings_panel");
27
27
 
28
- function copyToClipboardOsc52(text, stdout = process.stdout) {
28
+ const { spawnSync } = require("node:child_process");
29
+
30
+ /**
31
+ * Copy text to system clipboard.
32
+ * Strategy (in order):
33
+ * 1. wl-copy (Wayland)
34
+ * 2. xclip (X11)
35
+ * 3. xsel (X11 fallback)
36
+ * 4. pbcopy (macOS)
37
+ * 5. OSC 52 (terminal escape — only works in Kitty / iTerm2 / WezTerm)
38
+ */
39
+ function copyToClipboard(text, stdout = process.stdout) {
29
40
  if (!text) return false;
41
+
42
+ // Try system clipboard tools silently (no shell, no PATH-injection risk).
43
+ const candidates = [];
44
+ if (process.env.WAYLAND_DISPLAY) {
45
+ candidates.push({ cmd: "wl-copy", args: [] });
46
+ }
47
+ if (process.env.DISPLAY) {
48
+ candidates.push({ cmd: "xclip", args: ["-selection", "clipboard"] });
49
+ candidates.push({ cmd: "xsel", args: ["--clipboard", "--input"] });
50
+ }
51
+ candidates.push({ cmd: "pbcopy", args: [] }); // macOS
52
+
53
+ for (const { cmd, args } of candidates) {
54
+ try {
55
+ const result = spawnSync(cmd, args, {
56
+ input: text,
57
+ encoding: "utf8",
58
+ stdio: ["pipe", "ignore", "ignore"],
59
+ timeout: 1000,
60
+ });
61
+ if (result.status === 0) return true;
62
+ } catch {
63
+ // Not found or failed — try next.
64
+ }
65
+ }
66
+
67
+ // OSC 52 fallback (terminal must support it).
30
68
  const b64 = Buffer.from(text, "utf8").toString("base64");
31
69
  stdout.write(`\x1b]52;c;${b64}\x07`);
32
70
  return true;
@@ -38,7 +76,7 @@ function styleInlineMarkdown(line, ansi) {
38
76
  .replace(/\*\*([^*]+)\*\*/g, `${ansi.bold}${ansi.amber}$1${ansi.reset}${ansi.white}`);
39
77
  }
40
78
 
41
- function formatAssistantLines(text, innerW, ansi, isStreaming = false) {
79
+ function formatAssistantLines(text, innerW, ansi, isStreaming = false, animTick = 0) {
42
80
  const out = [];
43
81
  const rawLines = String(text || "").split(/\r?\n/);
44
82
  let inCode = false;
@@ -76,10 +114,16 @@ function formatAssistantLines(text, innerW, ansi, isStreaming = false) {
76
114
  }
77
115
 
78
116
  if (isStreaming) {
117
+ // Animated braille spinner — 6 frames cycling every render tick.
118
+ const SPIN = ["⠇", "⠋", "⠙", "⠸", "⠴", "⠦"];
119
+ const dot = SPIN[animTick % SPIN.length];
79
120
  if (inCode) {
80
- out.push(` ${ansi.gray}│ ${ansi.amber}${ansi.dim}writing... ▌${ansi.reset}`);
121
+ out.push(` ${ansi.gray}│ ${ansi.amber}${ansi.dim}${dot} writing...${ansi.reset}`);
81
122
  } else if (!text || text.endsWith("\n")) {
82
- out.push(` ${ansi.orange}┃ ${ansi.amber}${ansi.dim}writing... ▌${ansi.reset}`);
123
+ out.push(` ${ansi.orange}┃ ${ansi.amber}${ansi.dim}${dot} writing...${ansi.reset}`);
124
+ } else {
125
+ // Mid-line: append animated dot inline
126
+ out[out.length - 1] = (out[out.length - 1] || "") + ` ${ansi.dim}${dot}${ansi.reset}`;
83
127
  }
84
128
  }
85
129
 
@@ -232,6 +276,10 @@ class KovenceTUI {
232
276
  this.onKey = this.onKey.bind(this);
233
277
  this.onRawData = this.onRawData.bind(this);
234
278
  this.onResize = () => this.scheduleRender();
279
+
280
+ // Spinner/animation tick — increments every 150 ms while active.
281
+ this.animTick = 0;
282
+ this._animTimer = null;
235
283
  }
236
284
 
237
285
  getPalette() {
@@ -266,7 +314,7 @@ class KovenceTUI {
266
314
  this.flashNotice("No AI response to copy yet");
267
315
  return false;
268
316
  }
269
- copyToClipboardOsc52(lastAi.text, this.stdout);
317
+ copyToClipboard(lastAi.text, this.stdout);
270
318
  this.flashNotice(`Copied last response (${lastAi.text.length} chars)`);
271
319
  return true;
272
320
  }
@@ -392,7 +440,7 @@ class KovenceTUI {
392
440
  }
393
441
  const text = this.extractSelectedText();
394
442
  if (text) {
395
- copyToClipboardOsc52(text, this.stdout);
443
+ copyToClipboard(text, this.stdout);
396
444
  this.flashNotice(`Copied ${text.length} chars to clipboard`);
397
445
  }
398
446
  this.scheduleRender();
@@ -526,6 +574,23 @@ class KovenceTUI {
526
574
  this.stdin.on("data", this.onRawData);
527
575
  }
528
576
  this.stdout.on("resize", this.onResize);
577
+ // Start animation timer for spinner/dot animation.
578
+ this._animTimer = setInterval(() => {
579
+ this.animTick++;
580
+ // Re-render if there is an active write block OR a streaming assistant block.
581
+ const hasActive = this.blocks.some((b) => (b.writeStats && !b.writeStats.done) || b._streaming);
582
+ if (hasActive) {
583
+ // Invalidate cache for all animated blocks so spinner dots re-render.
584
+ for (const b of this.blocks) {
585
+ if ((b.writeStats && !b.writeStats.done) || b._streaming) {
586
+ b._ver = (b._ver || 0) + 1;
587
+ b._cache = null;
588
+ }
589
+ }
590
+ this.scheduleRender();
591
+ }
592
+ }, 150);
593
+ this._animTimer.unref?.();
529
594
  this.render();
530
595
  }
531
596
 
@@ -545,6 +610,10 @@ class KovenceTUI {
545
610
  this.stdin.setRawMode(false);
546
611
  } catch {}
547
612
  }
613
+ if (this._animTimer) {
614
+ clearInterval(this._animTimer);
615
+ this._animTimer = null;
616
+ }
548
617
  this.stdout.write(CONTROL_SEQ.keysOff + CONTROL_SEQ.mouseOff + CONTROL_SEQ.showCur + CONTROL_SEQ.altOff);
549
618
  }
550
619
 
@@ -693,7 +762,9 @@ class KovenceTUI {
693
762
  blockLines.push("");
694
763
  } else if (b.kind === "assistant") {
695
764
  blockLines.push(` ${ansi.orange}${ansi.bold}◆ KOVENCE CLI${ansi.reset}`);
696
- blockLines.push(...formatAssistantLines(b.text, innerW, ansi, Boolean(b._streaming)));
765
+ blockLines.push(
766
+ ...formatAssistantLines(b.text, innerW, ansi, Boolean(b._streaming), this.animTick)
767
+ );
697
768
  } else if (b.kind === "thinking") {
698
769
  blockLines.push(` ${ansi.orange}${ansi.bold}◆ KOVENCE CLI${ansi.reset}`);
699
770
  for (const wl of wrapped) {
@@ -701,8 +772,27 @@ class KovenceTUI {
701
772
  }
702
773
  } else if (b.kind === "tool") {
703
774
  if (b.collapsible) {
775
+ const ws = b.writeStats;
776
+ // Show write stats always (even after done) as a summary.
777
+ // isActiveWrite controls the spinner animation only.
778
+ const hasWriteStats = Boolean(ws);
779
+ const isActiveWrite = ws && !ws.done;
780
+
781
+ // --- Animated write indicator dots ---
782
+ // DOT_FRAMES cycles through 4 states every 150 ms (animTick steps each interval).
783
+ const DOT_FRAMES = ["⠇", "⠋", "⠙", "⠸", "⠴", "⠦"];
784
+ const dot = DOT_FRAMES[this.animTick % DOT_FRAMES.length];
785
+
704
786
  const arrow = b.expanded ? "▾" : "▸";
705
- const hint = b.expanded ? " (click to hide)" : " (click for live details)";
787
+ // For active writes, show expand toggle; for others, show generic hint.
788
+ const hint = hasWriteStats
789
+ ? b.expanded
790
+ ? " (click or Ctrl+O to collapse)"
791
+ : " ▸ expand for live preview"
792
+ : b.expanded
793
+ ? " (click or Ctrl+O to hide)"
794
+ : " (click for live details)";
795
+
706
796
  for (let i = 0; i < wrapped.length; i++) {
707
797
  const wl = wrapped[i];
708
798
  if (i === 0) {
@@ -714,7 +804,46 @@ class KovenceTUI {
714
804
  }
715
805
  }
716
806
  const detailW = Math.max(12, innerW - 6);
717
- if (b.expanded) {
807
+
808
+ if (hasWriteStats) {
809
+ // --- Stats line: spinner (if active) or ✓ (if done) + lines + tokens + speed ---
810
+ const elapsedSec = Math.max(0.1, (Date.now() - ws.startTime) / 1000);
811
+ // Rough token estimate: ~4 chars per token.
812
+ const tokEst = Math.round(ws.totalChars / 4);
813
+ const tokSec = Math.round(tokEst / elapsedSec);
814
+ const statusIcon = isActiveWrite ? dot : "✓";
815
+ const statsLine = `${statusIcon} ${ws.totalLines} lines · ~${tokEst} tokens · ${tokSec} tok/s`;
816
+ blockLines.push(
817
+ ` ${ansi.gray}│ ${ansi.amber}${clipToWidth(statsLine, detailW)}${ansi.reset}`
818
+ );
819
+
820
+ if (b.expanded) {
821
+ // Live Path line
822
+ const livePath = ws.filePath || (ws.dir ? `${ws.dir}/` : "");
823
+ if (livePath) {
824
+ const pathLine = `📄 Live Path: ${livePath}`;
825
+ blockLines.push(
826
+ ` ${ansi.gray}│ ${ansi.dim}${ansi.gray}${clipToWidth(pathLine, detailW)}${ansi.reset}`
827
+ );
828
+ }
829
+ // 5-line window of last written code (auto-scroll: always last 5 lines)
830
+ const preview = (ws.currentPreview || ws.previewLines || []).slice(-5);
831
+ if (preview.length) {
832
+ blockLines.push(
833
+ ` ${ansi.gray}│ ${ansi.dim}${ansi.gray}${"─".repeat(Math.min(detailW, 40))}${ansi.reset}`
834
+ );
835
+ for (const pl of preview) {
836
+ blockLines.push(
837
+ ` ${ansi.gray}│ ${ansi.dim}${ansi.gray}${clipToWidth(pl, detailW)}${ansi.reset}`
838
+ );
839
+ }
840
+ } else {
841
+ blockLines.push(
842
+ ` ${ansi.gray}│ ${ansi.dim}${ansi.gray}${clipToWidth("… waiting for written tokens …", detailW)}${ansi.reset}`
843
+ );
844
+ }
845
+ }
846
+ } else if (b.expanded) {
718
847
  const visDetails = (b.details || []).slice(-16);
719
848
  if (!visDetails.length) {
720
849
  const emptyMsg = b.statusLine || "… waiting for live command output …";
package/ui.js CHANGED
@@ -82,7 +82,7 @@ const SUBCOMMAND_HINTS = {
82
82
  { fill: "/set nonWorkspaceAccess ", desc: "ask | allow | deny" },
83
83
  { fill: "/set toolsEnabled ", desc: "true | false" },
84
84
  { fill: "/set autoSummarize ", desc: "true | false" },
85
- { fill: "/set maxToolSteps ", desc: "integer 1-100 (default 25)" },
85
+ { fill: "/set maxToolSteps ", desc: "integer 1-1000 (default 100)" },
86
86
  { fill: "/set maxHistoryMessages ", desc: "integer 2-500 (default 24)" },
87
87
  { fill: "/set contextWindow ", desc: "integer >= 1024 (default 128000)" },
88
88
  { fill: "/set temperature ", desc: "0.0-2.0 | null" },