@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.
Files changed (41) hide show
  1. package/package.json +1 -1
  2. package/src/acp/agentCatalog.js +1 -1
  3. package/src/acp/agentCatalog.ts +1 -1
  4. package/src/acp/peerProfiles.js +3 -3
  5. package/src/acp/peerProfiles.ts +3 -3
  6. package/src/agentLoop.js +58 -22
  7. package/src/agentLoop.ts +64 -25
  8. package/src/checkpoints.js +23 -5
  9. package/src/cliMode.js +4 -2
  10. package/src/commands.js +503 -78
  11. package/src/contextManager.d.ts +3 -0
  12. package/src/contextManager.js +78 -5
  13. package/src/cortex/autoCondenser.js +105 -145
  14. package/src/cortex/autoCondenser.ts +185 -0
  15. package/src/cortex/cortexEngine.js +179 -0
  16. package/src/cortex/cortexEngine.ts +209 -0
  17. package/src/cortex/provisioner.js +12 -14
  18. package/src/cortex/provisioner.ts +29 -0
  19. package/src/cortex/vectorDb.js +307 -386
  20. package/src/cortex/vectorDb.ts +473 -0
  21. package/src/reporting.js +30 -7
  22. package/src/sessionJournal.js +13 -0
  23. package/src/sessionJournal.ts +13 -0
  24. package/src/tokenTracker.js +22 -0
  25. package/src/tokenTracker.ts +28 -0
  26. package/src/tui/chatRenderer.js +6 -2
  27. package/src/tui/completion.js +34 -15
  28. package/src/tui/composerControls.js +5 -0
  29. package/src/tui/composerControls.ts +5 -0
  30. package/src/tui/layout.js +1 -1
  31. package/src/tui/layout.ts +1 -1
  32. package/src/tui/observerPicker.js +323 -0
  33. package/src/tui/observerPicker.ts +386 -0
  34. package/src/tui/prompt.js +184 -22
  35. package/src/tui/stageSurface.js +18 -8
  36. package/src/tui/usageCard.js +178 -0
  37. package/src/tui/usageCard.ts +240 -0
  38. package/src/utils/paths.js +30 -1
  39. package/src/utils/paths.ts +32 -1
  40. package/src/cortex/autoCondenser.d.ts +0 -2
  41. package/src/cortex/vectorDb.d.ts +0 -1
