@causyne/agent 1.20.117 → 1.20.120

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 (82) hide show
  1. package/package.json +7 -2
  2. package/src/agentLoop.js +29 -12
  3. package/src/agentLoop.ts +29 -16
  4. package/src/browser/causyneBrowser.js +231 -136
  5. package/src/browser/causyneBrowser.ts +229 -140
  6. package/src/browser/searchProviders.js +41 -30
  7. package/src/browser/searchProviders.ts +24 -14
  8. package/src/browser/workspacePathSafety.js +50 -0
  9. package/src/browser/workspacePathSafety.ts +50 -0
  10. package/src/browser/workspacePreview.js +27 -4
  11. package/src/browser/workspacePreview.ts +28 -4
  12. package/src/cliMode.js +20 -4
  13. package/src/commands.js +12 -14
  14. package/src/creative/liveBridge.js +34 -1
  15. package/src/creative/liveBridge.ts +28 -1
  16. package/src/observer/evidence.js +23 -0
  17. package/src/observer/evidence.ts +21 -0
  18. package/src/plugins/pluginManager.js +74 -0
  19. package/src/providers/anthropic.js +33 -17
  20. package/src/providers/base.js +14 -0
  21. package/src/providers/dashscope-byok.js +13 -7
  22. package/src/providers/deepseek.js +13 -18
  23. package/src/providers/gemini.js +33 -25
  24. package/src/providers/moonshot.js +13 -12
  25. package/src/providers/ollama.js +21 -21
  26. package/src/providers/openai-compatible.js +12 -19
  27. package/src/providers/openrouter.js +20 -90
  28. package/src/providers/openrouter.ts +31 -94
  29. package/src/providers/qwen-byok.js +13 -7
  30. package/src/providers/toolContracts.js +9 -3
  31. package/src/providers/toolContracts.ts +9 -3
  32. package/src/providers/wireNormalizer.js +238 -0
  33. package/src/providers/wireNormalizer.ts +279 -0
  34. package/src/providers/xai.js +13 -12
  35. package/src/reporting.js +12 -4
  36. package/src/skillsManager.js +3 -2
  37. package/src/skillsManager.ts +3 -2
  38. package/src/tools/browserAutomator.js +13 -1
  39. package/src/tools/browserAutomator.ts +13 -0
  40. package/src/tools/creativeApps.js +2 -1
  41. package/src/tools/creativeApps.ts +2 -1
  42. package/src/tools/gameAssetFetcher.js +130 -26
  43. package/src/tools/gameAssetHarvester.js +80 -58
  44. package/src/tools/nativeEngine.js +1 -1
  45. package/src/tools/nativeEngine.ts +1 -1
  46. package/src/tools/pluginManager.js +17 -2
  47. package/src/tools/registry.js +13 -0
  48. package/src/tools/toolScanner.js +596 -140
  49. package/src/tools/toolScanner.ts +665 -147
  50. package/src/tools/toolSelfRepair.js +243 -114
  51. package/src/tools/toolSelfRepair.ts +262 -111
  52. package/src/tools/webFetch.js +161 -24
  53. package/src/tools/webFetch.ts +157 -22
  54. package/src/tools/webSearch.js +33 -4
  55. package/src/tools/webSearch.ts +27 -4
  56. package/src/tui/composerControls.js +16 -3
  57. package/src/tui/composerControls.ts +14 -3
  58. package/src/tui/prompt.js +122 -16
  59. package/src/tui/sessionPicker.js +132 -35
  60. package/src/tui/sessionPicker.ts +153 -32
  61. package/src/tui/sessionPickerView.js +277 -34
  62. package/src/tui/sessionPickerView.ts +328 -34
  63. package/src/tui/statusLine.js +3 -0
  64. package/src/tui/statusLine.ts +5 -0
  65. package/src/tui/usageCard.js +119 -47
  66. package/src/tui/usageCard.ts +133 -49
  67. package/src/tui/workspaceIdentity.js +133 -0
  68. package/src/tui/workspaceIdentity.ts +146 -0
  69. package/src/tui/workspaceSwitch.js +2 -0
  70. package/src/tui/workspaceSwitch.ts +1 -0
  71. package/src/verification/boundedExplorer.js +119 -0
  72. package/src/verification/cliProbe.js +116 -0
  73. package/src/verification/featureMap.js +78 -0
  74. package/src/verification/interactivePty.js +188 -0
  75. package/src/verification/propertyProbe.js +121 -0
  76. package/src/verification/ptyProbe.js +125 -0
  77. package/src/verification/skillCatalog.d.ts +1 -0
  78. package/src/verification/skillCatalog.js +60 -0
  79. package/src/verification/statechart.js +143 -0
  80. package/src/verification/uiRuntime.js +57 -0
  81. package/src/verificationPlan.js +1 -1
  82. package/src/verificationPlan.ts +1 -1
