@causyne/agent 1.20.116 → 1.20.117

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.
@@ -13,6 +13,7 @@ import { loadConfig } from '../config.js';
13
13
  import { buildContextReport } from '../reporting.js';
14
14
  import { isAntigravityProvider } from '../providers/antigravity.js';
15
15
  import { isAcpProvider } from '../providers/acp.js';
16
+ import { resolveModelContextTokens } from '../contextManager.js';
16
17
 
17
18
  export interface UsageCardData {
18
19
  sessionId: string;
@@ -34,6 +35,12 @@ export interface UsageCardData {
34
35
  budgetLimitTokens?: number | undefined;
35
36
  budgetCostCeilingUsd?: number | undefined;
36
37
  budgetPercentUsed?: number | undefined;
38
+ /** All accounting is local; session counters require an active loop. */
39
+ sessionMetricsAvailable?: boolean;
40
+ /** A context ratio derived from text length and configured/assumed model window. */
41
+ contextLimitSource?: 'configured' | 'inferred';
42
+ /** Local history mixes provider token telemetry, ACP text estimates and media equivalents. */
43
+ usageProvenance?: string;
37
44
  }
38
45
 
39
46
  function oneLineText(value: unknown): string {
@@ -90,8 +97,10 @@ export async function collectUsageCardData(loop?: any): Promise<UsageCardData> {
90
97
  const daily = await tracker.getDailyUsage();
91
98
  const config = loadConfig() as Record<string, any>;
92
99
 
93
- const provider = oneLineText(config.provider || 'default') || 'default';
94
- const model = oneLineText(config.model || 'default') || 'default';
100
+ // The running agent can differ from saved settings after a model switch.
101
+ const liveConfig = loop?.config || {};
102
+ const provider = oneLineText(liveConfig.provider || config.provider || 'default') || 'default';
103
+ const model = oneLineText(liveConfig.model || config.model || 'default') || 'default';
95
104
  const isAgy = isAntigravityProvider(provider);
96
105
  const isAcp = isAcpProvider(provider);
97
106
  const billingNote = (isAgy || isAcp)
@@ -105,8 +114,21 @@ export async function collectUsageCardData(loop?: any): Promise<UsageCardData> {
105
114
 
106
115
  // Context accounting
107
116
  const contextReport = buildContextReport();
108
- const rawPoolTokens = finiteNonNeg(contextReport?.approxTokenPool, 250000);
109
- const poolTokens = rawPoolTokens > 0 ? Math.floor(rawPoolTokens) : 250000;
117
+ const override = liveConfig.contextTokens || liveConfig.maxContextTokens
118
+ || config.contextTokens || config.maxContextTokens;
119
+ const explicitLimit = Number.isFinite(Number(override)) && Number(override) > 0;
120
+ // report() uses persisted settings and can describe a *different* model.
121
+ // Resolve against the actual running provider/model; otherwise say inferred.
122
+ const modelLimit = resolveModelContextTokens({
123
+ provider, model, overrideTokens: explicitLimit ? Number(override) : 0
124
+ });
125
+ const liveLimitChars = finiteNonNeg(loop?._contextLimitChars, 0);
126
+ const liveLimitTokens = liveLimitChars > 0 ? Math.round(liveLimitChars / 4) : 0;
127
+ const poolTokens = Math.floor(
128
+ modelLimit > 0
129
+ ? finiteNonNeg(modelLimit, 0)
130
+ : (liveLimitTokens > 0 ? liveLimitTokens : finiteNonNeg(contextReport?.approxTokenPool, 0))
131
+ );
110
132
 
111
133
  // Measure active messages tokens
112
134
  let messageChars = 0;
@@ -138,8 +160,13 @@ export async function collectUsageCardData(loop?: any): Promise<UsageCardData> {
138
160
 
139
161
  const messageTokens = Math.round(messageChars / 4);
140
162
  const coreToolTokens = Math.floor(finiteNonNeg(contextReport?.core?.tokens, 5000));
141
- const contextUsed = messageTokens + coreToolTokens;
142
- const contextPctLeft = Math.max(0, Math.min(100, Math.round(((poolTokens - contextUsed) / poolTokens) * 100)));
163
+ const liveContextChars = finiteNonNeg(loop?._contextChars, 0);
164
+ const liveContextTokens = liveContextChars > 0 ? Math.round(liveContextChars / 4) : 0;
165
+ const contextUsed = liveContextTokens > 0
166
+ ? Math.max(liveContextTokens, messageTokens)
167
+ : (messageTokens + coreToolTokens);
168
+ const contextPctLeft = poolTokens > 0
169
+ ? Math.max(0, Math.min(100, Math.round(((poolTokens - contextUsed) / poolTokens) * 100))) : 0;
143
170
 
144
171
  // Budget
145
172
  const budget = config.tokenBudget || {};
@@ -152,8 +179,10 @@ export async function collectUsageCardData(loop?: any): Promise<UsageCardData> {
152
179
  const rawCostCeiling = finiteNonNeg(budget.maxCostUsd, 0);
153
180
 
154
181
  const sessionId = oneLineText(loop?.memoryManager?.sessionId || 'default') || 'default';
155
- const sessionTokens = finiteNonNeg(tracker.sessionTokens, 0) || finiteNonNeg(tracker.taskTokens, 0);
156
- const sessionCostUsd = finiteNonNeg(tracker.sessionCostUsd, 0) || finiteNonNeg(tracker.taskCostUsd, 0);
182
+ const sessionMetricsAvailable = Boolean(loop?.tokenTracker);
183
+ // These counters are per tracker instance, not persisted across restarts.
184
+ const sessionTokens = finiteNonNeg(tracker.sessionTokens, finiteNonNeg(reported?.sessionTokens, 0));
185
+ const sessionCostUsd = finiteNonNeg(tracker.sessionCostUsd, finiteNonNeg(reported?.sessionCostUsd, 0));
157
186
 
158
187
  return {
159
188
  sessionId,
@@ -174,7 +203,10 @@ export async function collectUsageCardData(loop?: any): Promise<UsageCardData> {
174
203
  budgetEnabled,
175
204
  budgetLimitTokens,
176
205
  budgetCostCeilingUsd: rawCostCeiling > 0 ? rawCostCeiling : undefined,
177
- budgetPercentUsed
206
+ budgetPercentUsed,
207
+ sessionMetricsAvailable,
208
+ contextLimitSource: explicitLimit ? 'configured' : 'inferred',
209
+ usageProvenance: 'Local tracker: provider reports, ACP text estimates and media equivalents can be mixed'
178
210
  };
179
211
  }
180
212
 
@@ -182,94 +214,69 @@ export async function collectUsageCardData(loop?: any): Promise<UsageCardData> {
182
214
  * Render the usage card as an array of styled terminal rows, exactly matching `width`.
183
215
  */
184
216
  export function renderUsageCardRows(data: UsageCardData, width: number): string[] {
185
- const safeWidth = Number.isFinite(width) ? Math.floor(width) : 80;
186
- const frameWidth = Math.max(40, safeWidth);
187
- const innerWidth = Math.max(20, frameWidth - 4); // border (1) + pad (1) on each side
188
- const borderRole = 'accent';
189
- const surfaceRole = 'surface';
190
-
191
- // Header row
192
- const title = ` ${bold(paint('accent', 'Usage & Context'))} `;
193
- const closeHint = ` ${dim('esc close')} `;
194
- const hLineLength = Math.max(0, frameWidth - 3 - visibleWidth(title) - visibleWidth(closeHint));
195
- const topBorder = paint(borderRole, FRAME.tl + FRAME.h)
196
- + title
197
- + paint(borderRole, FRAME.h.repeat(hLineLength))
198
- + closeHint
199
- + paint(borderRole, FRAME.tr);
200
-
201
- // Content lines inside card
202
- const lines: string[] = [];
203
-
204
- // 1. Session ID & Message count
205
- const cleanSession = oneLineText(data.sessionId || 'default') || 'default';
206
- const sessionChars = Array.from(cleanSession);
207
- const shortSession = sessionChars.length > 24
208
- ? `${sessionChars.slice(0, 10).join('')}…${sessionChars.slice(-10).join('')}`
209
- : cleanSession;
210
- lines.push(
211
- `${dim('Session/Chat :')} ${paint('ink', shortSession)} ${dim(`(${formatNumber(data.sessionTurns)} messages)`)}`
212
- );
213
-
214
- // 2. Context Window & Progress bar
215
- const safePercentLeft = Number.isFinite(data.contextPercentLeft)
216
- ? Math.max(0, Math.min(100, Math.round(data.contextPercentLeft)))
217
- : 0;
218
- const pBar = renderProgressBar(safePercentLeft, 22, false);
219
- lines.push(
220
- `${dim('Context :')} ${bold(`${safePercentLeft}% left`)} ${dim(`(${formatNumber(data.contextUsedTokens)} used / ${formatNumber(data.contextPoolTokens)})`)} ${pBar}`
221
- );
222
-
223
- // 3. This Session Usage
224
- lines.push(
225
- `${dim('This Session :')} ${bold(formatNumber(data.sessionTokens))} tokens${formatCostEstimate(data.sessionCostUsd)}`
226
- );
217
+ const safeWidth = Number.isFinite(width) ? Math.max(4, Math.floor(width)) : 80;
218
+ const frameWidth = safeWidth; // Never paint outside the terminal's actual columns.
219
+ const innerWidth = Math.max(0, frameWidth - 4);
220
+ const edge = paint('accent', FRAME.v);
221
+ const title = frameWidth >= 32 ? ` ${bold(paint('accent', 'Usage & Context'))} `
222
+ : frameWidth >= 13 ? ' Usage ' : '';
223
+ const hint = frameWidth >= 43 ? ` ${dim('esc close')} ` : '';
224
+ const lineRoom = Math.max(0, frameWidth - 3 - visibleWidth(title) - visibleWidth(hint));
225
+ const top = paint('accent', FRAME.tl + FRAME.h)
226
+ + title + paint('accent', FRAME.h.repeat(lineRoom)) + hint + paint('accent', FRAME.tr);
227
+ const rows = [fill('surface', top)];
228
+
229
+ const labelWidth = innerWidth >= 60 ? 16 : 13;
230
+ const addRow = (label: string, value: string): void => {
231
+ const name = dim(String(label).padEnd(labelWidth));
232
+ const text = name + value;
233
+ const clipped = visibleWidth(text) > innerWidth
234
+ ? truncate(text, innerWidth, GLYPHS.ellipsis) : text;
235
+ const padding = ' '.repeat(Math.max(0, innerWidth - visibleWidth(clipped)));
236
+ rows.push(fill('surface', `${edge} ${clipped}${padding} ${edge}`));
237
+ };
227
238
 
228
- // 4. Daily Usage (Today)
229
- lines.push(
230
- `${dim('Today (24h) :')} ${bold(formatNumber(data.dailyTokens))} tokens${formatCostEstimate(data.dailyCostUsd)}`
231
- );
239
+ const session = oneLineText(data.sessionId || 'unknown') || 'unknown';
240
+ const sessionName = truncate(session, Math.max(8, Math.floor(innerWidth / 2)), '…');
241
+ addRow('Session/Chat', `${paint('ink', sessionName)} ${dim(`(${formatNumber(data.sessionTurns)} messages)`)}`);
242
+ // Model and provider occupy separate rows, rather than squeezing two long
243
+ // identifiers into a single line where neither is readable.
244
+ addRow('Active Model', paint('accent', oneLineText(data.model || 'unknown')));
245
+ addRow('Provider', `${paint('ink', oneLineText(data.provider || 'unknown'))} ${dim(oneLineText(data.billingNote || ''))}`);
246
+
247
+ const pool = Number.isFinite(data.contextPoolTokens) && data.contextPoolTokens > 0
248
+ ? data.contextPoolTokens : 0;
249
+ const estimatedUsed = formatNumber(data.contextUsedTokens);
250
+ if (pool > 0) {
251
+ const percent = Number.isFinite(data.contextPercentLeft)
252
+ ? Math.max(0, Math.min(100, Math.round(data.contextPercentLeft))) : 0;
253
+ const poolSource = data.contextLimitSource === 'configured' ? 'configured cap' : 'inferred cap';
254
+ addRow('Context (est.)', `~${estimatedUsed} / ~${formatNumber(pool)} tokens (~${percent}% left; ${poolSource})`);
255
+ } else {
256
+ addRow('Context (est.)', `~${estimatedUsed} tokens; model limit unknown`);
257
+ }
232
258
 
233
- // 5. All-Time / Lifetime Usage
234
- lines.push(
235
- `${dim('All-Time :')} ${bold(formatNumber(data.lifetimeTokens))} tokens${formatCostEstimate(data.lifetimeCostUsd)} ${dim(`(${formatNumber(data.lifetimeCalls)} calls)`)}`
236
- );
259
+ addRow('This Session', data.sessionMetricsAvailable === false
260
+ ? dim('unavailable (no live tracker)')
261
+ : `${bold(formatNumber(data.sessionTokens))} tracked tokens ${dim('(current process only)')}`);
262
+ addRow('Today (local)', `${bold(formatNumber(data.dailyTokens))} tracked tokens ${dim('(calendar day)')}`);
263
+ addRow('All-Time', `${bold(formatNumber(data.lifetimeTokens))} tracked tokens ${dim(`(${formatNumber(data.lifetimeCalls)} recorded events)`)}`);
237
264
 
238
- // 6. Model & Provider
239
- const cleanProvider = oneLineText(data.provider || 'default') || 'default';
240
- const cleanModel = oneLineText(data.model || 'default') || 'default';
241
- const cleanBilling = oneLineText(data.billingNote || '');
242
- lines.push(
243
- `${dim('Active Model :')} ${paint('accent', `${cleanProvider} / ${cleanModel}`)}${cleanBilling ? ` ${dim(`(${cleanBilling})`)}` : ''}`
244
- );
265
+ const totalEstimate = formatCostEstimate(data.lifetimeCostUsd).trim();
266
+ const dailyEstimate = formatCostEstimate(data.dailyCostUsd).trim();
267
+ addRow('Cost (estimate)', totalEstimate
268
+ ? `${totalEstimate} all-time${dailyEstimate ? ` · ${dailyEstimate} today` : ''}`
269
+ : dim('no positive local estimate recorded'));
245
270
 
246
- // 7. Optional Budget
271
+ addRow('Data source', dim('Local tracker; not provider billing or exact token telemetry'));
247
272
  if (data.budgetEnabled && typeof data.budgetLimitTokens === 'number' && Number.isFinite(data.budgetLimitTokens) && data.budgetLimitTokens > 0) {
248
- const safeBudgetPercent = typeof data.budgetPercentUsed === 'number' && Number.isFinite(data.budgetPercentUsed)
249
- ? Math.max(0, Math.round(data.budgetPercentUsed))
250
- : 0;
251
- const bBar = renderProgressBar(safeBudgetPercent, 16, true);
252
- lines.push(
253
- `${dim('Daily Budget :')} ${formatNumber(data.dailyTokens)} / ${formatNumber(data.budgetLimitTokens)} tokens (${safeBudgetPercent}% used) ${bBar}`
254
- );
273
+ const pct = typeof data.budgetPercentUsed === 'number' && Number.isFinite(data.budgetPercentUsed)
274
+ ? Math.max(0, Math.round(data.budgetPercentUsed)) : 0;
275
+ addRow('Daily budget', `${formatNumber(data.dailyTokens)} / ${formatNumber(data.budgetLimitTokens)} tracked (${pct}% used)`);
255
276
  }
256
277
 
257
- // Construct boxed rows
258
- const edge = paint(borderRole, FRAME.v);
259
- const rows: string[] = [fill(surfaceRole, topBorder)];
260
-
261
- for (const line of lines) {
262
- const clipped = visibleWidth(line) > innerWidth ? truncate(line, innerWidth, GLYPHS.ellipsis) : line;
263
- const padding = ' '.repeat(Math.max(0, innerWidth - visibleWidth(clipped)));
264
- rows.push(fill(surfaceRole, `${edge} ${clipped}${padding} ${edge}`));
265
- }
266
-
267
- // Bottom row
268
- const bottomBorder = paint(borderRole, FRAME.bl + FRAME.h.repeat(Math.max(0, frameWidth - 2)) + FRAME.br);
269
- rows.push(fill(surfaceRole, bottomBorder));
270
-
271
- // Add 1 blank row gap separating the usage card from the chatbox below
272
- rows.push('');
273
-
278
+ const bottom = paint('accent', FRAME.bl + FRAME.h.repeat(Math.max(0, frameWidth - 2)) + FRAME.br);
279
+ rows.push(fill('surface', bottom));
280
+ rows.push(''); // Keep the composer visually separate from the usage panel.
274
281
  return rows;
275
282
  }
@@ -298,6 +298,9 @@ export interface WorkspaceContext {
298
298
  projectType?: string;
299
299
  designSystem?: string;
300
300
  keyFiles?: string[];
301
+ subprojectStacks?: string[];
302
+ docFiles?: string[];
303
+ buildFiles?: string[];
301
304
  applicationRoot?: string;
302
305
  workspaceRoot?: string;
303
306
  allowedReadRoots?: string[];