@@ -0,0 +1,240 @@
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
+
6
+ // @ts-expect-error theme.js has no TypeScript declaration yet.
7
+ import { paint, fill, bold, dim, GLYPHS, HAS_COLOR } from './theme.js';
8
+ import { visibleWidth, padEnd, truncate } from './text.js';
9
+ import { FRAME } from './overlay.js';
10
+ import { TokenTracker } from '../tokenTracker.js';
11
+ import { loadConfig } from '../config.js';
12
+ // @ts-expect-error reporting.js has no TypeScript declaration yet.
13
+ import { buildContextReport } from '../reporting.js';
14
+ import { isAntigravityProvider } from '../providers/antigravity.js';
15
+ import { isAcpProvider } from '../providers/acp.js';
16
+
17
+ export interface UsageCardData {
18
+ sessionId: string;
19
+ sessionTurns: number;
20
+ sessionTokens: number;
21
+ sessionCostUsd: number;
22
+ dailyTokens: number;
23
+ dailyCostUsd: number;
24
+ lifetimeTokens: number;
25
+ lifetimeCostUsd: number;
26
+ lifetimeCalls: number;
27
+ contextUsedTokens: number;
28
+ contextPoolTokens: number;
29
+ contextPercentLeft: number;
30
+ provider: string;
31
+ model: string;
32
+ billingNote: string;
33
+ budgetEnabled: boolean;
34
+ budgetLimitTokens?: number | undefined;
35
+ budgetCostCeilingUsd?: number | undefined;
36
+ budgetPercentUsed?: number | undefined;
37
+ }
38
+
39
+ function formatNumber(value: number | undefined | null): string {
40
+ return Number(value || 0).toLocaleString('en-US');
41
+ }
42
+
43
+ /**
44
+ * Render a visual progress bar for context capacity or token budget.
45
+ */
46
+ export function renderProgressBar(percent: number, barLength: number = 24, invertColors: boolean = false): string {
47
+ const clamped = Math.max(0, Math.min(100, Math.round(percent)));
48
+ const filledChars = Math.max(0, Math.min(barLength, Math.round((clamped / 100) * barLength)));
49
+ const emptyChars = Math.max(0, barLength - filledChars);
50
+
51
+ let role: string;
52
+ if (!invertColors) {
53
+ // Standard: higher percentage is good (e.g. % context remaining)
54
+ role = clamped >= 40 ? 'success' : (clamped >= 20 ? 'warn' : 'danger');
55
+ } else {
56
+ // Inverted: higher percentage is bad (e.g. % budget consumed)
57
+ role = clamped <= 60 ? 'success' : (clamped <= 85 ? 'warn' : 'danger');
58
+ }
59
+
60
+ const fillGlyph = GLYPHS.block || '█';
61
+ const emptyGlyph = GLYPHS.shadeLight || '░';
62
+
63
+ const filledPart = paint(role, fillGlyph.repeat(filledChars));
64
+ const emptyPart = dim(emptyGlyph.repeat(emptyChars));
65
+ return `${filledPart}${emptyPart}`;
66
+ }
67
+
68
+ /**
69
+ * Gather live usage and context accounting data from the session and token store.
70
+ */
71
+ export async function collectUsageCardData(loop?: any): Promise<UsageCardData> {
72
+ const tracker = loop?.tokenTracker && typeof loop.tokenTracker.getReportedUsage === 'function'
73
+ ? loop.tokenTracker
74
+ : new TokenTracker();
75
+
76
+ const reported = await tracker.getReportedUsage();
77
+ const cumulative = await tracker.getCumulativeUsage();
78
+ const daily = await tracker.getDailyUsage();
79
+ const config = loadConfig() as Record<string, any>;
80
+
81
+ const provider = String(config.provider || 'default');
82
+ const model = String(config.model || 'default');
83
+ const isAgy = isAntigravityProvider(provider);
84
+ const isAcp = isAcpProvider(provider);
85
+ const billingNote = (isAgy || isAcp)
86
+ ? 'Local CLI / ACP peer'
87
+ : 'BYOK (provider billed)';
88
+
89
+ // Context accounting
90
+ const contextReport = buildContextReport();
91
+ const poolTokens = Math.max(1, contextReport.approxTokenPool || 250000);
92
+
93
+ // Measure active messages tokens
94
+ let messageChars = 0;
95
+ let messageCount = 0;
96
+ const rawMessages = loop?.messages || (loop?.memoryManager ? loop.memoryManager.loadHistory() : []);
97
+ if (Array.isArray(rawMessages)) {
98
+ messageCount = rawMessages.length;
99
+ for (const msg of rawMessages) {
100
+ if (typeof msg?.content === 'string') {
101
+ messageChars += msg.content.length;
102
+ } else if (Array.isArray(msg?.content)) {
103
+ for (const part of msg.content) {
104
+ if (typeof part === 'string') messageChars += part.length;
105
+ else if (part?.text) messageChars += String(part.text).length;
106
+ }
107
+ }
108
+ }
109
+ }
110
+
111
+ const messageTokens = Math.round(messageChars / 4);
112
+ const coreToolTokens = contextReport.core?.tokens || 5000;
113
+ const contextUsed = messageTokens + coreToolTokens;
114
+ const contextPctLeft = Math.max(0, Math.min(100, Math.round(((poolTokens - contextUsed) / poolTokens) * 100)));
115
+
116
+ // Budget
117
+ const budget = config.tokenBudget || {};
118
+ const budgetEnabled = Boolean(budget.enabled);
119
+ const budgetLimitTokens = Number(budget.maxTokensPerDay) || 0;
120
+ const budgetPercentUsed = budgetLimitTokens > 0
121
+ ? Math.round((daily.totalTokens / budgetLimitTokens) * 100)
122
+ : 0;
123
+
124
+ const sessionId = String(loop?.memoryManager?.sessionId || 'default');
125
+
126
+ return {
127
+ sessionId,
128
+ sessionTurns: messageCount,
129
+ sessionTokens: tracker.sessionTokens || tracker.taskTokens || 0,
130
+ sessionCostUsd: tracker.sessionCostUsd || tracker.taskCostUsd || 0,
131
+ dailyTokens: daily.totalTokens,
132
+ dailyCostUsd: daily.totalCostUsd || 0,
133
+ lifetimeTokens: cumulative.totalTokens,
134
+ lifetimeCostUsd: cumulative.totalCostUsd || 0,
135
+ lifetimeCalls: cumulative.totalCalls || 0,
136
+ contextUsedTokens: contextUsed,
137
+ contextPoolTokens: poolTokens,
138
+ contextPercentLeft: contextPctLeft,
139
+ provider,
140
+ model,
141
+ billingNote,
142
+ budgetEnabled,
143
+ budgetLimitTokens,
144
+ budgetCostCeilingUsd: Number(budget.maxCostUsd) || undefined,
145
+ budgetPercentUsed
146
+ };
147
+ }
148
+
149
+ /**
150
+ * Render the usage card as an array of styled terminal rows, exactly matching `width`.
151
+ */
152
+ export function renderUsageCardRows(data: UsageCardData, width: number): string[] {
153
+ const frameWidth = Math.max(40, width);
154
+ const innerWidth = Math.max(20, frameWidth - 4); // border (1) + pad (1) on each side
155
+ const borderRole = 'accent';
156
+ const surfaceRole = 'surface';
157
+
158
+ // Header row
159
+ const title = ` ${bold(paint('accent', 'Usage & Context'))} `;
160
+ const closeHint = ` ${dim('esc close')} `;
161
+ const hLineLength = Math.max(0, frameWidth - 2 - visibleWidth(title) - visibleWidth(closeHint));
162
+ const topBorder = paint(borderRole, FRAME.tl + FRAME.h)
163
+ + title
164
+ + paint(borderRole, FRAME.h.repeat(hLineLength))
165
+ + closeHint
166
+ + paint(borderRole, FRAME.tr);
167
+
168
+ // Content lines inside card
169
+ const lines: string[] = [];
170
+
171
+ // 1. Session ID & Message count
172
+ const shortSession = data.sessionId.length > 24
173
+ ? `${data.sessionId.slice(0, 10)}…${data.sessionId.slice(-10)}`
174
+ : data.sessionId;
175
+ lines.push(
176
+ `${dim('Session/Chat :')} ${paint('ink', shortSession)} ${dim(`(${data.sessionTurns} messages)`)}`
177
+ );
178
+
179
+ // 2. Context Window & Progress bar
180
+ const pBar = renderProgressBar(data.contextPercentLeft, 22, false);
181
+ lines.push(
182
+ `${dim('Context :')} ${bold(`${data.contextPercentLeft}% left`)} ${dim(`(${formatNumber(data.contextUsedTokens)} used / ${formatNumber(data.contextPoolTokens)})`)} ${pBar}`
183
+ );
184
+
185
+ // 3. This Session Usage
186
+ const sessionSpend = data.sessionCostUsd > 0
187
+ ? ` ${dim(`$${data.sessionCostUsd.toFixed(4)} est`)}`
188
+ : '';
189
+ lines.push(
190
+ `${dim('This Session :')} ${bold(formatNumber(data.sessionTokens))} tokens${sessionSpend}`
191
+ );
192
+
193
+ // 4. Daily Usage (Today)
194
+ const dailySpend = data.dailyCostUsd > 0
195
+ ? ` ${dim(`$${data.dailyCostUsd.toFixed(4)} est`)}`
196
+ : '';
197
+ lines.push(
198
+ `${dim('Today (24h) :')} ${bold(formatNumber(data.dailyTokens))} tokens${dailySpend}`
199
+ );
200
+
201
+ // 5. All-Time / Lifetime Usage
202
+ const lifeSpend = data.lifetimeCostUsd > 0
203
+ ? ` ${dim(`$${data.lifetimeCostUsd.toFixed(4)} est`)}`
204
+ : '';
205
+ lines.push(
206
+ `${dim('All-Time :')} ${bold(formatNumber(data.lifetimeTokens))} tokens${lifeSpend} ${dim(`(${formatNumber(data.lifetimeCalls)} calls)`)}`
207
+ );
208
+
209
+ // 6. Model & Provider
210
+ lines.push(
211
+ `${dim('Active Model :')} ${paint('accent', `${data.provider} / ${data.model}`)} ${dim(`(${data.billingNote})`)}`
212
+ );
213
+
214
+ // 7. Optional Budget
215
+ if (data.budgetEnabled && data.budgetLimitTokens) {
216
+ const bBar = renderProgressBar(data.budgetPercentUsed || 0, 16, true);
217
+ lines.push(
218
+ `${dim('Daily Budget :')} ${formatNumber(data.dailyTokens)} / ${formatNumber(data.budgetLimitTokens)} tokens (${data.budgetPercentUsed}% used) ${bBar}`
219
+ );
220
+ }
221
+
222
+ // Construct boxed rows
223
+ const edge = paint(borderRole, FRAME.v);
224
+ const rows: string[] = [fill(surfaceRole, topBorder)];
225
+
226
+ for (const line of lines) {
227
+ const clipped = visibleWidth(line) > innerWidth ? truncate(line, innerWidth, GLYPHS.ellipsis) : line;
228
+ const padding = ' '.repeat(Math.max(0, innerWidth - visibleWidth(clipped)));
229
+ rows.push(fill(surfaceRole, `${edge} ${clipped}${padding} ${edge}`));
230
+ }
231
+
232
+ // Bottom row
233
+ const bottomBorder = paint(borderRole, FRAME.bl + FRAME.h.repeat(Math.max(0, frameWidth - 2)) + FRAME.br);
234
+ rows.push(fill(surfaceRole, bottomBorder));
235
+
236
+ // Add 1 blank row gap separating the usage card from the chatbox below
237
+ rows.push('');
238
+
239
+ return rows;
240
+ }
@@ -1,5 +1,20 @@
1
+ import fs from 'node:fs';
1
2
  import os from 'node:os';