@@ -168,67 +168,139 @@ export async function collectUsageCardData(loop) {
168
168
  usageProvenance: 'Local tracker: provider reports, ACP text estimates and media equivalents can be mixed'
169
169
  };
170
170
  }
171
- /**
172
- * Render the usage card as an array of styled terminal rows, exactly matching `width`.
173
- */
174
- export function renderUsageCardRows(data, width) {
171
+ function buildFramedCardRows(width, options, populate) {
175
172
  const safeWidth = Number.isFinite(width) ? Math.max(4, Math.floor(width)) : 80;
176
173
  const frameWidth = safeWidth; // Never paint outside the terminal's actual columns.
177
174
  const innerWidth = Math.max(0, frameWidth - 4);
178
175
  const edge = paint('accent', FRAME.v);
179
- const title = frameWidth >= 32 ? ` ${bold(paint('accent', 'Usage & Context'))} `
180
- : frameWidth >= 13 ? ' Usage ' : '';
181
- const hint = frameWidth >= 43 ? ` ${dim('esc close')} ` : '';
176
+ const cleanTitle = oneLineText(options.title);
177
+ const title = frameWidth >= 32 ? ` ${bold(paint('accent', cleanTitle))} `
178
+ : frameWidth >= 13 ? ` ${cleanTitle.split(/\s+/)[0] || cleanTitle} ` : '';
179
+ const footerText = oneLineText(options.footer || 'esc close');
180
+ const hint = frameWidth >= 43 && footerText ? ` ${dim(footerText)} ` : '';
182
181
  const lineRoom = Math.max(0, frameWidth - 3 - visibleWidth(title) - visibleWidth(hint));
183
182
  const top = paint('accent', FRAME.tl + FRAME.h)
184
183
  + title + paint('accent', FRAME.h.repeat(lineRoom)) + hint + paint('accent', FRAME.tr);
185
184
  const rows = [fill('surface', top)];
186
- const labelWidth = innerWidth >= 60 ? 16 : 13;
187
- const addRow = (label, value) => {
188
- const name = dim(String(label).padEnd(labelWidth));
189
- const text = name + value;
185
+ const labelWidth = options.labelWidth ?? (innerWidth >= 60 ? 16 : 13);
186
+ const pushInnerRow = (text) => {
190
187
  const clipped = visibleWidth(text) > innerWidth
191
188
  ? truncate(text, innerWidth, GLYPHS.ellipsis) : text;
192
189
  const padding = ' '.repeat(Math.max(0, innerWidth - visibleWidth(clipped)));
193
190
  rows.push(fill('surface', `${edge} ${clipped}${padding} ${edge}`));
194
191
  };
195
- const session = oneLineText(data.sessionId || 'unknown') || 'unknown';
196
- const sessionName = truncate(session, Math.max(8, Math.floor(innerWidth / 2)), '…');
197
- addRow('Session/Chat', `${paint('ink', sessionName)} ${dim(`(${formatNumber(data.sessionTurns)} messages)`)}`);
198
- // Model and provider occupy separate rows, rather than squeezing two long
199
- // identifiers into a single line where neither is readable.
200
- addRow('Active Model', paint('accent', oneLineText(data.model || 'unknown')));
201
- addRow('Provider', `${paint('ink', oneLineText(data.provider || 'unknown'))} ${dim(oneLineText(data.billingNote || ''))}`);
202
- const pool = Number.isFinite(data.contextPoolTokens) && data.contextPoolTokens > 0
203
- ? data.contextPoolTokens : 0;
204
- const estimatedUsed = formatNumber(data.contextUsedTokens);
205
- if (pool > 0) {
206
- const percent = Number.isFinite(data.contextPercentLeft)
207
- ? Math.max(0, Math.min(100, Math.round(data.contextPercentLeft))) : 0;
208
- const poolSource = data.contextLimitSource === 'configured' ? 'configured cap' : 'inferred cap';
209
- addRow('Context (est.)', `~${estimatedUsed} / ~${formatNumber(pool)} tokens (~${percent}% left; ${poolSource})`);
210
- }
211
- else {
212
- addRow('Context (est.)', `~${estimatedUsed} tokens; model limit unknown`);
213
- }
214
- addRow('This Session', data.sessionMetricsAvailable === false
215
- ? dim('unavailable (no live tracker)')
216
- : `${bold(formatNumber(data.sessionTokens))} tracked tokens ${dim('(current process only)')}`);
217
- addRow('Today (local)', `${bold(formatNumber(data.dailyTokens))} tracked tokens ${dim('(calendar day)')}`);
218
- addRow('All-Time', `${bold(formatNumber(data.lifetimeTokens))} tracked tokens ${dim(`(${formatNumber(data.lifetimeCalls)} recorded events)`)}`);
219
- const totalEstimate = formatCostEstimate(data.lifetimeCostUsd).trim();
220
- const dailyEstimate = formatCostEstimate(data.dailyCostUsd).trim();
221
- addRow('Cost (estimate)', totalEstimate
222
- ? `${totalEstimate} all-time${dailyEstimate ? ` · ${dailyEstimate} today` : ''}`
223
- : dim('no positive local estimate recorded'));
224
- addRow('Data source', dim('Local tracker; not provider billing or exact token telemetry'));
225
- if (data.budgetEnabled && typeof data.budgetLimitTokens === 'number' && Number.isFinite(data.budgetLimitTokens) && data.budgetLimitTokens > 0) {
226
- const pct = typeof data.budgetPercentUsed === 'number' && Number.isFinite(data.budgetPercentUsed)
227
- ? Math.max(0, Math.round(data.budgetPercentUsed)) : 0;
228
- addRow('Daily budget', `${formatNumber(data.dailyTokens)} / ${formatNumber(data.budgetLimitTokens)} tracked (${pct}% used)`);
229
- }
192
+ const addRow = (label, value) => {
193
+ const name = dim(String(label).padEnd(labelWidth));
194
+ pushInnerRow(name + value);
195
+ };
196
+ populate(addRow, pushInnerRow, { innerWidth, labelWidth });
230
197
  const bottom = paint('accent', FRAME.bl + FRAME.h.repeat(Math.max(0, frameWidth - 2)) + FRAME.br);
231
198
  rows.push(fill('surface', bottom));
232
- rows.push(''); // Keep the composer visually separate from the usage panel.
199
+ rows.push(''); // Keep the composer visually separate from the pinned panel.
233
200
  return rows;
234
201
  }
202
+ /**
203
+ * Render the usage card as an array of styled terminal rows, exactly matching `width`.
204
+ */
205
+ export function renderUsageCardRows(data, width) {
206
+ return buildFramedCardRows(width, { title: 'Usage & Context', footer: 'esc close' }, (addRow, _addLine, { innerWidth, labelWidth }) => {
207
+ const session = oneLineText(data.sessionId || 'unknown') || 'unknown';
208
+ const sessionName = truncate(session, Math.max(8, Math.floor(innerWidth / 2)), '…');
209
+ addRow('Session/Chat', `${paint('ink', sessionName)} ${dim(`(${formatNumber(data.sessionTurns)} messages)`)}`);
210
+ // Model and provider occupy separate rows, rather than squeezing two long
211
+ // identifiers into a single line where neither is readable.
212
+ addRow('Active Model', paint('accent', oneLineText(data.model || 'unknown')));
213
+ addRow('Provider', `${paint('ink', oneLineText(data.provider || 'unknown'))} ${dim(oneLineText(data.billingNote || ''))}`);
214
+ const pool = Number.isFinite(data.contextPoolTokens) && data.contextPoolTokens > 0
215
+ ? data.contextPoolTokens : 0;
216
+ const estimatedUsed = formatNumber(data.contextUsedTokens);
217
+ if (pool > 0) {
218
+ const percent = Number.isFinite(data.contextPercentLeft)
219
+ ? Math.max(0, Math.min(100, Math.round(data.contextPercentLeft))) : 0;
220
+ const poolSource = data.contextLimitSource === 'configured' ? 'configured cap' : 'inferred cap';
221
+ addRow('Context (est.)', `~${estimatedUsed} / ~${formatNumber(pool)} tokens (~${percent}% left; ${poolSource})`);
222
+ const barRoom = Math.max(0, innerWidth - labelWidth - 13);
223
+ if (barRoom >= 8) {
224
+ const barWidth = Math.min(28, barRoom);
225
+ const bar = renderProgressBar(percent, barWidth, false);
226
+ addRow('Window left', `[${bar}] ${String(percent).padStart(3)}% left`);
227
+ }
228
+ }
229
+ else {
230
+ addRow('Context (est.)', `~${estimatedUsed} tokens; model limit unknown`);
231
+ }
232
+ addRow('This Session', data.sessionMetricsAvailable === false
233
+ ? dim('unavailable (no live tracker)')
234
+ : `${bold(formatNumber(data.sessionTokens))} tracked tokens ${dim('(current process only)')}`);
235
+ addRow('Today (local)', `${bold(formatNumber(data.dailyTokens))} tracked tokens ${dim('(calendar day)')}`);
236
+ addRow('All-Time', `${bold(formatNumber(data.lifetimeTokens))} tracked tokens ${dim(`(${formatNumber(data.lifetimeCalls)} recorded events)`)}`);
237
+ const totalEstimate = formatCostEstimate(data.lifetimeCostUsd).trim();
238
+ const dailyEstimate = formatCostEstimate(data.dailyCostUsd).trim();
239
+ addRow('Cost (estimate)', totalEstimate
240
+ ? `${totalEstimate} all-time${dailyEstimate ? ` · ${dailyEstimate} today` : ''}`
241
+ : dim('no positive local estimate recorded'));
242
+ addRow('Data source', dim('Local tracker; not provider billing or exact token telemetry'));
243
+ if (data.budgetEnabled && typeof data.budgetLimitTokens === 'number' && Number.isFinite(data.budgetLimitTokens) && data.budgetLimitTokens > 0) {
244
+ const pct = typeof data.budgetPercentUsed === 'number' && Number.isFinite(data.budgetPercentUsed)
245
+ ? Math.max(0, Math.round(data.budgetPercentUsed)) : 0;
246
+ addRow('Daily budget', `${formatNumber(data.dailyTokens)} / ${formatNumber(data.budgetLimitTokens)} tracked (${pct}% used)`);
247
+ }
248
+ });
249
+ }
250
+ /**
251
+ * Render the pinned `/status` card matching the Usage card styling, plus live session/context meters when available.
252
+ */
253
+ export function renderStatusCardRows(statusText, usageData, width) {
254
+ return buildFramedCardRows(width, { title: 'Status', footer: 'esc close' }, (addRow, addLine, { innerWidth, labelWidth }) => {
255
+ const rawLines = String(statusText || '').split(/\r?\n/);
256
+ if (rawLines[0]?.trim() === 'Status')
257
+ rawLines.shift();
258
+ let hasSessionLine = false;
259
+ for (const rawLine of rawLines) {
260
+ const trimmed = oneLineText(rawLine);
261
+ if (!trimmed)
262
+ continue;
263
+ const sepIdx = trimmed.indexOf(':');
264
+ if (sepIdx > 0 && sepIdx <= 20) {
265
+ const key = trimmed.slice(0, sepIdx).trim();
266
+ const val = trimmed.slice(sepIdx + 1).trim();
267
+ if (key.toLowerCase() === 'session')
268
+ hasSessionLine = true;
269
+ const coloredVal = key.toLowerCase().includes('provider')
270
+ ? paint('accent', val)
271
+ : paint('ink', val);
272
+ addRow(key, coloredVal);
273
+ }
274
+ else {
275
+ addLine(dim(trimmed));
276
+ }
277
+ }
278
+ if (usageData) {
279
+ if (!hasSessionLine) {
280
+ const session = oneLineText(usageData.sessionId || 'unknown') || 'unknown';
281
+ const sessionName = truncate(session, Math.max(8, Math.floor(innerWidth / 2)), '…');
282
+ addRow('Session', `${paint('ink', sessionName)} ${dim(`(${formatNumber(usageData.sessionTurns)} messages)`)}`);
283
+ }
284
+ const pool = Number.isFinite(usageData.contextPoolTokens) && usageData.contextPoolTokens > 0
285
+ ? usageData.contextPoolTokens : 0;
286
+ const used = formatNumber(usageData.contextUsedTokens);
287
+ if (pool > 0) {
288
+ const percent = Number.isFinite(usageData.contextPercentLeft)
289
+ ? Math.max(0, Math.min(100, Math.round(usageData.contextPercentLeft))) : 0;
290
+ const barRoom = Math.max(0, innerWidth - labelWidth - 13);
291
+ if (barRoom >= 8) {
292
+ const barWidth = Math.min(26, barRoom);
293
+ const bar = renderProgressBar(percent, barWidth, false);
294
+ addRow('Context left', `[${bar}] ${String(percent).padStart(3)}% left`);
295
+ }
296
+ addRow('Context tokens', `~${used} / ~${formatNumber(pool)} tokens`);
297
+ }
298
+ else {
299
+ addRow('Context tokens', `~${used} tokens; model limit unknown`);
300
+ }
301
+ if (usageData.sessionMetricsAvailable !== false) {
302
+ addRow('Tracked tokens', `${bold(formatNumber(usageData.sessionTokens))} session · ${bold(formatNumber(usageData.dailyTokens))} today`);
303
+ }
304
+ }
305
+ });
306
+ }
@@ -210,73 +210,157 @@ export async function collectUsageCardData(loop?: any): Promise<UsageCardData> {
210
210
  };
211
211
  }
212
212
 
213
- /**
214
- * Render the usage card as an array of styled terminal rows, exactly matching `width`.
215
- */
216
- export function renderUsageCardRows(data: UsageCardData, width: number): string[] {
213
+ interface FramedCardOptions {
214
+ title: string;
215
+ footer?: string;
216
+ labelWidth?: number;
217
+ }
218
+
219
+ function buildFramedCardRows(
220
+ width: number,
221
+ options: FramedCardOptions,
222
+ populate: (addRow: (label: string, value: string) => void, addLine: (line: string) => void, ctx: { innerWidth: number; labelWidth: number }) => void
223
+ ): string[] {
217
224
  const safeWidth = Number.isFinite(width) ? Math.max(4, Math.floor(width)) : 80;
218
225
  const frameWidth = safeWidth; // Never paint outside the terminal's actual columns.
219
226
  const innerWidth = Math.max(0, frameWidth - 4);
220
227
  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')} ` : '';
228
+ const cleanTitle = oneLineText(options.title);
229
+ const title = frameWidth >= 32 ? ` ${bold(paint('accent', cleanTitle))} `
230
+ : frameWidth >= 13 ? ` ${cleanTitle.split(/\s+/)[0] || cleanTitle} ` : '';
231
+ const footerText = oneLineText(options.footer || 'esc close');
232
+ const hint = frameWidth >= 43 && footerText ? ` ${dim(footerText)} ` : '';
224
233
  const lineRoom = Math.max(0, frameWidth - 3 - visibleWidth(title) - visibleWidth(hint));
225
234
  const top = paint('accent', FRAME.tl + FRAME.h)
226
235
  + title + paint('accent', FRAME.h.repeat(lineRoom)) + hint + paint('accent', FRAME.tr);
227
236
  const rows = [fill('surface', top)];
228
237
 
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;
238
+ const labelWidth = options.labelWidth ?? (innerWidth >= 60 ? 16 : 13);
239
+ const pushInnerRow = (text: string): void => {
233
240
  const clipped = visibleWidth(text) > innerWidth
234
241
  ? truncate(text, innerWidth, GLYPHS.ellipsis) : text;
235
242
  const padding = ' '.repeat(Math.max(0, innerWidth - visibleWidth(clipped)));
236
243
  rows.push(fill('surface', `${edge} ${clipped}${padding} ${edge}`));
237
244
  };
245
+ const addRow = (label: string, value: string): void => {
246
+ const name = dim(String(label).padEnd(labelWidth));
247
+ pushInnerRow(name + value);
248
+ };
238
249
 
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 || ''))}`);
250
+ populate(addRow, pushInnerRow, { innerWidth, labelWidth });
246
251
 
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
- }
252
+ const bottom = paint('accent', FRAME.bl + FRAME.h.repeat(Math.max(0, frameWidth - 2)) + FRAME.br);
253
+ rows.push(fill('surface', bottom));
254
+ rows.push(''); // Keep the composer visually separate from the pinned panel.
255
+ return rows;
256
+ }
258
257
 
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)`)}`);
258
+ /**
259
+ * Render the usage card as an array of styled terminal rows, exactly matching `width`.
260
+ */
261
+ export function renderUsageCardRows(data: UsageCardData, width: number): string[] {
262
+ return buildFramedCardRows(width, { title: 'Usage & Context', footer: 'esc close' }, (addRow, _addLine, { innerWidth, labelWidth }) => {
263
+ const session = oneLineText(data.sessionId || 'unknown') || 'unknown';
264
+ const sessionName = truncate(session, Math.max(8, Math.floor(innerWidth / 2)), '…');
265
+ addRow('Session/Chat', `${paint('ink', sessionName)} ${dim(`(${formatNumber(data.sessionTurns)} messages)`)}`);
266
+ // Model and provider occupy separate rows, rather than squeezing two long
267
+ // identifiers into a single line where neither is readable.
268
+ addRow('Active Model', paint('accent', oneLineText(data.model || 'unknown')));
269
+ addRow('Provider', `${paint('ink', oneLineText(data.provider || 'unknown'))} ${dim(oneLineText(data.billingNote || ''))}`);
264
270
 
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'));
271
+ const pool = Number.isFinite(data.contextPoolTokens) && data.contextPoolTokens > 0
272
+ ? data.contextPoolTokens : 0;
273
+ const estimatedUsed = formatNumber(data.contextUsedTokens);
274
+ if (pool > 0) {
275
+ const percent = Number.isFinite(data.contextPercentLeft)
276
+ ? Math.max(0, Math.min(100, Math.round(data.contextPercentLeft))) : 0;
277
+ const poolSource = data.contextLimitSource === 'configured' ? 'configured cap' : 'inferred cap';
278
+ addRow('Context (est.)', `~${estimatedUsed} / ~${formatNumber(pool)} tokens (~${percent}% left; ${poolSource})`);
279
+ const barRoom = Math.max(0, innerWidth - labelWidth - 13);
280
+ if (barRoom >= 8) {
281
+ const barWidth = Math.min(28, barRoom);
282
+ const bar = renderProgressBar(percent, barWidth, false);
283
+ addRow('Window left', `[${bar}] ${String(percent).padStart(3)}% left`);
284
+ }
285
+ } else {
286
+ addRow('Context (est.)', `~${estimatedUsed} tokens; model limit unknown`);
287
+ }
270
288
 
271
- addRow('Data source', dim('Local tracker; not provider billing or exact token telemetry'));
272
- if (data.budgetEnabled && typeof data.budgetLimitTokens === 'number' && Number.isFinite(data.budgetLimitTokens) && data.budgetLimitTokens > 0) {
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)`);
276
- }
289
+ addRow('This Session', data.sessionMetricsAvailable === false
290
+ ? dim('unavailable (no live tracker)')
291
+ : `${bold(formatNumber(data.sessionTokens))} tracked tokens ${dim('(current process only)')}`);
292
+ addRow('Today (local)', `${bold(formatNumber(data.dailyTokens))} tracked tokens ${dim('(calendar day)')}`);
293
+ addRow('All-Time', `${bold(formatNumber(data.lifetimeTokens))} tracked tokens ${dim(`(${formatNumber(data.lifetimeCalls)} recorded events)`)}`);
277
294
 
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.
281
- return rows;
295
+ const totalEstimate = formatCostEstimate(data.lifetimeCostUsd).trim();
296
+ const dailyEstimate = formatCostEstimate(data.dailyCostUsd).trim();
297
+ addRow('Cost (estimate)', totalEstimate
298
+ ? `${totalEstimate} all-time${dailyEstimate ? ` · ${dailyEstimate} today` : ''}`
299
+ : dim('no positive local estimate recorded'));
300
+
301
+ addRow('Data source', dim('Local tracker; not provider billing or exact token telemetry'));
302
+ if (data.budgetEnabled && typeof data.budgetLimitTokens === 'number' && Number.isFinite(data.budgetLimitTokens) && data.budgetLimitTokens > 0) {
303
+ const pct = typeof data.budgetPercentUsed === 'number' && Number.isFinite(data.budgetPercentUsed)
304
+ ? Math.max(0, Math.round(data.budgetPercentUsed)) : 0;
305
+ addRow('Daily budget', `${formatNumber(data.dailyTokens)} / ${formatNumber(data.budgetLimitTokens)} tracked (${pct}% used)`);
306
+ }
307
+ });
308
+ }
309
+
310
+ /**
311
+ * Render the pinned `/status` card matching the Usage card styling, plus live session/context meters when available.
312
+ */
313
+ export function renderStatusCardRows(
314
+ statusText: string,
315
+ usageData: UsageCardData | null | undefined,
316
+ width: number
317
+ ): string[] {
318
+ return buildFramedCardRows(width, { title: 'Status', footer: 'esc close' }, (addRow, addLine, { innerWidth, labelWidth }) => {
319
+ const rawLines = String(statusText || '').split(/\r?\n/);
320
+ if (rawLines[0]?.trim() === 'Status') rawLines.shift();
321
+ let hasSessionLine = false;
322
+ for (const rawLine of rawLines) {
323
+ const trimmed = oneLineText(rawLine);
324
+ if (!trimmed) continue;
325
+ const sepIdx = trimmed.indexOf(':');
326
+ if (sepIdx > 0 && sepIdx <= 20) {
327
+ const key = trimmed.slice(0, sepIdx).trim();
328
+ const val = trimmed.slice(sepIdx + 1).trim();
329
+ if (key.toLowerCase() === 'session') hasSessionLine = true;
330
+ const coloredVal = key.toLowerCase().includes('provider')
331
+ ? paint('accent', val)
332
+ : paint('ink', val);
333
+ addRow(key, coloredVal);
334
+ } else {
335
+ addLine(dim(trimmed));
336
+ }
337
+ }
338
+
339
+ if (usageData) {
340
+ if (!hasSessionLine) {
341
+ const session = oneLineText(usageData.sessionId || 'unknown') || 'unknown';
342
+ const sessionName = truncate(session, Math.max(8, Math.floor(innerWidth / 2)), '…');
343
+ addRow('Session', `${paint('ink', sessionName)} ${dim(`(${formatNumber(usageData.sessionTurns)} messages)`)}`);
344
+ }
345
+ const pool = Number.isFinite(usageData.contextPoolTokens) && usageData.contextPoolTokens > 0
346
+ ? usageData.contextPoolTokens : 0;
347
+ const used = formatNumber(usageData.contextUsedTokens);
348
+ if (pool > 0) {
349
+ const percent = Number.isFinite(usageData.contextPercentLeft)
350
+ ? Math.max(0, Math.min(100, Math.round(usageData.contextPercentLeft))) : 0;
351
+ const barRoom = Math.max(0, innerWidth - labelWidth - 13);
352
+ if (barRoom >= 8) {
353
+ const barWidth = Math.min(26, barRoom);
354
+ const bar = renderProgressBar(percent, barWidth, false);
355
+ addRow('Context left', `[${bar}] ${String(percent).padStart(3)}% left`);
356
+ }
357
+ addRow('Context tokens', `~${used} / ~${formatNumber(pool)} tokens`);
358
+ } else {
359
+ addRow('Context tokens', `~${used} tokens; model limit unknown`);
360
+ }
361
+ if (usageData.sessionMetricsAvailable !== false) {
362
+ addRow('Tracked tokens', `${bold(formatNumber(usageData.sessionTokens))} session · ${bold(formatNumber(usageData.dailyTokens))} today`);
363
+ }
364
+ }
365
+ });
282
366
  }
