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 +11 -1
- package/package.json +1 -1
- package/providers.js +106 -5
- package/src/agent/streaming_write.js +159 -0
- package/src/agent/turn.js +27 -3
- package/src/cli/sinks.js +399 -13
- package/src/commands/handlers.js +9 -1
- package/src/config/paths.js +30 -9
- package/src/config/sessions.js +35 -0
- package/src/settings/schema.js +16 -3
- package/store.js +2 -0
- package/tools.js +1 -1
- package/tui.js +150 -10
- package/ui.js +1 -1
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 {
|
|
@@ -51,17 +54,21 @@ function createPlainSink(interactive, { headless = false, jsonMode = false } = {
|
|
|
51
54
|
const dots = [" ", ". ", ".. ", "..."];
|
|
52
55
|
let tick = 0;
|
|
53
56
|
let stopped = false;
|
|
57
|
+
let currentLabel = label;
|
|
54
58
|
const render = () => {
|
|
55
59
|
const symbol = frames[tick % frames.length];
|
|
56
60
|
const blink = dots[Math.floor(tick / 2) % dots.length];
|
|
57
61
|
process.stdout.write(
|
|
58
|
-
`\r\x1b[K${C.cyan}${prefix}${C.reset}${C.yellow}${symbol} ${
|
|
62
|
+
`\r\x1b[K${C.cyan}${prefix}${C.reset}${C.yellow}${symbol} ${currentLabel}${blink}${C.reset}`
|
|
59
63
|
);
|
|
60
64
|
tick++;
|
|
61
65
|
};
|
|
62
66
|
render();
|
|
63
67
|
const timer = setInterval(render, 100);
|
|
64
68
|
return {
|
|
69
|
+
setLabel(newLabel) {
|
|
70
|
+
if (newLabel) currentLabel = newLabel;
|
|
71
|
+
},
|
|
65
72
|
stop(keepPrefix = true) {
|
|
66
73
|
if (stopped) return;
|
|
67
74
|
stopped = true;
|
|
@@ -122,6 +129,9 @@ function addTuiBanner(tui, state) {
|
|
|
122
129
|
}
|
|
123
130
|
|
|
124
131
|
function createTuiSink(tui, state) {
|
|
132
|
+
// Maps provider tool-index -> { block, toolName } for streaming write preview
|
|
133
|
+
const streamWriteBlocks = new Map();
|
|
134
|
+
|
|
125
135
|
return {
|
|
126
136
|
isTui: true,
|
|
127
137
|
interactive: true,
|
|
@@ -137,7 +147,11 @@ function createTuiSink(tui, state) {
|
|
|
137
147
|
addTuiBanner(tui, state);
|
|
138
148
|
},
|
|
139
149
|
setBusy(label) {
|
|
140
|
-
tui.setStatus({
|
|
150
|
+
tui.setStatus({
|
|
151
|
+
busyLabel: label,
|
|
152
|
+
isBusy: Boolean(state.isBusy || label),
|
|
153
|
+
queueLen: state.queue?.length || 0,
|
|
154
|
+
});
|
|
141
155
|
},
|
|
142
156
|
syncStatus() {
|
|
143
157
|
tui.setStatus({
|
|
@@ -164,26 +178,37 @@ function createTuiSink(tui, state) {
|
|
|
164
178
|
process.stdout.write("\x07");
|
|
165
179
|
}
|
|
166
180
|
},
|
|
167
|
-
startThinking(_prefix = "Kovence: ",
|
|
181
|
+
startThinking(_prefix = "Kovence: ", initialLabel = "Thinking") {
|
|
182
|
+
// Clear per-turn write block registry so old indices don't bleed across turns.
|
|
183
|
+
streamWriteBlocks.clear();
|
|
168
184
|
const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
|
169
185
|
const dots = [" ", ". ", ".. ", "..."];
|
|
170
186
|
let tick = 0;
|
|
171
187
|
let stopped = false;
|
|
172
|
-
|
|
188
|
+
let currentLabel = initialLabel;
|
|
189
|
+
const block = tui.addBlock("thinking", `⠋ ${currentLabel} `);
|
|
173
190
|
const timer = setInterval(() => {
|
|
174
191
|
tick++;
|
|
175
192
|
const symbol = frames[tick % frames.length];
|
|
176
193
|
const blink = dots[Math.floor(tick / 2) % dots.length];
|
|
177
|
-
tui.updateBlock(block, `${symbol} ${
|
|
194
|
+
tui.updateBlock(block, `${symbol} ${currentLabel}${blink}`);
|
|
178
195
|
}, 100);
|
|
179
196
|
|
|
180
197
|
return {
|
|
198
|
+
setLabel(newLabel) {
|
|
199
|
+
if (stopped || !newLabel) return;
|
|
200
|
+
currentLabel = newLabel;
|
|
201
|
+
const symbol = frames[tick % frames.length];
|
|
202
|
+
const blink = dots[Math.floor(tick / 2) % dots.length];
|
|
203
|
+
tui.updateBlock(block, `${symbol} ${currentLabel}${blink}`);
|
|
204
|
+
},
|
|
181
205
|
stop(keepForStream = true) {
|
|
182
206
|
if (stopped) return;
|
|
183
207
|
stopped = true;
|
|
184
208
|
clearInterval(timer);
|
|
185
209
|
if (keepForStream) {
|
|
186
210
|
block.kind = "assistant";
|
|
211
|
+
block._streaming = true;
|
|
187
212
|
tui.updateBlock(block, "");
|
|
188
213
|
} else {
|
|
189
214
|
const idx = tui.blocks.indexOf(block);
|
|
@@ -194,7 +219,13 @@ function createTuiSink(tui, state) {
|
|
|
194
219
|
write(tok) {
|
|
195
220
|
tui.appendBlock(block, tok);
|
|
196
221
|
},
|
|
197
|
-
end() {
|
|
222
|
+
end() {
|
|
223
|
+
if (block._streaming) {
|
|
224
|
+
block._streaming = false;
|
|
225
|
+
block._cache = null;
|
|
226
|
+
tui.scheduleRender();
|
|
227
|
+
}
|
|
228
|
+
},
|
|
198
229
|
};
|
|
199
230
|
},
|
|
200
231
|
confirm: (label) => tui.askModal(label, false),
|
|
@@ -251,18 +282,86 @@ function createTuiSink(tui, state) {
|
|
|
251
282
|
},
|
|
252
283
|
};
|
|
253
284
|
},
|
|
254
|
-
startToolCall(label, { collapsible = true, expanded = false } = {}) {
|
|
255
|
-
const
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
285
|
+
startToolCall(label, { collapsible = true, expanded = false, toolIdx = null } = {}) {
|
|
286
|
+
const isWrite = /write_file|edit_file|multi_edit|apply_patch/.test(label);
|
|
287
|
+
const isRead = /read_file|glob_files|grep_files/.test(label);
|
|
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
|
+
|
|
261
305
|
const details = [];
|
|
262
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
|
+
}
|
|
263
320
|
|
|
264
321
|
return {
|
|
265
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
|
+
},
|
|
266
365
|
pushOutput(rawChunk) {
|
|
267
366
|
const cleaned = String(rawChunk || "")
|
|
268
367
|
.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, "")
|
|
@@ -295,6 +394,8 @@ function createTuiSink(tui, state) {
|
|
|
295
394
|
}
|
|
296
395
|
},
|
|
297
396
|
finish(fullOutputText = "", isError = false) {
|
|
397
|
+
// Mark write as done so animation stops.
|
|
398
|
+
if (block.writeStats) block.writeStats.done = true;
|
|
298
399
|
if (!details.length && fullOutputText) {
|
|
299
400
|
const fallbackLines = String(fullOutputText)
|
|
300
401
|
.split(/\r?\n/)
|
|
@@ -310,6 +411,291 @@ function createTuiSink(tui, state) {
|
|
|
310
411
|
},
|
|
311
412
|
};
|
|
312
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
|
+
},
|
|
313
699
|
};
|
|
314
700
|
}
|
|
315
701
|
|
package/src/commands/handlers.js
CHANGED
|
@@ -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 ||
|
|
641
|
+
const id = rawName || makeAutoSessionId();
|
|
634
642
|
await switchToSession(state, id, true, sink, waitForMemorySync);
|
|
635
643
|
return;
|
|
636
644
|
}
|
package/src/config/paths.js
CHANGED
|
@@ -29,15 +29,32 @@ function findProjectRoot(cwd = process.cwd()) {
|
|
|
29
29
|
}
|
|
30
30
|
|
|
31
31
|
/**
|
|
32
|
-
* Resolve
|
|
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
|
|
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
|
-
|
|
49
|
-
|
|
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(
|
|
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
|
|
package/src/config/sessions.js
CHANGED
|
@@ -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
|
};
|