2
3
  import path from 'node:path';
4
+ function isTempHome(dir) {
5
+ const normalized = path.resolve(dir);
6
+ const tmp = path.resolve(os.tmpdir());
7
+ return (normalized.startsWith(tmp) ||
8
+ normalized.startsWith('/tmp/') ||
9
+ normalized.startsWith('/private/tmp/') ||
10
+ normalized.startsWith('/var/folders/') ||
11
+ normalized.startsWith('/private/var/folders/'));
12
+ }
13
+ function isNodeTestRunner() {
14
+ if (process.env['NODE_TEST_CONTEXT'])
15
+ return true;
16
+ return process.execArgv.some((arg) => arg === '--test' || arg.startsWith('--test-'));
17
+ }
3
18
  /**
4
19
  * Resolve a path the model supplied, expanding a leading `~`.
5
20
  *
@@ -31,5 +46,19 @@ export function causyneHome() {
31
46
  if (envHome && String(envHome).trim()) {
32
47
  return path.resolve(String(envHome).trim());
33
48
  }
34
- return path.join(os.homedir(), '.causyne');
49
+ const home = os.homedir();
50
+ if (isNodeTestRunner() && !isTempHome(home)) {
51
+ const fallbackRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'causyne-test-auto-'));
52
+ process.env['CAUSYNE_HOME'] = fallbackRoot;
53
+ process.once('exit', () => {
54
+ try {
55
+ fs.rmSync(fallbackRoot, { recursive: true, force: true });
56
+ }
57
+ catch {
58
+ // Best-effort cleanup
59
+ }
60
+ });
61
+ return fallbackRoot;
62
+ }
63
+ return path.join(home, '.causyne');
35
64
  }
@@ -1,6 +1,24 @@
1
+ import fs from 'node:fs';
1
2
  import os from 'node:os';
2
3
  import path from 'node:path';
3
4
 
5
+ function isTempHome(dir: string): boolean {
6
+ const normalized = path.resolve(dir);
7
+ const tmp = path.resolve(os.tmpdir());
8
+ return (
9
+ normalized.startsWith(tmp) ||
10
+ normalized.startsWith('/tmp/') ||
11
+ normalized.startsWith('/private/tmp/') ||
12
+ normalized.startsWith('/var/folders/') ||
13
+ normalized.startsWith('/private/var/folders/')
14
+ );
15
+ }
16
+
17
+ function isNodeTestRunner(): boolean {
18
+ if (process.env['NODE_TEST_CONTEXT']) return true;
19
+ return process.execArgv.some((arg) => arg === '--test' || arg.startsWith('--test-'));
20
+ }
21
+
4
22
  /**
5
23
  * Resolve a path the model supplied, expanding a leading `~`.
6
24
  *
@@ -32,5 +50,18 @@ export function causyneHome(): string {
32
50
  if (envHome && String(envHome).trim()) {
33
51
  return path.resolve(String(envHome).trim());
34
52
  }
35
- return path.join(os.homedir(), '.causyne');
53
+ const home = os.homedir();
54
+ if (isNodeTestRunner() && !isTempHome(home)) {
55
+ const fallbackRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'causyne-test-auto-'));
56
+ process.env['CAUSYNE_HOME'] = fallbackRoot;
57
+ process.once('exit', () => {
58
+ try {
59
+ fs.rmSync(fallbackRoot, { recursive: true, force: true });
60
+ } catch {
61
+ // Best-effort cleanup
62
+ }
63
+ });
64
+ return fallbackRoot;
65
+ }
66
+ return path.join(home, '.causyne');
36
67
  }
@@ -1,2 +0,0 @@
1
- export function buildStructuralSummary(...args: any[]): any;
2
- export function condenseAndSave(...args: any[]): any;
@@ -1 +0,0 @@
1
- export const cortexDb: any;