@@ -0,0 +1,133 @@
1
+ // Dynamic canonical workspace identity & display helpers for Causyne Agent TUI.
2
+ // Authored in Strict TypeScript. Never hardcodes user or project workspace names.
3
+ // Source-available under BUSL-1.1.
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import { safeDisplay } from './text.js';
8
+ function cleanInlineText(value) {
9
+ return safeDisplay(typeof value === 'string' ? value : String(value ?? ''))
10
+ .replace(/[\r\n\t]+/g, ' ')
11
+ .trim();
12
+ }
13
+ function getUserHomeDir() {
14
+ const fromEnv = process.env.HOME || process.env.USERPROFILE || '';
15
+ if (fromEnv && fromEnv.trim())
16
+ return fromEnv.trim();
17
+ try {
18
+ return os.homedir() || '';
19
+ }
20
+ catch {
21
+ return '';
22
+ }
23
+ }
24
+ function isDriveRoot(value) {
25
+ return value.length >= 2
26
+ && value.length <= 3
27
+ && ((value[0] >= 'A' && value[0] <= 'Z') || (value[0] >= 'a' && value[0] <= 'z'))
28
+ && value[1] === ':'
29
+ && (value.length === 2 || value[2] === '\\' || value[2] === '/');
30
+ }
31
+ /**
32
+ * Resolve a workspace path into a canonical comparison key.
33
+ * Resolves symlinks (for example `/tmp` vs `/private/tmp` on macOS) when the
34
+ * directory exists on disk, falling back to `path.resolve()` otherwise.
35
+ */
36
+ export function canonicalWorkspacePath(workspacePath, cache) {
37
+ if (typeof workspacePath !== 'string')
38
+ return '';
39
+ const trimmed = workspacePath.trim();
40
+ if (!trimmed)
41
+ return '';
42
+ const resolved = path.resolve(trimmed);
43
+ const cached = cache?.get(resolved);
44
+ if (cached !== undefined)
45
+ return cached;
46
+ let canonical = resolved;
47
+ try {
48
+ canonical = typeof fs.realpathSync.native === 'function'
49
+ ? fs.realpathSync.native(resolved)
50
+ : fs.realpathSync(resolved);
51
+ }
52
+ catch {
53
+ // Missing or synthetic paths keep their lexical resolved form.
54
+ }
55
+ const normalized = process.platform === 'win32' ? canonical.toLowerCase() : canonical;
56
+ if (cache)
57
+ cache.set(resolved, normalized);
58
+ return normalized;
59
+ }
60
+ /**
61
+ * True when two workspace paths refer to the same canonical directory.
62
+ */
63
+ export function sameWorkspace(first, second, cache) {
64
+ const a = canonicalWorkspacePath(first, cache);
65
+ const b = canonicalWorkspacePath(second, cache);
66
+ return a.length > 0 && a === b;
67
+ }
68
+ /**
69
+ * Shorten a workspace path for display by replacing the exact home prefix with `~`.
70
+ * Always sanitized for safe single-line terminal rendering.
71
+ */
72
+ export function shortenWorkspacePath(workspacePath) {
73
+ if (typeof workspacePath !== 'string' || !workspacePath.trim())
74
+ return '(default)';
75
+ const trimmed = workspacePath.trim();
76
+ const home = getUserHomeDir();
77
+ if (home) {
78
+ const resolved = path.resolve(trimmed);
79
+ const resolvedHome = path.resolve(home);
80
+ const cmpResolved = process.platform === 'win32' ? resolved.toLowerCase() : resolved;
81
+ const cmpHome = process.platform === 'win32' ? resolvedHome.toLowerCase() : resolvedHome;
82
+ if (cmpResolved === cmpHome)
83
+ return '~';
84
+ const prefix = cmpHome.endsWith(path.sep) ? cmpHome : `${cmpHome}${path.sep}`;
85
+ if (cmpResolved.startsWith(prefix)) {
86
+ const tail = resolved.slice(resolvedHome.length);
87
+ return cleanInlineText(`~${tail}`) || '~';
88
+ }
89
+ }
90
+ return cleanInlineText(trimmed) || '(default)';
91
+ }
92
+ /**
93
+ * Dynamically derive the human-readable workspace folder name from any path
94
+ * without hardcoding user or repository names.
95
+ */
96
+ export function workspaceDisplayName(workspacePath, cache) {
97
+ if (typeof workspacePath !== 'string' || !workspacePath.trim())
98
+ return 'Current Workspace';
99
+ const trimmed = workspacePath.trim();
100
+ const resolved = path.resolve(trimmed);
101
+ const home = getUserHomeDir();
102
+ if (home && sameWorkspace(resolved, home, cache)) {
103
+ return '~';
104
+ }
105
+ const base = path.basename(resolved);
106
+ const cleanBase = cleanInlineText(base);
107
+ if (cleanBase)
108
+ return cleanBase;
109
+ const cleanRoot = cleanInlineText(resolved);
110
+ return cleanRoot || 'Current Workspace';
111
+ }
112
+ /**
113
+ * Format the dynamic section header label for the active workspace's sessions.
114
+ * Preserves the user's folder casing (for example `suika-game SESSIONS (2)` or
115
+ * `causyne-agent SESSIONS (0)`) while handling home and filesystem roots cleanly.
116
+ */
117
+ export function formatWorkspaceSectionTitle(workspacePath, sessionCount, cache) {
118
+ const name = workspaceDisplayName(workspacePath, cache);
119
+ let base;
120
+ if (name === '~') {
121
+ base = 'HOME (~) SESSIONS';
122
+ }
123
+ else if (name === '/' || isDriveRoot(name)) {
124
+ base = `WORKSPACE (${name}) SESSIONS`;
125
+ }
126
+ else {
127
+ base = `${name} SESSIONS`;
128
+ }
129
+ if (typeof sessionCount === 'number' && Number.isFinite(sessionCount) && sessionCount >= 0) {
130
+ return `${base} (${Math.floor(sessionCount)})`;
131
+ }
132
+ return base;
133
+ }