@causyne/agent 1.20.60 → 1.20.62
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/package.json +1 -1
- package/src/acp/agentCatalog.js +1 -1
- package/src/acp/agentCatalog.ts +1 -1
- package/src/acp/peerProfiles.js +3 -3
- package/src/acp/peerProfiles.ts +3 -3
- package/src/agentLoop.js +58 -22
- package/src/agentLoop.ts +64 -25
- package/src/checkpoints.js +23 -5
- package/src/cliMode.js +4 -2
- package/src/commands.js +503 -78
- package/src/contextManager.d.ts +3 -0
- package/src/contextManager.js +78 -5
- package/src/cortex/autoCondenser.js +105 -145
- package/src/cortex/autoCondenser.ts +185 -0
- package/src/cortex/cortexEngine.js +179 -0
- package/src/cortex/cortexEngine.ts +209 -0
- package/src/cortex/provisioner.js +12 -14
- package/src/cortex/provisioner.ts +29 -0
- package/src/cortex/vectorDb.js +307 -386
- package/src/cortex/vectorDb.ts +473 -0
- package/src/reporting.js +30 -7
- package/src/sessionJournal.js +13 -0
- package/src/sessionJournal.ts +13 -0
- package/src/tokenTracker.js +22 -0
- package/src/tokenTracker.ts +28 -0
- package/src/tui/chatRenderer.js +6 -2
- package/src/tui/completion.js +34 -15
- package/src/tui/composerControls.js +5 -0
- package/src/tui/composerControls.ts +5 -0
- package/src/tui/layout.js +1 -1
- package/src/tui/layout.ts +1 -1
- package/src/tui/observerPicker.js +323 -0
- package/src/tui/observerPicker.ts +386 -0
- package/src/tui/prompt.js +184 -22
- package/src/tui/stageSurface.js +18 -8
- package/src/tui/usageCard.js +178 -0
- package/src/tui/usageCard.ts +240 -0
- package/src/utils/paths.js +30 -1
- package/src/utils/paths.ts +32 -1
- package/src/cortex/autoCondenser.d.ts +0 -2
- package/src/cortex/vectorDb.d.ts +0 -1
package/src/tui/prompt.js
CHANGED
|
@@ -23,9 +23,10 @@ import { PromptHistory } from './history.js';
|
|
|
23
23
|
import { FileIndex, suggest, applyCompletion, detectTrigger, renderPicker, MAX_VISIBLE } from './completion.js';
|
|
24
24
|
import { paint, dim, bold, GLYPHS, terminalWidth, HAS_COLOR } from './theme.js';
|
|
25
25
|
import { barBlock, GUTTER } from './block.js';
|
|
26
|
-
import { visibleWidth, truncate, wrapBlock, shortenHome, safeDisplay } from './text.js';
|
|
26
|
+
import { visibleWidth, truncate, wrapBlock, shortenHome, safeDisplay, stripAnsi } from './text.js';
|
|
27
27
|
import { pickExample, fitHints } from './banner.js';
|
|
28
28
|
import { panelRows } from './overlay.js';
|
|
29
|
+
import { renderUsageCardRows, collectUsageCardData } from './usageCard.js';
|
|
29
30
|
import { commandPalette, skillPicker, ApprovalLayer, DecisionLayer, ConfirmLayer, HomeLayer, TextLayer } from './dialogs.js';
|
|
30
31
|
import { describeTool } from './toolDisplay.js';
|
|
31
32
|
import { readClipboardSync, writeClipboardSync } from './clipboardSync.js';
|
|
@@ -121,6 +122,7 @@ export class ChatPrompt {
|
|
|
121
122
|
this.busy = false;
|
|
122
123
|
this.active = false;
|
|
123
124
|
this.drawnRows = 0;
|
|
125
|
+
this.usageCard = null;
|
|
124
126
|
|
|
125
127
|
// Which row of the drawn block the caret is parked on.
|
|
126
128
|
//
|
|
@@ -250,7 +252,47 @@ export class ChatPrompt {
|
|
|
250
252
|
|
|
251
253
|
handleData = (chunk) => {
|
|
252
254
|
let motionOnly = true;
|
|
253
|
-
|
|
255
|
+
const str = typeof chunk === 'string' ? chunk : Buffer.isBuffer(chunk) ? chunk.toString('utf8') : '';
|
|
256
|
+
// Unbracketed multi-line or bulk paste safeguard: when a multi-line or bulk block arrives
|
|
257
|
+
// without bracketed paste (e.g. VS Code terminal, native clipboard paste, terminal ANSI logs,
|
|
258
|
+
// or piped stream), handle it atomically as a paste event rather than executing multiple
|
|
259
|
+
// spurious Enter submissions or freezing in per-character completion loops.
|
|
260
|
+
const isBracketedPasteStart = str.startsWith('\x1b[200~');
|
|
261
|
+
const isMouse = str.startsWith('\x1b[<') || str.startsWith('\x1b[M');
|
|
262
|
+
const hasNewlines = str.includes('\n') || str.includes('\r');
|
|
263
|
+
if (!this.layer && !this.decoder.inPaste && !isBracketedPasteStart && !isMouse && (
|
|
264
|
+
(str.length > 2 && hasNewlines) ||
|
|
265
|
+
(str.length >= 64 && !str.startsWith('\x1b'))
|
|
266
|
+
)) {
|
|
267
|
+
const clean = stripAnsi(str).replace(/\r\n/g, '\n').replace(/\r/g, '\n');
|
|
268
|
+
try {
|
|
269
|
+
this.handleKey({ name: 'paste', text: clean, sequence: clean });
|
|
270
|
+
} catch (e) {
|
|
271
|
+
process.stderr.write(`\n[tui] paste failed: ${e.message}\n`);
|
|
272
|
+
}
|
|
273
|
+
this.draw();
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const keys = this.decoder.decode(chunk);
|
|
278
|
+
let charBatch = '';
|
|
279
|
+
|
|
280
|
+
for (let i = 0; i < keys.length; i++) {
|
|
281
|
+
const key = keys[i];
|
|
282
|
+
if (!this.layer && key.name === 'char' && typeof key.text === 'string' && !key.alt && !key.ctrl) {
|
|
283
|
+
charBatch += key.text;
|
|
284
|
+
motionOnly = false;
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
if (charBatch.length > 0) {
|
|
288
|
+
this.editor.insert(charBatch);
|
|
289
|
+
if (charBatch.length < 60 && !charBatch.includes('\n')) {
|
|
290
|
+
this.refreshCompletion();
|
|
291
|
+
} else {
|
|
292
|
+
this.completion = null;
|
|
293
|
+
}
|
|
294
|
+
charBatch = '';
|
|
295
|
+
}
|
|
254
296
|
if (key.name !== 'mouse' || !isMouseMotion(key.sequence)) motionOnly = false;
|
|
255
297
|
try {
|
|
256
298
|
this.handleKey(key);
|
|
@@ -260,6 +302,17 @@ export class ChatPrompt {
|
|
|
260
302
|
process.stderr.write(`\n[tui] key "${key.name}" failed: ${e.message}\n`);
|
|
261
303
|
}
|
|
262
304
|
}
|
|
305
|
+
|
|
306
|
+
if (charBatch.length > 0) {
|
|
307
|
+
this.editor.insert(charBatch);
|
|
308
|
+
if (charBatch.length < 60 && !charBatch.includes('\n')) {
|
|
309
|
+
this.refreshCompletion();
|
|
310
|
+
} else {
|
|
311
|
+
this.completion = null;
|
|
312
|
+
}
|
|
313
|
+
charBatch = '';
|
|
314
|
+
}
|
|
315
|
+
|
|
263
316
|
// All-motion chunks repaint only when the hovered message actually changes.
|
|
264
317
|
if (!motionOnly) this.draw();
|
|
265
318
|
};
|
|
@@ -492,7 +545,13 @@ export class ChatPrompt {
|
|
|
492
545
|
showText(title, text, options = {}) {
|
|
493
546
|
const panelWidth = dialogWidth(this.width(), options.width || 76);
|
|
494
547
|
const contentWidth = Math.max(12, panelWidth - 4);
|
|
495
|
-
|
|
548
|
+
let lines = wrapBlock(safeDisplay(String(text == null ? '' : text)), contentWidth);
|
|
549
|
+
if (lines.length > 0 && lines[0].trim().toLowerCase() === String(title || '').trim().toLowerCase()) {
|
|
550
|
+
lines = lines.slice(1);
|
|
551
|
+
if (lines.length > 0 && /^[-─═_]+$/.test(lines[0].trim())) {
|
|
552
|
+
lines = lines.slice(1);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
496
555
|
return this.openLayer(new TextLayer({
|
|
497
556
|
title: String(title || 'Details'),
|
|
498
557
|
lines: options.danger ? lines.map((line) => paint('danger', line)) : lines,
|
|
@@ -501,6 +560,31 @@ export class ChatPrompt {
|
|
|
501
560
|
}));
|
|
502
561
|
}
|
|
503
562
|
|
|
563
|
+
/** Toggle the docked usage card directly above the chatbox. */
|
|
564
|
+
async toggleUsageCard(loop = null) {
|
|
565
|
+
if (this.usageCard) {
|
|
566
|
+
this.usageCard = null;
|
|
567
|
+
this.scheduleDraw();
|
|
568
|
+
return false;
|
|
569
|
+
}
|
|
570
|
+
this.usageCard = await collectUsageCardData(loop || this.messageActionLoop);
|
|
571
|
+
this.scheduleDraw();
|
|
572
|
+
return true;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
showUsageCard(loop = null) {
|
|
576
|
+
return this.toggleUsageCard(loop);
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
closeUsageCard() {
|
|
580
|
+
if (this.usageCard) {
|
|
581
|
+
this.usageCard = null;
|
|
582
|
+
this.scheduleDraw();
|
|
583
|
+
return true;
|
|
584
|
+
}
|
|
585
|
+
return false;
|
|
586
|
+
}
|
|
587
|
+
|
|
504
588
|
/**
|
|
505
589
|
* Ask for approval of a tool call: risk, arguments and a scrollable diff.
|
|
506
590
|
*
|
|
@@ -627,6 +711,9 @@ export class ChatPrompt {
|
|
|
627
711
|
this.history.add(text);
|
|
628
712
|
this.editor.clear();
|
|
629
713
|
this.completion = null;
|
|
714
|
+
if (this.usageCard && !this.isCommand(text)) {
|
|
715
|
+
this.usageCard = null;
|
|
716
|
+
}
|
|
630
717
|
|
|
631
718
|
// Control commands take priority over busy turns so the user is never locked out.
|
|
632
719
|
// Commands like /stop, /new, /model, /session, /sessions, /continuum, /clear can interrupt
|
|
@@ -641,6 +728,14 @@ export class ChatPrompt {
|
|
|
641
728
|
text === '/clear'
|
|
642
729
|
);
|
|
643
730
|
|
|
731
|
+
// Immediate abort signals interrupt the running turn directly without queuing as a future task.
|
|
732
|
+
if ((text === '/stop' || text === '/interrupt') && this.busy) {
|
|
733
|
+
this.interrupt();
|
|
734
|
+
this.notice = 'Interrupted';
|
|
735
|
+
this.scheduleDraw();
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
|
|
644
739
|
if (isControlCommand && this.busy) {
|
|
645
740
|
this.interrupt();
|
|
646
741
|
}
|
|
@@ -660,6 +755,10 @@ export class ChatPrompt {
|
|
|
660
755
|
const settle = this.waiter;
|
|
661
756
|
this.waiter = null;
|
|
662
757
|
if (settle) settle(text);
|
|
758
|
+
else {
|
|
759
|
+
if (!Array.isArray(this.queue)) this.queue = [];
|
|
760
|
+
this.queue.push(text); // nobody is reading yet: hold it, never drop it
|
|
761
|
+
}
|
|
663
762
|
return;
|
|
664
763
|
}
|
|
665
764
|
|
|
@@ -669,7 +768,7 @@ export class ChatPrompt {
|
|
|
669
768
|
else this.commit('user', (width) => {
|
|
670
769
|
const blockWidth = Math.max(8, width);
|
|
671
770
|
return barBlock(
|
|
672
|
-
wrapBlock(safeDisplay(text), Math.max(8, blockWidth - visibleWidth(GLYPHS.barHeavy || GLYPHS.bar) - GUTTER)),
|
|
771
|
+
wrapBlock(safeDisplay(text), Math.max(8, blockWidth - visibleWidth(GLYPHS.barHeavy || GLYPHS.bar) - GUTTER), { hang: 0 }),
|
|
673
772
|
{ width: blockWidth, role: 'user', filled: true, surface: 'surfaceHi' }
|
|
674
773
|
);
|
|
675
774
|
});
|
|
@@ -683,6 +782,14 @@ export class ChatPrompt {
|
|
|
683
782
|
// -------------------------------------------------------------------------
|
|
684
783
|
|
|
685
784
|
handleKey(key) {
|
|
785
|
+
// A notice reports the result of the last action. Once the user edits the
|
|
786
|
+
// line again it is stale, and leaving it up made "copied ..." follow every
|
|
787
|
+
// later keystroke for the rest of the session.
|
|
788
|
+
if (this.notice && !this.layer
|
|
789
|
+
&& (key.name === 'char' || key.name === 'paste' || key.name === 'backspace' || key.name === 'delete')) {
|
|
790
|
+
this.notice = '';
|
|
791
|
+
}
|
|
792
|
+
|
|
686
793
|
// The wheel was handed to the terminal at the top of the band; the moment
|
|
687
794
|
// the user types again they are driving this prompt, so take it back.
|
|
688
795
|
if (key.name !== 'wheel' && key.name !== 'mouse') {
|
|
@@ -737,8 +844,16 @@ export class ChatPrompt {
|
|
|
737
844
|
}
|
|
738
845
|
|
|
739
846
|
if (key.name === 'paste') {
|
|
847
|
+
if (this.surface && typeof this.surface.captureMouse === 'function') {
|
|
848
|
+
this.surface.captureMouse();
|
|
849
|
+
}
|
|
740
850
|
this.editor.insert(key.text);
|
|
741
|
-
|
|
851
|
+
if (typeof key.text === 'string' && !key.text.includes('\n') && key.text.length < 60) {
|
|
852
|
+
this.refreshCompletion();
|
|
853
|
+
} else {
|
|
854
|
+
this.completion = null;
|
|
855
|
+
}
|
|
856
|
+
this.scheduleDraw();
|
|
742
857
|
return;
|
|
743
858
|
}
|
|
744
859
|
|
|
@@ -983,8 +1098,8 @@ export class ChatPrompt {
|
|
|
983
1098
|
// sit at almost the same seam — a footer is immediately followed by the next
|
|
984
1099
|
// question — so accepting either made the jump land twice two rows apart
|
|
985
1100
|
// instead of once per exchange.
|
|
986
|
-
if (key.name === '[' || (key.alt && key.name === '<')) { viewport.jump(-1, ['user']); return true; }
|
|
987
|
-
if (key.name === ']' || (key.alt && key.name === '>')) { viewport.jump(1, ['user']); return true; }
|
|
1101
|
+
if ((key.alt && key.name === '[') || (key.alt && key.name === '<')) { viewport.jump(-1, ['user']); return true; }
|
|
1102
|
+
if ((key.alt && key.name === ']') || (key.alt && key.name === '>')) { viewport.jump(1, ['user']); return true; }
|
|
988
1103
|
|
|
989
1104
|
if (key.alt && key.name === 'u') { this.offerUndo(); return true; }
|
|
990
1105
|
|
|
@@ -1173,6 +1288,25 @@ export class ChatPrompt {
|
|
|
1173
1288
|
handleCompletionKey(key) {
|
|
1174
1289
|
if (key.name === 'up') { this.moveSelection(-1); return true; }
|
|
1175
1290
|
if (key.name === 'down') { this.moveSelection(1); return true; }
|
|
1291
|
+
// The wheel, PgUp and PgDn belong to the open picker. Letting them fall
|
|
1292
|
+
// through scrolled the transcript behind a frozen menu.
|
|
1293
|
+
if (key.name === 'wheel') {
|
|
1294
|
+
const direction = key.wheel && key.wheel.direction;
|
|
1295
|
+
if (direction === 'up') this.moveSelectionClamped(-1);
|
|
1296
|
+
else if (direction === 'down') this.moveSelectionClamped(1);
|
|
1297
|
+
this.scheduleDraw();
|
|
1298
|
+
return true;
|
|
1299
|
+
}
|
|
1300
|
+
if (key.name === 'pageup' && !key.shift) {
|
|
1301
|
+
this.moveSelectionClamped(-MAX_VISIBLE);
|
|
1302
|
+
this.scheduleDraw();
|
|
1303
|
+
return true;
|
|
1304
|
+
}
|
|
1305
|
+
if (key.name === 'pagedown' && !key.shift) {
|
|
1306
|
+
this.moveSelectionClamped(MAX_VISIBLE);
|
|
1307
|
+
this.scheduleDraw();
|
|
1308
|
+
return true;
|
|
1309
|
+
}
|
|
1176
1310
|
if (key.name === 'mouse') {
|
|
1177
1311
|
if (key.mouse && key.mouse.pressed && key.mouse.button === 0) {
|
|
1178
1312
|
let item = null;
|
|
@@ -1183,7 +1317,11 @@ export class ChatPrompt {
|
|
|
1183
1317
|
const pickerBottom = pickerTop + this.pickerLayout.pickerCount - 1;
|
|
1184
1318
|
|
|
1185
1319
|
if (key.mouse.row >= pickerTop && key.mouse.row <= pickerBottom) {
|
|
1186
|
-
|
|
1320
|
+
// The picker renders a scrolled window (renderPicker); a click maps
|
|
1321
|
+
// to the item under the cursor, not to the first page of items.
|
|
1322
|
+
const total = this.completion.items ? this.completion.items.length : 0;
|
|
1323
|
+
const windowStart = Math.max(0, Math.min(this.selected - MAX_VISIBLE + 1, total - MAX_VISIBLE));
|
|
1324
|
+
const index = windowStart + (key.mouse.row - pickerTop);
|
|
1187
1325
|
item = this.completion.items && this.completion.items[index];
|
|
1188
1326
|
} else {
|
|
1189
1327
|
// Click outside picker closes it
|
|
@@ -1197,16 +1335,17 @@ export class ChatPrompt {
|
|
|
1197
1335
|
|
|
1198
1336
|
if (item) {
|
|
1199
1337
|
if (this.completion.kind === 'command') {
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1338
|
+
// A skill entry goes onto the line so the user can say what to do
|
|
1339
|
+
// with it; clicking it used to invoke it immediately with no task.
|
|
1340
|
+
if (typeof item.value === 'string' && (item.value.startsWith('/skills ') || item.value.startsWith('/skill '))) {
|
|
1341
|
+
this.acceptCompletion();
|
|
1342
|
+
return true;
|
|
1343
|
+
}
|
|
1344
|
+
this.submitPickedCommand(item.value);
|
|
1203
1345
|
return true;
|
|
1204
1346
|
}
|
|
1205
1347
|
if (this.completion.kind === 'command-argument') {
|
|
1206
|
-
|
|
1207
|
-
this.editor.clear();
|
|
1208
|
-
this.completion = null;
|
|
1209
|
-
this.deliver(`/${cmd} ${item.value}`);
|
|
1348
|
+
this.submitPickedCommand(`/${this.completion.command} ${item.value}`);
|
|
1210
1349
|
return true;
|
|
1211
1350
|
}
|
|
1212
1351
|
this.acceptCompletion();
|
|
@@ -1218,10 +1357,12 @@ export class ChatPrompt {
|
|
|
1218
1357
|
if (key.name === 'enter' && !key.alt) {
|
|
1219
1358
|
const item = this.completion.items && this.completion.items[this.selected];
|
|
1220
1359
|
if (this.completion.kind === 'command' && item) {
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1360
|
+
if (typeof item.value === 'string' && (item.value.startsWith('/skills ') || item.value.startsWith('/skill '))) {
|
|
1361
|
+
this.acceptCompletion();
|
|
1362
|
+
return true;
|
|
1363
|
+
}
|
|
1364
|
+
// Instant execution on single Enter for any pure slash command
|
|
1365
|
+
this.submitPickedCommand(item.value);
|
|
1225
1366
|
return true;
|
|
1226
1367
|
}
|
|
1227
1368
|
if (this.completionIsExact()) {
|
|
@@ -1250,6 +1391,26 @@ export class ChatPrompt {
|
|
|
1250
1391
|
this.selected = (this.selected + direction + count) % count;
|
|
1251
1392
|
}
|
|
1252
1393
|
|
|
1394
|
+
/** Move without wrapping: a wheel or page key stops at either end. */
|
|
1395
|
+
moveSelectionClamped(delta) {
|
|
1396
|
+
const count = this.completion.items.length;
|
|
1397
|
+
if (count === 0) return;
|
|
1398
|
+
this.selected = Math.max(0, Math.min(count - 1, this.selected + delta));
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
/**
|
|
1402
|
+
* Run a command chosen in the picker through the same path as typing it.
|
|
1403
|
+
*
|
|
1404
|
+
* deliver() bypassed submit(): during a running turn a picked `/stop` was
|
|
1405
|
+
* queued behind the very turn it was meant to stop, and the command never
|
|
1406
|
+
* reached input history.
|
|
1407
|
+
*/
|
|
1408
|
+
submitPickedCommand(value) {
|
|
1409
|
+
this.completion = null;
|
|
1410
|
+
this.editor.setText(value);
|
|
1411
|
+
this.submit();
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1253
1414
|
acceptCompletion() {
|
|
1254
1415
|
const item = this.completion.items[this.selected];
|
|
1255
1416
|
if (!item) { this.completion = null; return; }
|
|
@@ -1392,10 +1553,11 @@ export class ChatPrompt {
|
|
|
1392
1553
|
punctuate: false
|
|
1393
1554
|
});
|
|
1394
1555
|
|
|
1556
|
+
const usageCardRows = this.usageCard ? renderUsageCardRows(this.usageCard, width) : [];
|
|
1395
1557
|
const planRows = this.planRows(width);
|
|
1396
1558
|
const pickerRows = this.completion ? this.pickerRows(width) : [];
|
|
1397
1559
|
this.pickerLayout = this.completion ? {
|
|
1398
|
-
pickerStart: planRows.length + boxRows.length,
|
|
1560
|
+
pickerStart: usageCardRows.length + planRows.length + boxRows.length,
|
|
1399
1561
|
pickerCount: pickerRows.length,
|
|
1400
1562
|
totalPromptRows: 0
|
|
1401
1563
|
} : null;
|
|
@@ -1409,7 +1571,7 @@ export class ChatPrompt {
|
|
|
1409
1571
|
const gap = status.length > 0 ? new Array(FOOTER_GAP).fill('') : [];
|
|
1410
1572
|
|
|
1411
1573
|
const all = this.clampRows(
|
|
1412
|
-
|
|
1574
|
+
usageCardRows.concat(planRows, boxRows, pickerRows, noticeRows, gap, status), width
|
|
1413
1575
|
);
|
|
1414
1576
|
if (this.pickerLayout) this.pickerLayout.totalPromptRows = all.length;
|
|
1415
1577
|
|
|
@@ -1420,7 +1582,7 @@ export class ChatPrompt {
|
|
|
1420
1582
|
const positioned = this.surface
|
|
1421
1583
|
? (this.surface.homeInfo ? centerRows(all, this.surface.width) : sessionRows(all, availableWidth))
|
|
1422
1584
|
: { rows: all, inset: 0 };
|
|
1423
|
-
this.present(positioned.rows, planRows.length + caretRow + padTop, layout.cursorCol + inset + positioned.inset);
|
|
1585
|
+
this.present(positioned.rows, usageCardRows.length + planRows.length + caretRow + padTop, layout.cursorCol + inset + positioned.inset);
|
|
1424
1586
|
}
|
|
1425
1587
|
|
|
1426
1588
|
/**
|
package/src/tui/stageSurface.js
CHANGED
|
@@ -400,9 +400,7 @@ export class StageSurface {
|
|
|
400
400
|
const sidebar = sidebarVisible(width);
|
|
401
401
|
const mainWidth = sessionMainWidth(width);
|
|
402
402
|
const rail = this.railEnabled(mainWidth);
|
|
403
|
-
const
|
|
404
|
-
const turnRailBudget = (rail && hasTurns) ? 3 : 0;
|
|
405
|
-
const contentWidth = rail ? Math.max(20, mainWidth - RAIL_BUDGET - turnRailBudget) : mainWidth;
|
|
403
|
+
const contentWidth = rail ? Math.max(20, mainWidth - RAIL_BUDGET) : mainWidth;
|
|
406
404
|
|
|
407
405
|
let block = promptRows;
|
|
408
406
|
let caretRow = caret && Number.isFinite(caret.row) ? caret.row : Math.max(0, block.length - 1);
|
|
@@ -646,13 +644,13 @@ export class StageSurface {
|
|
|
646
644
|
*/
|
|
647
645
|
attachRail(rows, contentWidth) {
|
|
648
646
|
const turns = collectSessionTurns(this.transcript, contentWidth);
|
|
647
|
+
const hasTurns = turns.length > 0;
|
|
649
648
|
const isAtBottom = typeof this.viewport?.atBottom === 'function' ? this.viewport.atBottom() : false;
|
|
650
649
|
const activeTurn = this.activeTurnIndex || resolveActiveTurnIndex(turns, this.viewport.state().scrollTop, rows.length, isAtBottom);
|
|
651
|
-
const railResult =
|
|
650
|
+
const railResult = hasTurns
|
|
652
651
|
? buildTurnRailCells(turns, rows.length, activeTurn, this.hoveredTurnIndex)
|
|
653
652
|
: null;
|
|
654
653
|
|
|
655
|
-
const hasTurns = turns.length > 0;
|
|
656
654
|
this.turnRailLayout = {
|
|
657
655
|
railX: hasTurns ? 1 : contentWidth + 1,
|
|
658
656
|
stageTop: (this.out.rows || this.stage.height) - this.stage.height,
|
|
@@ -665,12 +663,24 @@ export class StageSurface {
|
|
|
665
663
|
const rail = this.buildRail(rows.length, contentWidth);
|
|
666
664
|
for (let i = 0; i < rows.length; i++) {
|
|
667
665
|
const rightCell = rail[i] || ' ';
|
|
666
|
+
let row = rows[i] || '';
|
|
668
667
|
if (hasTurns && railResult) {
|
|
669
668
|
const leftCell = railResult.cells[i] || ' ';
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
669
|
+
if (leftCell !== ' ') {
|
|
670
|
+
if (row.startsWith(' ')) {
|
|
671
|
+
row = ` ${leftCell} ${row.slice(3)}`;
|
|
672
|
+
} else if (row.startsWith(' ')) {
|
|
673
|
+
row = ` ${leftCell}${row.slice(2)}`;
|
|
674
|
+
} else if (row.startsWith(' ')) {
|
|
675
|
+
row = ` ${leftCell}${row.slice(1)}`;
|
|
676
|
+
} else if (row.length > 0) {
|
|
677
|
+
row = ` ${leftCell} ${row}`;
|
|
678
|
+
} else {
|
|
679
|
+
row = ` ${leftCell} `;
|
|
680
|
+
}
|
|
681
|
+
}
|
|
673
682
|
}
|
|
683
|
+
rows[i] = `${padEnd(row, contentWidth)} ${rightCell}`;
|
|
674
684
|
}
|
|
675
685
|
return rows;
|
|
676
686
|
}
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Usage Card Banner: Docked status and token usage card rendered directly above the chatbox.
|
|
3
|
+
* Displays real-time session usage, all-time lifetime usage, daily spend, and context capacity.
|
|
4
|
+
*/
|
|
5
|
+
// @ts-expect-error theme.js has no TypeScript declaration yet.
|
|
6
|
+
import { paint, fill, bold, dim, GLYPHS, HAS_COLOR } from './theme.js';
|
|
7
|
+
import { visibleWidth, padEnd, truncate } from './text.js';
|
|
8
|
+
import { FRAME } from './overlay.js';
|
|
9
|
+
import { TokenTracker } from '../tokenTracker.js';
|
|
10
|
+
import { loadConfig } from '../config.js';
|
|
11
|
+
// @ts-expect-error reporting.js has no TypeScript declaration yet.
|
|
12
|
+
import { buildContextReport } from '../reporting.js';
|
|
13
|
+
import { isAntigravityProvider } from '../providers/antigravity.js';
|
|
14
|
+
import { isAcpProvider } from '../providers/acp.js';
|
|
15
|
+
function formatNumber(value) {
|
|
16
|
+
return Number(value || 0).toLocaleString('en-US');
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Render a visual progress bar for context capacity or token budget.
|
|
20
|
+
*/
|
|
21
|
+
export function renderProgressBar(percent, barLength = 24, invertColors = false) {
|
|
22
|
+
const clamped = Math.max(0, Math.min(100, Math.round(percent)));
|
|
23
|
+
const filledChars = Math.max(0, Math.min(barLength, Math.round((clamped / 100) * barLength)));
|
|
24
|
+
const emptyChars = Math.max(0, barLength - filledChars);
|
|
25
|
+
let role;
|
|
26
|
+
if (!invertColors) {
|
|
27
|
+
// Standard: higher percentage is good (e.g. % context remaining)
|
|
28
|
+
role = clamped >= 40 ? 'success' : (clamped >= 20 ? 'warn' : 'danger');
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
// Inverted: higher percentage is bad (e.g. % budget consumed)
|
|
32
|
+
role = clamped <= 60 ? 'success' : (clamped <= 85 ? 'warn' : 'danger');
|
|
33
|
+
}
|
|
34
|
+
const fillGlyph = GLYPHS.block || '█';
|
|
35
|
+
const emptyGlyph = GLYPHS.shadeLight || '░';
|
|
36
|
+
const filledPart = paint(role, fillGlyph.repeat(filledChars));
|
|
37
|
+
const emptyPart = dim(emptyGlyph.repeat(emptyChars));
|
|
38
|
+
return `${filledPart}${emptyPart}`;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Gather live usage and context accounting data from the session and token store.
|
|
42
|
+
*/
|
|
43
|
+
export async function collectUsageCardData(loop) {
|
|
44
|
+
const tracker = loop?.tokenTracker && typeof loop.tokenTracker.getReportedUsage === 'function'
|
|
45
|
+
? loop.tokenTracker
|
|
46
|
+
: new TokenTracker();
|
|
47
|
+
const reported = await tracker.getReportedUsage();
|
|
48
|
+
const cumulative = await tracker.getCumulativeUsage();
|
|
49
|
+
const daily = await tracker.getDailyUsage();
|
|
50
|
+
const config = loadConfig();
|
|
51
|
+
const provider = String(config.provider || 'default');
|
|
52
|
+
const model = String(config.model || 'default');
|
|
53
|
+
const isAgy = isAntigravityProvider(provider);
|
|
54
|
+
const isAcp = isAcpProvider(provider);
|
|
55
|
+
const billingNote = (isAgy || isAcp)
|
|
56
|
+
? 'Local CLI / ACP peer'
|
|
57
|
+
: 'BYOK (provider billed)';
|
|
58
|
+
// Context accounting
|
|
59
|
+
const contextReport = buildContextReport();
|
|
60
|
+
const poolTokens = Math.max(1, contextReport.approxTokenPool || 250000);
|
|
61
|
+
// Measure active messages tokens
|
|
62
|
+
let messageChars = 0;
|
|
63
|
+
let messageCount = 0;
|
|
64
|
+
const rawMessages = loop?.messages || (loop?.memoryManager ? loop.memoryManager.loadHistory() : []);
|
|
65
|
+
if (Array.isArray(rawMessages)) {
|
|
66
|
+
messageCount = rawMessages.length;
|
|
67
|
+
for (const msg of rawMessages) {
|
|
68
|
+
if (typeof msg?.content === 'string') {
|
|
69
|
+
messageChars += msg.content.length;
|
|
70
|
+
}
|
|
71
|
+
else if (Array.isArray(msg?.content)) {
|
|
72
|
+
for (const part of msg.content) {
|
|
73
|
+
if (typeof part === 'string')
|
|
74
|
+
messageChars += part.length;
|
|
75
|
+
else if (part?.text)
|
|
76
|
+
messageChars += String(part.text).length;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const messageTokens = Math.round(messageChars / 4);
|
|
82
|
+
const coreToolTokens = contextReport.core?.tokens || 5000;
|
|
83
|
+
const contextUsed = messageTokens + coreToolTokens;
|
|
84
|
+
const contextPctLeft = Math.max(0, Math.min(100, Math.round(((poolTokens - contextUsed) / poolTokens) * 100)));
|
|
85
|
+
// Budget
|
|
86
|
+
const budget = config.tokenBudget || {};
|
|
87
|
+
const budgetEnabled = Boolean(budget.enabled);
|
|
88
|
+
const budgetLimitTokens = Number(budget.maxTokensPerDay) || 0;
|
|
89
|
+
const budgetPercentUsed = budgetLimitTokens > 0
|
|
90
|
+
? Math.round((daily.totalTokens / budgetLimitTokens) * 100)
|
|
91
|
+
: 0;
|
|
92
|
+
const sessionId = String(loop?.memoryManager?.sessionId || 'default');
|
|
93
|
+
return {
|
|
94
|
+
sessionId,
|
|
95
|
+
sessionTurns: messageCount,
|
|
96
|
+
sessionTokens: tracker.sessionTokens || tracker.taskTokens || 0,
|
|
97
|
+
sessionCostUsd: tracker.sessionCostUsd || tracker.taskCostUsd || 0,
|
|
98
|
+
dailyTokens: daily.totalTokens,
|
|
99
|
+
dailyCostUsd: daily.totalCostUsd || 0,
|
|
100
|
+
lifetimeTokens: cumulative.totalTokens,
|
|
101
|
+
lifetimeCostUsd: cumulative.totalCostUsd || 0,
|
|
102
|
+
lifetimeCalls: cumulative.totalCalls || 0,
|
|
103
|
+
contextUsedTokens: contextUsed,
|
|
104
|
+
contextPoolTokens: poolTokens,
|
|
105
|
+
contextPercentLeft: contextPctLeft,
|
|
106
|
+
provider,
|
|
107
|
+
model,
|
|
108
|
+
billingNote,
|
|
109
|
+
budgetEnabled,
|
|
110
|
+
budgetLimitTokens,
|
|
111
|
+
budgetCostCeilingUsd: Number(budget.maxCostUsd) || undefined,
|
|
112
|
+
budgetPercentUsed
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Render the usage card as an array of styled terminal rows, exactly matching `width`.
|
|
117
|
+
*/
|
|
118
|
+
export function renderUsageCardRows(data, width) {
|
|
119
|
+
const frameWidth = Math.max(40, width);
|
|
120
|
+
const innerWidth = Math.max(20, frameWidth - 4); // border (1) + pad (1) on each side
|
|
121
|
+
const borderRole = 'accent';
|
|
122
|
+
const surfaceRole = 'surface';
|
|
123
|
+
// Header row
|
|
124
|
+
const title = ` ${bold(paint('accent', 'Usage & Context'))} `;
|
|
125
|
+
const closeHint = ` ${dim('esc close')} `;
|
|
126
|
+
const hLineLength = Math.max(0, frameWidth - 2 - visibleWidth(title) - visibleWidth(closeHint));
|
|
127
|
+
const topBorder = paint(borderRole, FRAME.tl + FRAME.h)
|
|
128
|
+
+ title
|
|
129
|
+
+ paint(borderRole, FRAME.h.repeat(hLineLength))
|
|
130
|
+
+ closeHint
|
|
131
|
+
+ paint(borderRole, FRAME.tr);
|
|
132
|
+
// Content lines inside card
|
|
133
|
+
const lines = [];
|
|
134
|
+
// 1. Session ID & Message count
|
|
135
|
+
const shortSession = data.sessionId.length > 24
|
|
136
|
+
? `${data.sessionId.slice(0, 10)}…${data.sessionId.slice(-10)}`
|
|
137
|
+
: data.sessionId;
|
|
138
|
+
lines.push(`${dim('Session/Chat :')} ${paint('ink', shortSession)} ${dim(`(${data.sessionTurns} messages)`)}`);
|
|
139
|
+
// 2. Context Window & Progress bar
|
|
140
|
+
const pBar = renderProgressBar(data.contextPercentLeft, 22, false);
|
|
141
|
+
lines.push(`${dim('Context :')} ${bold(`${data.contextPercentLeft}% left`)} ${dim(`(${formatNumber(data.contextUsedTokens)} used / ${formatNumber(data.contextPoolTokens)})`)} ${pBar}`);
|
|
142
|
+
// 3. This Session Usage
|
|
143
|
+
const sessionSpend = data.sessionCostUsd > 0
|
|
144
|
+
? ` ${dim(`$${data.sessionCostUsd.toFixed(4)} est`)}`
|
|
145
|
+
: '';
|
|
146
|
+
lines.push(`${dim('This Session :')} ${bold(formatNumber(data.sessionTokens))} tokens${sessionSpend}`);
|
|
147
|
+
// 4. Daily Usage (Today)
|
|
148
|
+
const dailySpend = data.dailyCostUsd > 0
|
|
149
|
+
? ` ${dim(`$${data.dailyCostUsd.toFixed(4)} est`)}`
|
|
150
|
+
: '';
|
|
151
|
+
lines.push(`${dim('Today (24h) :')} ${bold(formatNumber(data.dailyTokens))} tokens${dailySpend}`);
|
|
152
|
+
// 5. All-Time / Lifetime Usage
|
|
153
|
+
const lifeSpend = data.lifetimeCostUsd > 0
|
|
154
|
+
? ` ${dim(`$${data.lifetimeCostUsd.toFixed(4)} est`)}`
|
|
155
|
+
: '';
|
|
156
|
+
lines.push(`${dim('All-Time :')} ${bold(formatNumber(data.lifetimeTokens))} tokens${lifeSpend} ${dim(`(${formatNumber(data.lifetimeCalls)} calls)`)}`);
|
|
157
|
+
// 6. Model & Provider
|
|
158
|
+
lines.push(`${dim('Active Model :')} ${paint('accent', `${data.provider} / ${data.model}`)} ${dim(`(${data.billingNote})`)}`);
|
|
159
|
+
// 7. Optional Budget
|
|
160
|
+
if (data.budgetEnabled && data.budgetLimitTokens) {
|
|
161
|
+
const bBar = renderProgressBar(data.budgetPercentUsed || 0, 16, true);
|
|
162
|
+
lines.push(`${dim('Daily Budget :')} ${formatNumber(data.dailyTokens)} / ${formatNumber(data.budgetLimitTokens)} tokens (${data.budgetPercentUsed}% used) ${bBar}`);
|
|
163
|
+
}
|
|
164
|
+
// Construct boxed rows
|
|
165
|
+
const edge = paint(borderRole, FRAME.v);
|
|
166
|
+
const rows = [fill(surfaceRole, topBorder)];
|
|
167
|
+
for (const line of lines) {
|
|
168
|
+
const clipped = visibleWidth(line) > innerWidth ? truncate(line, innerWidth, GLYPHS.ellipsis) : line;
|
|
169
|
+
const padding = ' '.repeat(Math.max(0, innerWidth - visibleWidth(clipped)));
|
|
170
|
+
rows.push(fill(surfaceRole, `${edge} ${clipped}${padding} ${edge}`));
|
|
171
|
+
}
|
|
172
|
+
// Bottom row
|
|
173
|
+
const bottomBorder = paint(borderRole, FRAME.bl + FRAME.h.repeat(Math.max(0, frameWidth - 2)) + FRAME.br);
|
|
174
|
+
rows.push(fill(surfaceRole, bottomBorder));
|
|
175
|
+
// Add 1 blank row gap separating the usage card from the chatbox below
|
|
176
|
+
rows.push('');
|
|
177
|
+
return rows;
|
|
178
|
+
}
|