@causyne/agent 1.20.60 → 1.20.63

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.
Files changed (90) hide show
  1. package/README.md +2 -2
  2. package/package.json +1 -1
  3. package/src/acp/agentCatalog.js +1 -1
  4. package/src/acp/agentCatalog.ts +1 -1
  5. package/src/acp/client.js +48 -0
  6. package/src/acp/client.ts +44 -0
  7. package/src/acp/peerProfiles.js +3 -3
  8. package/src/acp/peerProfiles.ts +3 -3
  9. package/src/agentLoop.js +239 -33
  10. package/src/agentLoop.ts +248 -36
  11. package/src/checkpoints.js +23 -5
  12. package/src/cliMode.js +13 -2
  13. package/src/commands.js +534 -78
  14. package/src/contextManager.d.ts +3 -0
  15. package/src/contextManager.js +78 -5
  16. package/src/cortex/autoCondenser.js +105 -145
  17. package/src/cortex/autoCondenser.ts +185 -0
  18. package/src/cortex/cortexEngine.js +179 -0
  19. package/src/cortex/cortexEngine.ts +209 -0
  20. package/src/cortex/provisioner.js +12 -14
  21. package/src/cortex/provisioner.ts +29 -0
  22. package/src/cortex/vectorDb.js +307 -386
  23. package/src/cortex/vectorDb.ts +473 -0
  24. package/src/decisionPolicy.js +18 -1
  25. package/src/decisionPolicy.ts +18 -1
  26. package/src/implementationPlan.js +26 -0
  27. package/src/implementationPlan.ts +25 -0
  28. package/src/observer/coldObserver.js +6 -1
  29. package/src/observer/coldObserver.ts +6 -1
  30. package/src/observer.js +24 -2
  31. package/src/observer.ts +24 -2
  32. package/src/providers/acp.js +2 -8
  33. package/src/providers/acp.ts +2 -8
  34. package/src/providers/antigravity.js +7 -10
  35. package/src/providers/antigravity.ts +7 -10
  36. package/src/reporting.js +30 -7
  37. package/src/sessionJournal.js +13 -0
  38. package/src/sessionJournal.ts +13 -0
  39. package/src/smartToolsUse.js +1 -1
  40. package/src/smartToolsUse.ts +1 -1
  41. package/src/tokenTracker.js +22 -0
  42. package/src/tokenTracker.ts +28 -0
  43. package/src/toolPacks.js +1 -1
  44. package/src/toolPacks.ts +1 -1
  45. package/src/tools/toolSelfRepair.js +51 -8
  46. package/src/tools/toolSelfRepair.ts +42 -9
  47. package/src/tui/CausyneRotor.js +234 -0
  48. package/src/tui/CausyneRotor.ts +280 -0
  49. package/src/tui/activityLayout.js +1 -1
  50. package/src/tui/activityLayout.ts +1 -1
  51. package/src/tui/chatRenderer.js +62 -9
  52. package/src/tui/chatboxClipboard.js +96 -10
  53. package/src/tui/chatboxClipboard.ts +121 -11
  54. package/src/tui/clipboardImage.js +308 -0
  55. package/src/tui/clipboardImage.ts +320 -0
  56. package/src/tui/codeStreamRenderer.js +89 -1
  57. package/src/tui/codeStreamRenderer.ts +109 -1
  58. package/src/tui/completion.js +34 -15
  59. package/src/tui/composerControls.js +5 -0
  60. package/src/tui/composerControls.ts +5 -0
  61. package/src/tui/dialogs.js +5 -2
  62. package/src/tui/engineSpinner.js +20 -0
  63. package/src/tui/engineSpinner.ts +46 -0
  64. package/src/tui/layout.js +1 -1
  65. package/src/tui/layout.ts +1 -1
  66. package/src/tui/lineEditor.js +44 -12
  67. package/src/tui/messageInteraction.js +16 -5
  68. package/src/tui/messageInteraction.ts +14 -5
  69. package/src/tui/observerPicker.js +319 -0
  70. package/src/tui/observerPicker.ts +382 -0
  71. package/src/tui/prompt.js +247 -55
  72. package/src/tui/runningLight.js +213 -0
  73. package/src/tui/runningLight.ts +271 -0
  74. package/src/tui/sessionSidebar.js +7 -1
  75. package/src/tui/sessionSidebar.ts +7 -1
  76. package/src/tui/stage.js +4 -4
  77. package/src/tui/stageSurface.js +27 -10
  78. package/src/tui/statusLine.js +27 -4
  79. package/src/tui/statusLine.ts +27 -4
  80. package/src/tui/theme.js +5 -2
  81. package/src/tui/thinkingBox.js +41 -10
  82. package/src/tui/thinkingBox.ts +43 -10
  83. package/src/tui/turnRail.js +155 -24
  84. package/src/tui/turnRail.ts +170 -22
  85. package/src/tui/usageCard.js +178 -0
  86. package/src/tui/usageCard.ts +240 -0
  87. package/src/utils/paths.js +30 -1
  88. package/src/utils/paths.ts +32 -1
  89. package/src/cortex/autoCondenser.d.ts +0 -2
  90. package/src/cortex/vectorDb.d.ts +0 -1
