kovence-cli 1.0.3 → 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
@@ -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 {
@@ -83,6 +86,29 @@ function createPlainSink(interactive, { headless = false, jsonMode = false } = {
83
86
  confirm: (label) => (interactive ? promptConfirm(`${C.yellow}${label}${C.reset}`) : Promise.resolve("n")),
84
87
  askPrompt: (label) => (interactive ? promptLine(label, []) : Promise.resolve("")),
85
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
+ },
86
112
  startProgress(initialText = "") {
87
113
  if (jsonMode || headless || !process.stdout.isTTY) {
88
114
  return { update() {}, done() {} };
@@ -126,6 +152,9 @@ function addTuiBanner(tui, state) {
126
152
  }
127
153
 
128
154
  function createTuiSink(tui, state) {
155
+ // Maps provider tool-index -> { block, toolName } for streaming write preview
156
+ const streamWriteBlocks = new Map();
157
+
129
158
  return {
130
159
  isTui: true,
131
160
  interactive: true,
@@ -141,7 +170,11 @@ function createTuiSink(tui, state) {
141
170
  addTuiBanner(tui, state);
142
171
  },
143
172
  setBusy(label) {
144
- tui.setStatus({ busyLabel: label, isBusy: Boolean(state.isBusy || label), queueLen: state.queue.length });
173
+ tui.setStatus({
174
+ busyLabel: label,
175
+ isBusy: Boolean(state.isBusy || label),
176
+ queueLen: state.queue?.length || 0,
177
+ });
145
178
  },
146
179
  syncStatus() {
147
180
  tui.setStatus({
@@ -151,6 +184,7 @@ function createTuiSink(tui, state) {
151
184
  model: state.model,
152
185
  ctxText: getContextLabel(state),
153
186
  agentMode: state.settings.agentMode,
187
+ reasoning: state.settings.reasoning || "off",
154
188
  colorScheme: state.settings.colorScheme || "amber",
155
189
  tools: state.settings.toolsEnabled,
156
190
  auto: state.settings.agentMode === "auto",
@@ -169,6 +203,8 @@ function createTuiSink(tui, state) {
169
203
  }
170
204
  },
171
205
  startThinking(_prefix = "Kovence: ", initialLabel = "Thinking") {
206
+ // Clear per-turn write block registry so old indices don't bleed across turns.
207
+ streamWriteBlocks.clear();
172
208
  const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
173
209
  const dots = [" ", ". ", ".. ", "..."];
174
210
  let tick = 0;
@@ -236,6 +272,18 @@ function createTuiSink(tui, state) {
236
272
  });
237
273
  return res?.action === "select" ? res.item?.id || "" : "";
238
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
+ },
239
287
  async openModePicker(currentMode) {
240
288
  const modeMeta = [
241
289
  { id: "default", desc: "Ask confirmation for file edits, downloads & commands" },
@@ -270,20 +318,87 @@ function createTuiSink(tui, state) {
270
318
  },
271
319
  };
272
320
  },
273
- startToolCall(label, { collapsible = true, expanded = false } = {}) {
321
+ startToolCall(label, { collapsible = true, expanded = false, toolIdx = null } = {}) {
274
322
  const isWrite = /write_file|edit_file|multi_edit|apply_patch/.test(label);
275
323
  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
- });
324
+
325
+ // If preRegisterWriteBlock already created a block for this tool, reuse it
326
+ const preReg = toolIdx !== null ? streamWriteBlocks.get(toolIdx) : null;
327
+ const block = preReg?.preRegistered
328
+ ? preReg.block
329
+ : tui.addBlock("tool", label, {
330
+ collapsible,
331
+ expanded,
332
+ details: [],
333
+ statusLine: isWrite ? "writing..." : isRead ? "reading..." : "running...",
334
+ });
335
+ // Update label on reused block
336
+ if (preReg?.preRegistered) {
337
+ block.text = label;
338
+ block._cache = null;
339
+ }
340
+
282
341
  const details = [];
283
342
  let lastUpdateAt = 0;
343
+ if (toolIdx !== null && isWrite) {
344
+ if (!streamWriteBlocks.has(toolIdx)) {
345
+ streamWriteBlocks.set(toolIdx, { block, toolName: label });
346
+ }
347
+ // Replay any chunks that arrived before this block was created
348
+ const pending = streamWriteBlocks.get(`pending-${toolIdx}`);
349
+ if (pending && pending.chunks.length) {
350
+ streamWriteBlocks.delete(`pending-${toolIdx}`);
351
+ for (const ch of pending.chunks) {
352
+ this.onWriteStreamChunk(toolIdx, pending.toolName || label, pending.path || "", ch);
353
+ }
354
+ }
355
+ }
284
356
 
285
357
  return {
286
358
  block,
359
+ /**
360
+ * Called once at write start with { filePath, content }.
361
+ * Populates block.writeStats so the TUI can animate and show live stats.
362
+ */
363
+ startWrite({ filePath = "", content = "" } = {}) {
364
+ // If streaming already pre-populated writeStats, just update totals with
365
+ // the final known values and keep the live previewLines.
366
+ if (block.writeStats) {
367
+ const ws = block.writeStats;
368
+ const lines = String(content || "").split(/\r?\n/);
369
+ ws.filePath = String(filePath || ws.filePath || "");
370
+ ws.dir =
371
+ ws.dir ||
372
+ (filePath ? filePath.replace(/\\/g, "/").split("/").slice(0, -1).join("/") || "." : "");
373
+ ws.totalLines = lines.length;
374
+ ws.totalChars = content.length;
375
+ // Use streaming preview if it has content, else fall back to final content
376
+ if (!ws.previewLines.length && !ws.currentPreview?.length) {
377
+ ws.previewLines = lines.filter((l) => l.trim()).slice(-5);
378
+ ws.currentPreview = ws.previewLines;
379
+ }
380
+ block._ver = (block._ver || 0) + 1;
381
+ block._cache = null;
382
+ tui.scheduleRender();
383
+ return;
384
+ }
385
+ const lines = String(content || "").split(/\r?\n/);
386
+ const dir = filePath ? filePath.replace(/\\/g, "/").split("/").slice(0, -1).join("/") || "." : "";
387
+ block.writeStats = {
388
+ filePath: String(filePath || ""),
389
+ dir: String(dir),
390
+ totalLines: lines.length,
391
+ totalChars: content.length,
392
+ startTime: Date.now(),
393
+ firstChunkAt: null,
394
+ // 5-line rolling preview (last 5 non-blank lines)
395
+ previewLines: lines.filter((l) => l.trim()).slice(-5),
396
+ done: false,
397
+ };
398
+ block._ver = (block._ver || 0) + 1;
399
+ block._cache = null;
400
+ tui.scheduleRender();
401
+ },
287
402
  pushOutput(rawChunk) {
288
403
  const cleaned = String(rawChunk || "")
289
404
  .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, "")
@@ -316,6 +431,11 @@ function createTuiSink(tui, state) {
316
431
  }
317
432
  },
318
433
  finish(fullOutputText = "", isError = false) {
434
+ // Mark write as done so animation stops.
435
+ if (block.writeStats) {
436
+ block.writeStats.done = true;
437
+ block.writeStats.doneAt = Date.now();
438
+ }
319
439
  if (!details.length && fullOutputText) {
320
440
  const fallbackLines = String(fullOutputText)
321
441
  .split(/\r?\n/)
@@ -331,6 +451,333 @@ function createTuiSink(tui, state) {
331
451
  },
332
452
  };
333
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
+ },
492
+ /**
493
+ * Called by providers.js as soon as the file path is known during LLM streaming.
494
+ * Creates target directory and file beforehand, registers checkpoint, and pre-registers TUI block.
495
+ * @param {number} toolIdx - provider toolMap index
496
+ * @param {string} toolName - e.g. "write_file"
497
+ * @param {string} filePath - destination file path
498
+ */
499
+ preRegisterWriteBlock(toolIdx, toolName, filePath) {
500
+ let entry = streamWriteBlocks.get(toolIdx);
501
+ if (entry?.preRegistered && entry.filePath === filePath && !entry.block?.writeStats?.done) return;
502
+
503
+ const workspaceRoot = state.workspaceRoot || process.cwd();
504
+ const absPath = filePath
505
+ ? path.isAbsolute(filePath)
506
+ ? filePath
507
+ : path.resolve(workspaceRoot, filePath)
508
+ : "";
509
+
510
+ let fileCreated = false;
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) {
515
+ try {
516
+ const targetDir = path.dirname(absPath);
517
+ fs.mkdirSync(targetDir, { recursive: true });
518
+
519
+ if (state.paths) {
520
+ if (!state.streamCheckpointed) state.streamCheckpointed = new Set();
521
+ if (!state.streamCheckpointed.has(absPath)) {
522
+ recordCheckpoint({
523
+ sessionId: state.session?.id || "default",
524
+ toolName: "write_file",
525
+ filePaths: [absPath],
526
+ paths: state.paths,
527
+ });
528
+ state.streamCheckpointed.add(absPath);
529
+ }
530
+ }
531
+
532
+ fs.writeFileSync(absPath, "", "utf8");
533
+ fileCreated = true;
534
+ } catch {}
535
+ }
536
+
537
+ const fname = filePath ? filePath.replace(/\\/g, "/").split("/").pop() : "...";
538
+ const label = `⚙ ${toolName}(${fname})`;
539
+ const dir = filePath ? filePath.replace(/\\/g, "/").split("/").slice(0, -1).join("/") || "." : "";
540
+
541
+ const shouldCreateFresh =
542
+ !entry ||
543
+ Boolean(entry.block?.writeStats?.done) ||
544
+ Boolean(entry.filePath && filePath && entry.filePath !== filePath);
545
+
546
+ if (shouldCreateFresh) {
547
+ const rawBlock = {
548
+ kind: "tool",
549
+ text: label,
550
+ collapsible: true,
551
+ expanded: false,
552
+ details: [],
553
+ statusLine: "writing...",
554
+ _ver: 1,
555
+ _cache: null,
556
+ };
557
+ rawBlock.writeStats = {
558
+ filePath: String(filePath || ""),
559
+ dir: String(dir),
560
+ totalLines: 0,
561
+ totalChars: 0,
562
+ startTime: Date.now(),
563
+ firstChunkAt: null,
564
+ lineBuf: "",
565
+ previewLines: [],
566
+ done: false,
567
+ };
568
+ let insertAt = tui.blocks.length;
569
+ for (let i = tui.blocks.length - 1; i >= 0; i--) {
570
+ if (tui.blocks[i].kind === "thinking") {
571
+ insertAt = i + 1;
572
+ break;
573
+ }
574
+ }
575
+ tui.blocks.splice(insertAt, 0, rawBlock);
576
+ streamWriteBlocks.set(toolIdx, {
577
+ block: rawBlock,
578
+ toolName,
579
+ filePath,
580
+ absPath,
581
+ preRegistered: true,
582
+ fileCreated,
583
+ pendingDiskChunks: [],
584
+ });
585
+ } else {
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 = {
592
+ filePath: String(filePath || ""),
593
+ dir: String(dir),
594
+ totalLines: 0,
595
+ totalChars: 0,
596
+ startTime: Date.now(),
597
+ firstChunkAt: null,
598
+ lineBuf: "",
599
+ previewLines: [],
600
+ done: false,
601
+ };
602
+ } else {
603
+ entry.block.writeStats.filePath = String(filePath || entry.block.writeStats.filePath || "");
604
+ entry.block.writeStats.dir = String(dir || entry.block.writeStats.dir || "");
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;
620
+ }
621
+ tui.scheduleRender();
622
+ },
623
+ /**
624
+ * Called by providers.js for each unescaped chunk while the LLM streams.
625
+ * Appends dynamically to the target file on disk and updates the TUI 5-line sliding preview.
626
+ * @param {number} toolIdx - provider's toolMap index
627
+ * @param {string} toolName - e.g. "write_file"
628
+ * @param {string} filePath - destination file path
629
+ * @param {string} unescapedChunk - unescaped content chunk from LLM stream
630
+ */
631
+ onWriteStreamChunk(toolIdx, toolName, filePath, unescapedChunk) {
632
+ let entry = streamWriteBlocks.get(toolIdx);
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 || "");
640
+ entry = streamWriteBlocks.get(toolIdx);
641
+ }
642
+ if (!entry) return;
643
+
644
+ const { block } = entry;
645
+ const workspaceRoot = state.workspaceRoot || process.cwd();
646
+ const absPath =
647
+ entry.absPath ||
648
+ (filePath ? (path.isAbsolute(filePath) ? filePath : path.resolve(workspaceRoot, filePath)) : "");
649
+
650
+ // If write_file, ensure created in directory and dynamically append token chunks to the file
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 {
663
+ try {
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);
677
+ }
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 = [];
685
+ }
686
+ }
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
+ }
706
+ }
707
+
708
+ if (!block.writeStats) {
709
+ block.writeStats = {
710
+ filePath: filePath || entry.filePath || "",
711
+ dir: filePath ? filePath.replace(/\\/g, "/").split("/").slice(0, -1).join("/") || "." : "",
712
+ totalLines: 0,
713
+ totalChars: 0,
714
+ startTime: Date.now(),
715
+ firstChunkAt: null,
716
+ lineBuf: "",
717
+ previewLines: [],
718
+ done: false,
719
+ };
720
+ }
721
+ const ws = block.writeStats;
722
+ if (ws.done) return;
723
+
724
+ // Track first-chunk time for accurate tok/s (excludes LLM thinking delay)
725
+ if (!ws.firstChunkAt) ws.firstChunkAt = Date.now();
726
+
727
+ ws.totalChars += unescapedChunk.length;
728
+ ws.lineBuf = (ws.lineBuf || "") + unescapedChunk;
729
+ const parts = ws.lineBuf.split(/\r?\n/);
730
+ ws.lineBuf = parts.pop();
731
+ for (const p of parts) {
732
+ if (p.trim()) ws.previewLines.push(p);
733
+ ws.totalLines++;
734
+ }
735
+ if (ws.previewLines.length > 20) {
736
+ ws.previewLines = ws.previewLines.slice(-10);
737
+ }
738
+ // Real-time visible 5-line window of last written code with auto-scroll
739
+ const activeLines = [...ws.previewLines];
740
+ if (ws.lineBuf && ws.lineBuf.trim()) activeLines.push(ws.lineBuf);
741
+ ws.currentPreview = activeLines.slice(-5);
742
+ ws.totalLines = Math.max(ws.totalLines, activeLines.length);
743
+
744
+ block._ver = (block._ver || 0) + 1;
745
+ block._cache = null;
746
+ tui.scheduleRender();
747
+ },
748
+ onWriteStreamChunkEnd(_toolIdx, _toolName, _filePath) {
749
+ // Content stream finished for this tool
750
+ },
751
+ cleanupStreamWrite(toolIdx, revert = false) {
752
+ const entry = streamWriteBlocks.get(toolIdx);
753
+ if (!entry) return;
754
+ if (revert && entry.absPath && entry.fileCreated) {
755
+ const workspaceRoot = state.workspaceRoot || process.cwd();
756
+ if (state.paths && state.streamCheckpointed?.has(entry.absPath)) {
757
+ try {
758
+ undoLastCheckpoint(state.session?.id || "default", state.paths, workspaceRoot);
759
+ state.streamCheckpointed.delete(entry.absPath);
760
+ } catch {
761
+ try {
762
+ if (fs.existsSync(entry.absPath)) fs.rmSync(entry.absPath, { force: true });
763
+ } catch {}
764
+ }
765
+ } else {
766
+ try {
767
+ if (fs.existsSync(entry.absPath)) fs.rmSync(entry.absPath, { force: true });
768
+ } catch {}
769
+ }
770
+ }
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
+ },
334
781
  };
335
782
  }
336
783