kovence-cli 1.2.0 → 1.3.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/src/cli/args.js CHANGED
@@ -26,6 +26,7 @@ function parseArgs(argv) {
26
26
  json: false,
27
27
  noSession: false,
28
28
  debug: false,
29
+ logRequests: "",
29
30
  doctor: false,
30
31
  help: false,
31
32
  version: false,
@@ -100,6 +101,9 @@ function parseArgs(argv) {
100
101
  } else if (a === "--new-session") {
101
102
  opts.newSession = takeValue(i, a);
102
103
  i++;
104
+ } else if (a === "--log-requests") {
105
+ opts.logRequests = takeValue(i, a);
106
+ i++;
103
107
  } else if (a.startsWith("-")) {
104
108
  throw new Error(`Unknown option '${a}'. Run with --help to see supported flags.`);
105
109
  } else {
@@ -132,6 +136,7 @@ CLI Options:
132
136
  --json Emit structured JSON result in -p headless mode
133
137
  --no-session Run without persisting session history to disk
134
138
  --debug Enable verbose debug tracing
139
+ --log-requests <file> Write scrubbed outgoing request bodies as JSONL
135
140
  doctor Run environment, tools & provider connectivity checks
136
141
  -t, --temp <num> Sampling temperature (0.0-2.0)
137
142
  --max-tokens <num> Max completion tokens
@@ -147,7 +152,10 @@ Harness Commands:
147
152
  /settings Open interactive Settings panel (Ctrl+,)
148
153
  /set <key> <value> Update persisted setting directly
149
154
  /api [subcmd] Open provider picker or list/add/use/rm
150
- /model [name] Open model picker or switch & save model
155
+ /model [name] Open model & reasoning picker or switch & save model
156
+ /reasoning [level] Pick reasoning level (off|low|medium|high)
157
+ /skills [subcmd] Manage markdown skills (list|add <file>|show|rm)
158
+ /browser [subcmd] Manage headless Playwright runtime (status|install|close)
151
159
  /sessions [subcmd] Open session picker (Ctrl+S) or list/new/switch/delete
152
160
  /new [name] Create fresh isolated session (Ctrl+N)
153
161
  /save <name> Rename and save current session
package/src/cli/sinks.js CHANGED
@@ -86,6 +86,29 @@ function createPlainSink(interactive, { headless = false, jsonMode = false } = {
86
86
  confirm: (label) => (interactive ? promptConfirm(`${C.yellow}${label}${C.reset}`) : Promise.resolve("n")),
87
87
  askPrompt: (label) => (interactive ? promptLine(label, []) : Promise.resolve("")),
88
88
  askPassword: interactive ? (label) => promptSecret(label) : null,
89
+ async openMultiChoicePicker(title, items = []) {
90
+ if (!interactive || !items.length) return [];
91
+ const selectable = items.filter((x) => x.type !== "header" && x.type !== "skip");
92
+ if (!selectable.length) return [];
93
+ console.log(`\n${C.bold}${C.cyan}${title}${C.reset}`);
94
+ selectable.forEach((it, idx) => {
95
+ console.log(` ${idx + 1}. ${it.label}${it.desc ? ` — ${C.dim}${it.desc}${C.reset}` : ""}`);
96
+ });
97
+ const ans = (await promptLine("Select skill(s) (e.g. 1,2 or 'all', Enter to skip): ", []))
98
+ .trim()
99
+ .toLowerCase();
100
+ if (!ans || ans === "skip" || ans === "none" || ans === "0") return [];
101
+ if (ans === "all" || ans === "*") return selectable.map((x) => x.id);
102
+ const chosen = [];
103
+ for (const part of ans.split(/[\s,]+/)) {
104
+ const n = Number.parseInt(part, 10);
105
+ if (Number.isInteger(n) && n >= 1 && n <= selectable.length) {
106
+ const id = selectable[n - 1].id;
107
+ if (!chosen.includes(id)) chosen.push(id);
108
+ }
109
+ }
110
+ return chosen;
111
+ },
89
112
  startProgress(initialText = "") {
90
113
  if (jsonMode || headless || !process.stdout.isTTY) {
91
114
  return { update() {}, done() {} };
@@ -161,6 +184,7 @@ function createTuiSink(tui, state) {
161
184
  model: state.model,
162
185
  ctxText: getContextLabel(state),
163
186
  agentMode: state.settings.agentMode,
187
+ reasoning: state.settings.reasoning || "off",
164
188
  colorScheme: state.settings.colorScheme || "amber",
165
189
  tools: state.settings.toolsEnabled,
166
190
  auto: state.settings.agentMode === "auto",
@@ -248,6 +272,18 @@ function createTuiSink(tui, state) {
248
272
  });
249
273
  return res?.action === "select" ? res.item?.id || "" : "";
250
274
  },
275
+ async openMultiChoicePicker(title, items, preselectedIds = []) {
276
+ if (!items || !items.length) return [];
277
+ const res = await tui.openPicker(title, items, {
278
+ initialIdx: 0,
279
+ multiSelect: true,
280
+ selectedIds: new Set(preselectedIds),
281
+ hint: "↑/↓ move · Space toggle [✓] · a all · Enter apply · Esc skip",
282
+ });
283
+ if (res?.action === "multi") return Array.isArray(res.ids) ? res.ids : [];
284
+ if (res?.action === "select" && res.item?.id && res.item.type !== "skip") return [res.item.id];
285
+ return [];
286
+ },
251
287
  async openModePicker(currentMode) {
252
288
  const modeMeta = [
253
289
  { id: "default", desc: "Ask confirmation for file edits, downloads & commands" },
@@ -354,6 +390,7 @@ function createTuiSink(tui, state) {
354
390
  totalLines: lines.length,
355
391
  totalChars: content.length,
356
392
  startTime: Date.now(),
393
+ firstChunkAt: null,
357
394
  // 5-line rolling preview (last 5 non-blank lines)
358
395
  previewLines: lines.filter((l) => l.trim()).slice(-5),
359
396
  done: false,
@@ -395,7 +432,10 @@ function createTuiSink(tui, state) {
395
432
  },
396
433
  finish(fullOutputText = "", isError = false) {
397
434
  // Mark write as done so animation stops.
398
- if (block.writeStats) block.writeStats.done = true;
435
+ if (block.writeStats) {
436
+ block.writeStats.done = true;
437
+ block.writeStats.doneAt = Date.now();
438
+ }
399
439
  if (!details.length && fullOutputText) {
400
440
  const fallbackLines = String(fullOutputText)
401
441
  .split(/\r?\n/)
@@ -411,6 +451,44 @@ function createTuiSink(tui, state) {
411
451
  },
412
452
  };
413
453
  },
454
+ startSubagent({ agent = "explore", description = "task" } = {}) {
455
+ const baseLabel = `task(${agent}): ${description}`;
456
+ const block = tui.addBlock("tool", baseLabel, {
457
+ collapsible: true,
458
+ expanded: false,
459
+ details: [],
460
+ statusLine: "starting...",
461
+ });
462
+ let lastRenderAt = 0;
463
+ const formatStatus = (toolCalls, elapsedMs, suffix = "") => {
464
+ const sec = Math.max(0, Math.round((elapsedMs || 0) / 1000));
465
+ const base = `${baseLabel} - ${toolCalls || 0} tool calls - ${sec}s`;
466
+ return suffix ? `${base} (${suffix})` : base;
467
+ };
468
+ return {
469
+ update({ toolCalls = 0, elapsedMs = 0 } = {}) {
470
+ const now = Date.now();
471
+ if (now - lastRenderAt < 250) return;
472
+ lastRenderAt = now;
473
+ const text = formatStatus(toolCalls, elapsedMs);
474
+ block.text = text;
475
+ block.statusLine = `${toolCalls} tool calls · ${Math.round(elapsedMs / 1000)}s`;
476
+ block._cache = null;
477
+ tui.scheduleRender();
478
+ },
479
+ finish({ ok = true, toolCalls = 0, elapsedMs = 0, error = "" } = {}) {
480
+ const text = formatStatus(toolCalls, elapsedMs, ok ? "done" : error || "failed");
481
+ block.text = `${ok ? "✓" : "✗"} ${text}`;
482
+ block.statusLine = ok ? "done" : error || "failed";
483
+ block._cache = null;
484
+ tui.setBlockDetails(
485
+ block,
486
+ ok ? [`Completed in ${(elapsedMs / 1000).toFixed(1)}s`] : [String(error)],
487
+ block.statusLine
488
+ );
489
+ },
490
+ };
491
+ },
414
492
  /**
415
493
  * Called by providers.js as soon as the file path is known during LLM streaming.
416
494
  * Creates target directory and file beforehand, registers checkpoint, and pre-registers TUI block.
@@ -420,7 +498,7 @@ function createTuiSink(tui, state) {
420
498
  */
421
499
  preRegisterWriteBlock(toolIdx, toolName, filePath) {
422
500
  let entry = streamWriteBlocks.get(toolIdx);
423
- if (entry?.preRegistered && entry.filePath === filePath) return;
501
+ if (entry?.preRegistered && entry.filePath === filePath && !entry.block?.writeStats?.done) return;
424
502
 
425
503
  const workspaceRoot = state.workspaceRoot || process.cwd();
426
504
  const absPath = filePath
@@ -430,7 +508,10 @@ function createTuiSink(tui, state) {
430
508
  : "";
431
509
 
432
510
  let fileCreated = false;
433
- if (toolName === "write_file" && state.settings?.agentMode !== "plan" && absPath) {
511
+ const blockedByReadTracker = Boolean(
512
+ absPath && fs.existsSync(absPath) && state.readTracker && !state.readTracker.isFresh(absPath)
513
+ );
514
+ if (toolName === "write_file" && state.settings?.agentMode !== "plan" && absPath && !blockedByReadTracker) {
434
515
  try {
435
516
  const targetDir = path.dirname(absPath);
436
517
  fs.mkdirSync(targetDir, { recursive: true });
@@ -453,11 +534,16 @@ function createTuiSink(tui, state) {
453
534
  } catch {}
454
535
  }
455
536
 
456
- const fname = filePath ? filePath.replace(/\\/g, "/").split("/").pop() : "file";
537
+ const fname = filePath ? filePath.replace(/\\/g, "/").split("/").pop() : "...";
457
538
  const label = `⚙ ${toolName}(${fname})`;
458
539
  const dir = filePath ? filePath.replace(/\\/g, "/").split("/").slice(0, -1).join("/") || "." : "";
459
540
 
460
- if (!entry) {
541
+ const shouldCreateFresh =
542
+ !entry ||
543
+ Boolean(entry.block?.writeStats?.done) ||
544
+ Boolean(entry.filePath && filePath && entry.filePath !== filePath);
545
+
546
+ if (shouldCreateFresh) {
461
547
  const rawBlock = {
462
548
  kind: "tool",
463
549
  text: label,
@@ -474,6 +560,7 @@ function createTuiSink(tui, state) {
474
560
  totalLines: 0,
475
561
  totalChars: 0,
476
562
  startTime: Date.now(),
563
+ firstChunkAt: null,
477
564
  lineBuf: "",
478
565
  previewLines: [],
479
566
  done: false,
@@ -493,71 +580,43 @@ function createTuiSink(tui, state) {
493
580
  absPath,
494
581
  preRegistered: true,
495
582
  fileCreated,
583
+ pendingDiskChunks: [],
496
584
  });
497
585
  } 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 = {
586
+ entry.filePath = filePath || entry.filePath;
587
+ entry.absPath = absPath || entry.absPath;
588
+ entry.fileCreated = fileCreated || entry.fileCreated;
589
+ if (filePath) entry.block.text = label;
590
+ if (!entry.block.writeStats) {
591
+ entry.block.writeStats = {
515
592
  filePath: String(filePath || ""),
516
593
  dir: String(dir),
517
594
  totalLines: 0,
518
595
  totalChars: 0,
519
596
  startTime: Date.now(),
597
+ firstChunkAt: null,
520
598
  lineBuf: "",
521
599
  previewLines: [],
522
600
  done: false,
523
601
  };
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
602
  } 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;
603
+ entry.block.writeStats.filePath = String(filePath || entry.block.writeStats.filePath || "");
604
+ entry.block.writeStats.dir = String(dir || entry.block.writeStats.dir || "");
560
605
  }
606
+ // Backfill any content chunks streamed before `path` arrived
607
+ if (
608
+ entry.fileCreated &&
609
+ entry.absPath &&
610
+ Array.isArray(entry.pendingDiskChunks) &&
611
+ entry.pendingDiskChunks.length > 0
612
+ ) {
613
+ try {
614
+ fs.appendFileSync(entry.absPath, entry.pendingDiskChunks.join(""), "utf8");
615
+ entry.pendingDiskChunks = [];
616
+ } catch {}
617
+ }
618
+ entry.block._ver = (entry.block._ver || 0) + 1;
619
+ entry.block._cache = null;
561
620
  }
562
621
  tui.scheduleRender();
563
622
  },
@@ -571,22 +630,16 @@ function createTuiSink(tui, state) {
571
630
  */
572
631
  onWriteStreamChunk(toolIdx, toolName, filePath, unescapedChunk) {
573
632
  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);
633
+ // Create block IMMEDIATELY even when content arrives before `path` (filePath === "")
634
+ if (
635
+ !entry ||
636
+ (filePath && entry.filePath && entry.filePath !== filePath) ||
637
+ entry.block?.writeStats?.done
638
+ ) {
639
+ this.preRegisterWriteBlock(toolIdx, toolName, filePath || "");
578
640
  entry = streamWriteBlocks.get(toolIdx);
579
641
  }
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
- }
642
+ if (!entry) return;
590
643
 
591
644
  const { block } = entry;
592
645
  const workspaceRoot = state.workspaceRoot || process.cwd();
@@ -595,45 +648,61 @@ function createTuiSink(tui, state) {
595
648
  (filePath ? (path.isAbsolute(filePath) ? filePath : path.resolve(workspaceRoot, filePath)) : "");
596
649
 
597
650
  // 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)
651
+ const blockedByReadTracker = Boolean(
652
+ absPath &&
653
+ !entry.fileCreated &&
654
+ fs.existsSync(absPath) &&
655
+ state.readTracker &&
656
+ !state.readTracker.isFresh(absPath)
657
+ );
658
+ if (toolName === "write_file" && state.settings?.agentMode !== "plan" && !blockedByReadTracker) {
659
+ if (!absPath) {
660
+ if (!Array.isArray(entry.pendingDiskChunks)) entry.pendingDiskChunks = [];
661
+ entry.pendingDiskChunks.push(unescapedChunk);
662
+ } else {
620
663
  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");
664
+ if (!entry.fileCreated) {
665
+ const targetDir = path.dirname(absPath);
666
+ fs.mkdirSync(targetDir, { recursive: true });
667
+ if (state.paths) {
668
+ if (!state.streamCheckpointed) state.streamCheckpointed = new Set();
669
+ if (!state.streamCheckpointed.has(absPath)) {
670
+ recordCheckpoint({
671
+ sessionId: state.session?.id || "default",
672
+ toolName: "write_file",
673
+ filePaths: [absPath],
674
+ paths: state.paths,
675
+ });
676
+ state.streamCheckpointed.add(absPath);
629
677
  }
630
- fs.appendFileSync(absPath, unescapedChunk, "utf8");
631
- } catch {
632
- // Silently drop chunk — final write_file handler will write full content
678
+ }
679
+ fs.writeFileSync(absPath, "", "utf8");
680
+ entry.fileCreated = true;
681
+ entry.absPath = absPath;
682
+ if (Array.isArray(entry.pendingDiskChunks) && entry.pendingDiskChunks.length > 0) {
683
+ fs.appendFileSync(absPath, entry.pendingDiskChunks.join(""), "utf8");
684
+ entry.pendingDiskChunks = [];
633
685
  }
634
686
  }
635
- }
636
- } catch {}
687
+ try {
688
+ fs.appendFileSync(absPath, unescapedChunk, "utf8");
689
+ } catch (appendErr) {
690
+ if (
691
+ appendErr.code === "ENOENT" ||
692
+ appendErr.code === "EBUSY" ||
693
+ appendErr.code === "EMFILE"
694
+ ) {
695
+ try {
696
+ if (!fs.existsSync(absPath)) {
697
+ fs.mkdirSync(path.dirname(absPath), { recursive: true });
698
+ fs.writeFileSync(absPath, "", "utf8");
699
+ }
700
+ fs.appendFileSync(absPath, unescapedChunk, "utf8");
701
+ } catch {}
702
+ }
703
+ }
704
+ } catch {}
705
+ }
637
706
  }
638
707
 
639
708
  if (!block.writeStats) {
@@ -643,6 +712,7 @@ function createTuiSink(tui, state) {
643
712
  totalLines: 0,
644
713
  totalChars: 0,
645
714
  startTime: Date.now(),
715
+ firstChunkAt: null,
646
716
  lineBuf: "",
647
717
  previewLines: [],
648
718
  done: false,
@@ -651,6 +721,9 @@ function createTuiSink(tui, state) {
651
721
  const ws = block.writeStats;
652
722
  if (ws.done) return;
653
723
 
724
+ // Track first-chunk time for accurate tok/s (excludes LLM thinking delay)
725
+ if (!ws.firstChunkAt) ws.firstChunkAt = Date.now();
726
+
654
727
  ws.totalChars += unescapedChunk.length;
655
728
  ws.lineBuf = (ws.lineBuf || "") + unescapedChunk;
656
729
  const parts = ws.lineBuf.split(/\r?\n/);
@@ -696,6 +769,15 @@ function createTuiSink(tui, state) {
696
769
  }
697
770
  }
698
771
  },
772
+ cleanupAllStreamWrites(revert = false) {
773
+ const keys = [...streamWriteBlocks.keys()];
774
+ for (const key of keys) {
775
+ if (typeof key === "number") {
776
+ this.cleanupStreamWrite(key, revert);
777
+ }
778
+ }
779
+ streamWriteBlocks.clear();
780
+ },
699
781
  };
700
782
  }
701
783