@@ -19,6 +19,8 @@ export interface TurnRailLayout {
19
19
  viewportHeight: number;
20
20
  dotRows: Map<number, number>; // turnIndex -> screenY
21
21
  rowToTurn: Map<number, number>; // screenY -> turnIndex
22
+ turns?: SessionTurn[];
23
+ cardRect?: { x: number; y: number; width: number; height: number; turnIndex: number } | null;
22
24
  }
23
25
 
24
26
  export function formatTurnTimestamp(ts: number): string {
@@ -100,7 +102,7 @@ export function collectSessionTurns(transcript: any, contentWidth = 80): Session
100
102
  turnIndex,
101
103
  totalTurns,
102
104
  userPrompt: userPrompt.replace(/\s+/g, ' ').trim(),
103
- assistantSummary: assistantSummary.replace(/\s+/g, ' ').trim(),
105
+ assistantSummary: formatPreviewCardMarkdown(assistantSummary),
104
106
  timestamp: frame.ts || Date.now(),
105
107
  formattedDate: formatTurnTimestamp(frame.ts || Date.now()),
106
108
  frameId: frame.id,
@@ -251,6 +253,65 @@ export function buildTurnRailCells(
251
253
  return { cells, layout: { dotRows, rowToTurn } };
252
254
  }
253
255
 
256
+ /**
257
+ * Render and clean markdown for display within the Floating Turn Preview Card.
258
+ * Strips raw syntax markers (###, **, *, `, table delimiters) and renders
259
+ * clean, readable, professional text without leaking markdown source code.
260
+ */
261
+ export function formatPreviewCardMarkdown(raw: string): string {
262
+ if (!raw) return '';
263
+ let text = String(raw);
264
+
265
+ // Strip code block fences
266
+ text = text.replace(/```[a-zA-Z0-9_-]*\n?/g, ' ');
267
+
268
+ // Strip headings: ### Heading -> Heading
269
+ text = text.replace(/(?:^|\n)\s*#{1,6}\s+/g, '\n');
270
+
271
+ // Strip blockquotes: > quote -> quote
272
+ text = text.replace(/(?:^|\n)\s*>\s?/g, '\n');
273
+
274
+ // Strip horizontal rules: --- or ***
275
+ text = text.replace(/(?:^|\n)\s*[-*_]{3,}\s*(?=\n|$)/g, '\n');
276
+
277
+ // Strip table separator lines: | :--- | :--- |
278
+ text = text.replace(/(?:^|\n)\s*\|?(\s*:?-+:?\s*\|)+\s*(?=\n|$)/g, '\n');
279
+
280
+ // Convert table row pipes: | a | b | -> a · b
281
+ text = text.replace(/(?:^|\n)\s*\|\s*(.+?)\s*\|\s*(?=\n|$)/g, (_m, content) => {
282
+ return '\n' + content.split(/\s*\|\s*/).filter(Boolean).join(' · ');
283
+ });
284
+
285
+ // Convert list bullets: - item, * item -> • item
286
+ text = text.replace(/(?:^|\n)\s*[-*+]\s+/g, '\n• ');
287
+
288
+ // Convert numbered lists: 1. item -> 1. item
289
+ text = text.replace(/(?:^|\n)\s*(\d+)\.\s+/g, '\n$1. ');
290
+
291
+ // Strip links: [label](url) -> label
292
+ text = text.replace(/\[([^\]\n]+)\]\([^\)\s]+\)/g, '$1');
293
+
294
+ // Strip images: ![alt](url) -> alt
295
+ text = text.replace(/!\[([^\]\n]*)\]\([^\)\s]+\)/g, '$1');
296
+
297
+ // Strip inline code backticks: `code` -> code
298
+ text = text.replace(/`([^`\n]+)`/g, '$1');
299
+
300
+ // Format bold and italic: ***text***, **text**, *text*, ___text___, __text__, _text_
301
+ text = text.replace(/\*\*\*([^*]+)\*\*\*/g, '$1');
302
+ text = text.replace(/\*\*([^*]+)\*\*/g, '$1');
303
+ text = text.replace(/(?:^|[^*])\*([^*]+)\*(?!\*)/g, (m, inner) => m.startsWith('*') ? inner : `${m[0]}${inner}`);
304
+ text = text.replace(/___([^_]+)___/g, '$1');
305
+ text = text.replace(/__([^_]+)__/g, '$1');
306
+ text = text.replace(/(?:^|[^_])_([^_]+)_(?!_)/g, (m, inner) => m.startsWith('_') ? inner : `${m[0]}${inner}`);
307
+
308
+ // Strip strikethrough: ~~text~~ -> text
309
+ text = text.replace(/~~([^~]+)~~/g, '$1');
310
+
311
+ // Collapse multiple spaces/newlines cleanly into single space
312
+ return text.replace(/\s+/g, ' ').trim();
313
+ }
314
+
254
315
  /**
255
316
  * Render the Floating Turn Preview Card popover.
256
317
  * Exactly matches the UX/UI in Screen Recording 2026-10-30 at 02.42.17:
@@ -267,17 +328,18 @@ export function renderTurnPreviewCard(turn: SessionTurn, maxCardWidth = 50): str
267
328
  const borderStyle = `${cardBg}\x1b[38;2;75;75;82m`;
268
329
  const reset = '\x1b[0m';
269
330
 
270
- // Format header: User Prompt (bold primary)
271
- const rawPrompt = turn.userPrompt || 'User request';
272
- const promptLines = wrapBlock(rawPrompt, innerWidth).slice(0, 2);
331
+ // Format header: User Prompt (bold primary) rendered cleanly without raw markdown, strictly flush-left with hang: 0
332
+ const rawPrompt = formatPreviewCardMarkdown(turn.userPrompt || 'User request');
333
+ const promptLines = wrapBlock(rawPrompt, innerWidth, { hang: 0 }).slice(0, 2);
273
334
  if (promptLines.length === 2 && promptLines[1]) {
274
335
  promptLines[1] = truncate(promptLines[1], innerWidth - 3, '...');
275
336
  }
276
337
 
277
- // Format body: Assistant Summary (muted secondary)
338
+ // Format body: Assistant Summary (muted secondary) rendered cleanly without raw markdown, strictly flush-left with hang: 0
278
339
  let bodyLines: string[] = [];
279
340
  if (turn.assistantSummary) {
280
- bodyLines = wrapBlock(turn.assistantSummary, innerWidth).slice(0, 3);
341
+ const formattedSummary = formatPreviewCardMarkdown(turn.assistantSummary);
342
+ bodyLines = wrapBlock(formattedSummary, innerWidth, { hang: 0 }).slice(0, 3);
281
343
  if (bodyLines.length === 3 && bodyLines[2]) {
282
344
  bodyLines[2] = truncate(bodyLines[2], innerWidth - 3, '...');
283
345
  }
@@ -335,10 +397,11 @@ export function overlayTurnPreviewCard(
335
397
  if (cardRows.length === 0 || viewportRows.length === 0) return viewportRows;
336
398
 
337
399
  const cardWidth = visibleWidth(cardRows[0] || '');
338
- // Clamp card placement horizontally: preferably to the left of the rail, or to the right
400
+ // Clamp card placement horizontally: flush-left with transcript baseline at column 3
401
+ const cardSpacing = 2; // railX + 2 gives x = 3, perfectly flush left with transcript content
339
402
  let x = railX - cardWidth - 1;
340
- if (x < 0 || (railX <= 4 && railX + 3 + cardWidth <= screenWidth)) {
341
- x = Math.max(0, Math.min(screenWidth - cardWidth - 1, railX + 3));
403
+ if (x < 0 || (railX <= 4 && railX + cardSpacing + cardWidth <= screenWidth)) {
404
+ x = Math.max(0, Math.min(screenWidth - cardWidth - 1, railX + cardSpacing));
342
405
  }
343
406
 
344
407
  // Center vertically around anchorY
@@ -354,10 +417,39 @@ export function overlayTurnPreviewCard(
354
417
  const baseRow = out[targetY] || '';
355
418
  const cardRow = cardRows[i] || '';
356
419
 
357
- // Composite cardRow onto baseRow at column x
358
- const beforePart = padEnd(truncate(baseRow, x, ''), x);
359
- const afterPart = sliceFromColumn(baseRow, x + cardWidth);
360
- out[targetY] = `${beforePart}${cardRow}${afterPart}`;
420
+ // Composite cardRow onto baseRow at column x.
421
+ // To the left of the card, NEVER allow severed underlying characters (like '▸' or text) to leak!
422
+ // Maintain a perfectly clean, flush, symmetrical margin:
423
+ // Only preserve the rail dot (if present at railX) and whitespace padding up to column x.
424
+ let beforePart = '';
425
+ if (x <= 6 && railX <= 4) {
426
+ const plainBase = stripAnsi(baseRow);
427
+ const dotChar = plainBase[railX] || ' ';
428
+ const isDot = dotChar === '●' || dotChar === '•' || dotChar === '·' || dotChar === '[' || dotChar === ']';
429
+ let dotCell = ' ';
430
+ if (isDot) {
431
+ const sliceDot = sliceFromColumn(baseRow, railX);
432
+ dotCell = sliceDot ? truncate(sliceDot, 1, '') : dotChar;
433
+ }
434
+ const leadingSpace = ' '.repeat(Math.max(0, railX));
435
+ const trailingSpace = ' '.repeat(Math.max(0, x - railX - 1));
436
+ beforePart = `${leadingSpace}${dotCell}${trailingSpace}`;
437
+ } else {
438
+ beforePart = padEnd(truncate(baseRow, x, ''), x);
439
+ }
440
+
441
+ let restOfRow = '';
442
+ if (x <= 6) {
443
+ // For left-placed turn cards, do not leave severed text tails sticking out
444
+ const totalRowWidth = Math.max(screenWidth, visibleWidth(baseRow));
445
+ const rightCell = sliceFromColumn(baseRow, totalRowWidth - 1);
446
+ const rightCellWidth = visibleWidth(rightCell);
447
+ const gap = Math.max(0, totalRowWidth - x - cardWidth - rightCellWidth);
448
+ restOfRow = `${' '.repeat(gap)}${rightCell}`;
449
+ } else {
450
+ restOfRow = sliceFromColumn(baseRow, x + cardWidth);
451
+ }
452
+ out[targetY] = `${beforePart}${cardRow}${restOfRow}`;
361
453
  }
362
454
 
363
455
  return out;
@@ -388,27 +480,72 @@ export function handleTurnRailMouse(
388
480
  ? (mouseX >= 0 && mouseX <= Math.max(3, layout.railX + 2))
389
481
  : (mouseX >= layout.railX - 1 && mouseX <= layout.railX + 2);
390
482
 
391
- if (!isRail || relY < 0 || relY >= layout.viewportHeight) {
483
+ // Check if currently showing a card and mouse is hovering over the card or bridge tunnel
484
+ const hasActiveCard = surface.hoveredTurnIndex !== null && surface.hoveredTurnIndex !== undefined;
485
+ let isCard = false;
486
+ let isBridge = false;
487
+
488
+ if (hasActiveCard) {
489
+ const cardRect = layout.cardRect;
490
+ if (cardRect && cardRect.turnIndex === surface.hoveredTurnIndex) {
491
+ isCard = mouseX >= cardRect.x && mouseX < cardRect.x + cardRect.width &&
492
+ relY >= cardRect.y && relY < cardRect.y + cardRect.height;
493
+ isBridge = layout.railX <= 4 &&
494
+ mouseX >= 0 && mouseX < cardRect.x &&
495
+ relY >= cardRect.y && relY < cardRect.y + cardRect.height;
496
+ } else {
497
+ const cardWidth = 52;
498
+ const cardX = layout.railX <= 4 ? layout.railX + 2 : Math.max(0, layout.railX - cardWidth - 1);
499
+ const anchorY = surface.hoveredTurnAnchorY ?? Math.floor(layout.viewportHeight / 2);
500
+ const cardHeight = 9;
501
+ const cardStartY = Math.max(0, Math.min(layout.viewportHeight - cardHeight, anchorY - Math.floor(cardHeight / 2)));
502
+ const cardEndY = cardStartY + cardHeight;
503
+
504
+ isCard = mouseX >= cardX && mouseX < cardX + cardWidth &&
505
+ relY >= cardStartY && relY < cardEndY;
506
+ isBridge = layout.railX <= 4 &&
507
+ mouseX >= 0 && mouseX < cardX &&
508
+ relY >= cardStartY && relY < cardEndY;
509
+ }
510
+ }
511
+
512
+ const inHoverZone = isRail || isCard || isBridge;
513
+
514
+ if (!inHoverZone || relY < 0 || relY >= layout.viewportHeight) {
392
515
  surface.turnRailHoverSuppressed = false;
393
516
  if (surface.hoveredTurnIndex !== null && surface.hoveredTurnIndex !== undefined) {
394
- surface.hoveredTurnIndex = null;
395
- surface.hoveredTurnAnchorY = null;
396
- if (typeof host?.scheduleDraw === 'function') host.scheduleDraw();
397
- else if (typeof host?.draw === 'function') host.draw();
517
+ if (!surface._turnCardLeaveTimer) {
518
+ surface._turnCardLeaveTimer = setTimeout(() => {
519
+ surface._turnCardLeaveTimer = null;
520
+ if (surface.hoveredTurnIndex !== null && surface.hoveredTurnIndex !== undefined) {
521
+ surface.hoveredTurnIndex = null;
522
+ surface.hoveredTurnAnchorY = null;
523
+ if (typeof host?.scheduleDraw === 'function') host.scheduleDraw();
524
+ else if (typeof host?.draw === 'function') host.draw();
525
+ }
526
+ }, 120);
527
+ }
398
528
  }
399
529
  return false;
400
530
  }
401
531
 
532
+ // Inside hover zone - cancel any pending leave timer
533
+ if (surface._turnCardLeaveTimer) {
534
+ clearTimeout(surface._turnCardLeaveTimer);
535
+ surface._turnCardLeaveTimer = null;
536
+ }
537
+
402
538
  // If hover is temporarily suppressed after a click, swallow rail mouse events until suppression ends
403
539
  if (surface.turnRailHoverSuppressed) {
404
540
  return true;
405
541
  }
406
542
 
407
- let turnNum = layout.rowToTurn?.get(relY);
543
+ // Rail takes precedence when mouse is on the rail track
544
+ let turnNum = isRail ? layout.rowToTurn?.get(relY) : ((isCard || isBridge) ? surface.hoveredTurnIndex : undefined);
408
545
  let anchorY = relY;
409
546
 
410
- // If not an exact row hit, resolve closest dot within proximity
411
- if (!turnNum && layout.dotRows && layout.dotRows.size > 0) {
547
+ // If on rail and not an exact row hit, resolve closest dot within proximity
548
+ if (!turnNum && isRail && layout.dotRows && layout.dotRows.size > 0) {
412
549
  let minDistance = Infinity;
413
550
  let closestTurn: number | undefined;
414
551
  let closestRow: number | undefined;
@@ -422,7 +559,7 @@ export function handleTurnRailMouse(
422
559
  }
423
560
  }
424
561
 
425
- if (minDistance <= 2 && closestTurn !== undefined && closestRow !== undefined) {
562
+ if (minDistance <= 1 && closestTurn !== undefined && closestRow !== undefined) {
426
563
  turnNum = closestTurn;
427
564
  anchorY = closestRow;
428
565
  }
@@ -430,6 +567,17 @@ export function handleTurnRailMouse(
430
567
 
431
568
  if (turnNum) {
432
569
  if (isMouseMotion(event.sequence)) {
570
+ // While a turn is streaming, a hover card would sit on top of live output
571
+ // (thinking, code edits, tool frames). Clicking a dot still navigates.
572
+ if (host?.busy) {
573
+ if (surface.hoveredTurnIndex !== null && surface.hoveredTurnIndex !== undefined) {
574
+ surface.hoveredTurnIndex = null;
575
+ surface.hoveredTurnAnchorY = null;
576
+ if (typeof host?.scheduleDraw === 'function') host.scheduleDraw();
577
+ else if (typeof host?.draw === 'function') host.draw();
578
+ }
579
+ return true;
580
+ }
433
581
  if (surface.hoveredTurnIndex !== turnNum) {
434
582
  surface.hoveredTurnIndex = turnNum;
435
583
  surface.hoveredTurnAnchorY = anchorY;
@@ -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
+ }