@agy-daddy/plugin-context 1.0.0 → 1.1.2

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/src/node.js CHANGED
@@ -10,6 +10,7 @@ const {
10
10
  analyzeTrajectorySteps,
11
11
  extractStepTimestampsFromTrajectory,
12
12
  parseGeneratorCall,
13
+ collectSessionGeneratorCalls,
13
14
  summarizeSessionGeneratorCalls,
14
15
  resolveThresholdTokens,
15
16
  formatThresholdLabel,
@@ -82,6 +83,7 @@ function readTranscriptStepTimestampsCached(cascadeId, brainDirs = null) {
82
83
  }
83
84
 
84
85
  let disposers = [];
86
+ let activeHost = null;
85
87
 
86
88
  function pickTargetCascadeId(requestedId, summariesObj = {}) {
87
89
  if (requestedId) return requestedId;
@@ -118,11 +120,15 @@ function buildAlerts(snapshot, settings = {}) {
118
120
  }
119
121
 
120
122
  async function activate(host) {
123
+ activeHost = host;
124
+ let deactivated = false;
121
125
  const availableModels = new Map();
122
126
  const seenCallIds = new Set();
123
127
  const recentCalls = [];
124
128
  const contextCacheBySession = new Map();
125
129
  let latestSnapshot = null;
130
+ let lastSessionCalls = [];
131
+ let lastUsageCurrencyKey = '';
126
132
 
127
133
  function loadSettings() {
128
134
  const saved = (typeof host.settings?.get === 'function' ? host.settings.get() : null) || {};
@@ -135,6 +141,7 @@ async function activate(host) {
135
141
  const showSpeed = saved.showSpeed !== undefined
136
142
  ? saved.showSpeed !== false
137
143
  : saved.showSpeedInTopbar !== false;
144
+ const showCost = saved.showCost !== false;
138
145
  const VALID_COMPACT_POLICIES = new Set(['remind', 'idle_prompt', 'cliff_auto', 'idle_and_cliff']);
139
146
  const compactPolicy = VALID_COMPACT_POLICIES.has(saved.compactPolicy)
140
147
  ? saved.compactPolicy
@@ -144,6 +151,7 @@ async function activate(host) {
144
151
  return {
145
152
  displayLocation,
146
153
  showSpeed,
154
+ showCost,
147
155
  pollIntervalMs: Number(saved.pollIntervalMs) >= 1000 ? Number(saved.pollIntervalMs) : 3000,
148
156
  warnThreshold,
149
157
  cliffThreshold,
@@ -152,17 +160,73 @@ async function activate(host) {
152
160
  };
153
161
  }
154
162
 
155
- function recomputeAlertsFromSettings() {
156
- if (!latestSnapshot || !latestSnapshot.hasSession) return;
163
+ async function checkUsageServiceAvailable() {
164
+ try {
165
+ if (typeof host.services?.has === 'function') {
166
+ return Boolean(await Promise.resolve(host.services.has('usage')));
167
+ }
168
+ } catch {}
169
+ return false;
170
+ }
171
+
172
+ function buildEmptySnapshot(settings = loadSettings(), usageAvailable = null) {
173
+ return {
174
+ ok: true,
175
+ hasSession: false,
176
+ cascadeId: null,
177
+ status: 'idle',
178
+ used: null,
179
+ budget: null,
180
+ percent: null,
181
+ remainPercent: null,
182
+ model: null,
183
+ speed: null,
184
+ sessionUsage: summarizeSessionGeneratorCalls([]),
185
+ groups: null,
186
+ attachments: { items: [], totals: { count: 0, chars: 0, bytes: 0, low: 0, high: 0 } },
187
+ alerts: [],
188
+ referenceCost: null,
189
+ usageServiceAvailable: usageAvailable,
190
+ displayLocation: settings.displayLocation,
191
+ showSpeed: settings.showSpeed,
192
+ showCost: settings.showCost,
193
+ compactPolicy: settings.compactPolicy,
194
+ warnThreshold: settings.warnThreshold,
195
+ cliffThreshold: settings.cliffThreshold,
196
+ updatedAt: Date.now()
197
+ };
198
+ }
199
+
200
+ function syncSnapshotFromSettings() {
157
201
  const settings = loadSettings();
202
+ if (!latestSnapshot || !latestSnapshot.hasSession) {
203
+ latestSnapshot = {
204
+ ...(latestSnapshot || buildEmptySnapshot(settings)),
205
+ displayLocation: settings.displayLocation,
206
+ showSpeed: settings.showSpeed,
207
+ showCost: settings.showCost,
208
+ compactPolicy: settings.compactPolicy,
209
+ warnThreshold: settings.warnThreshold,
210
+ cliffThreshold: settings.cliffThreshold,
211
+ updatedAt: Date.now()
212
+ };
213
+ host.state?.set?.('state:context.snapshot@1', latestSnapshot);
214
+ return;
215
+ }
158
216
  const used = Number(latestSnapshot.used || 0);
159
217
  const warnTokens = resolveThresholdTokens(settings.warnThreshold, latestSnapshot.budget, 240000);
160
218
  const cliffTokens = resolveThresholdTokens(settings.cliffThreshold, latestSnapshot.budget, 328000);
161
219
  const cacheCliffRisk = used >= cliffTokens
162
220
  ? 'critical'
163
221
  : (used >= warnTokens ? 'warn' : 'none');
222
+ const prevShowCost = latestSnapshot.showCost !== false;
164
223
  latestSnapshot = {
165
224
  ...latestSnapshot,
225
+ displayLocation: settings.displayLocation,
226
+ showSpeed: settings.showSpeed,
227
+ showCost: settings.showCost,
228
+ referenceCost: settings.showCost ? latestSnapshot.referenceCost : null,
229
+ compactPolicy: settings.compactPolicy,
166
230
  warnThreshold: settings.warnThreshold,
167
231
  cliffThreshold: settings.cliffThreshold,
168
232
  warnThresholdTokens: warnTokens,
@@ -172,7 +236,10 @@ async function activate(host) {
172
236
  updatedAt: Date.now()
173
237
  };
174
238
  host.storage.writeJson('latest-snapshot.json', latestSnapshot);
175
- host.state.set('state:context.snapshot@1', latestSnapshot);
239
+ host.state?.set?.('state:context.snapshot@1', latestSnapshot);
240
+ if (!prevShowCost && settings.showCost && !deactivated) {
241
+ void scanCascade({ cascadeId: latestSnapshot.cascadeId, force: true }).catch(() => {});
242
+ }
176
243
  }
177
244
 
178
245
  function recordNewGeneratorCalls(rows, cascadeId, parseOptions = {}) {
@@ -217,7 +284,7 @@ async function activate(host) {
217
284
  }
218
285
 
219
286
  let summaries = {};
220
- if (!cascadeId) {
287
+ if (!cascadeId && !options.isNewChat) {
221
288
  try {
222
289
  const allResp = await host.rpc.call('GetAllCascadeTrajectories', {
223
290
  metadata: { ideName: 'antigravity', extensionName: 'antigravity' }
@@ -228,26 +295,12 @@ async function activate(host) {
228
295
  }
229
296
 
230
297
  if (!cascadeId) {
231
- const emptySnap = {
232
- ok: true,
233
- hasSession: false,
234
- cascadeId: null,
235
- status: 'idle',
236
- used: null,
237
- budget: null,
238
- percent: null,
239
- remainPercent: null,
240
- model: null,
241
- speed: null,
242
- sessionUsage: summarizeSessionGeneratorCalls([]),
243
- groups: null,
244
- attachments: { items: [], totals: { count: 0, chars: 0, bytes: 0, low: 0, high: 0 } },
245
- alerts: [],
246
- referenceCost: null,
247
- updatedAt: Date.now()
248
- };
298
+ lastSessionCalls = [];
299
+ const usageAvailable = await checkUsageServiceAvailable();
300
+ const emptySnap = buildEmptySnapshot(settings, usageAvailable);
249
301
  latestSnapshot = emptySnap;
250
- host.state.set('state:context.snapshot@1', emptySnap);
302
+ host.storage.writeJson('latest-snapshot.json', emptySnap);
303
+ host.state?.set?.('state:context.snapshot@1', emptySnap);
251
304
  return emptySnap;
252
305
  }
253
306
 
@@ -303,6 +356,12 @@ async function activate(host) {
303
356
  stepTimestamps,
304
357
  fallbackTimestampMs
305
358
  });
359
+ const sessionCalls = collectSessionGeneratorCalls(gmRows, {
360
+ cascadeId,
361
+ source: 'desktop',
362
+ stepTimestamps,
363
+ fallbackTimestampMs
364
+ });
306
365
  const sessionUsage = summarizeSessionGeneratorCalls(gmRows, { cascadeId });
307
366
 
308
367
  const stepAnalysis = analyzeTrajectorySteps(steps, {
@@ -329,17 +388,27 @@ async function activate(host) {
329
388
  contextCacheBySession.set(cascadeId, metaSummary);
330
389
  }
331
390
 
332
- // 软消费可选 usage 服务获取本会话参考费用(usage 未安装时安全返回 null)
391
+ // 软消费可选 usage 服务获取本会话参考费用(usage 未安装或开关关闭时安全返回 null)
333
392
  let referenceCost = null;
393
+ let usageServiceAvailable = false;
334
394
  const callsForSession = recentCalls.filter((c) => c.cascadeId === cascadeId);
335
- const costInput = callsForSession.length ? callsForSession : newCalls;
336
- if (costInput.length > 0) {
395
+ const costInput = sessionCalls.length ? sessionCalls : (callsForSession.length ? callsForSession : newCalls);
396
+ lastSessionCalls = costInput;
397
+ if (settings.showCost && costInput.length > 0) {
337
398
  try {
338
- const usageRes = await host.services.call('usage', 'estimateCallsCost', [costInput], { optional: true });
339
- if (usageRes?.ok && usageRes.value) {
340
- referenceCost = usageRes.value;
399
+ const usageRes = await host.services.call('usage', 'estimateCallsCost', [costInput], { optional: true, timeoutMs: 2000 });
400
+ if (usageRes?.ok) {
401
+ usageServiceAvailable = true;
402
+ if (usageRes.value) {
403
+ referenceCost = usageRes.value;
404
+ if (referenceCost.currency) {
405
+ lastUsageCurrencyKey = `${referenceCost.currency}:${referenceCost.exchangeRate || ''}:${referenceCost.currencySymbol || ''}`;
406
+ }
407
+ }
341
408
  }
342
409
  } catch {}
410
+ } else {
411
+ usageServiceAvailable = await checkUsageServiceAvailable();
343
412
  }
344
413
 
345
414
  const snapshot = {
@@ -379,7 +448,12 @@ async function activate(host) {
379
448
  compressionDrop: stepAnalysis.compressionDrop,
380
449
  attachments: attachmentAudit,
381
450
  referenceCost,
451
+ usageServiceAvailable,
382
452
  alerts: [],
453
+ displayLocation: settings.displayLocation,
454
+ showSpeed: settings.showSpeed,
455
+ showCost: settings.showCost,
456
+ compactPolicy: settings.compactPolicy,
383
457
  updatedAt: Date.now()
384
458
  };
385
459
  snapshot.alerts = buildAlerts(snapshot, settings);
@@ -391,7 +465,13 @@ async function activate(host) {
391
465
  }
392
466
 
393
467
  const serviceMethods = {
468
+ getSettings() {
469
+ return loadSettings();
470
+ },
394
471
  async getSnapshot(opts = {}) {
472
+ if (opts.isNewChat && !opts.cascadeId) {
473
+ return await scanCascade(opts);
474
+ }
395
475
  if (!opts.force && latestSnapshot && (!opts.cascadeId || opts.cascadeId === latestSnapshot.cascadeId) && Date.now() - latestSnapshot.updatedAt < 1000) {
396
476
  return latestSnapshot;
397
477
  }
@@ -445,15 +525,44 @@ async function activate(host) {
445
525
  sessionUsage: snap.sessionUsage || summarizeSessionGeneratorCalls([]),
446
526
  alerts: snap.alerts || [],
447
527
  attachmentSummary: snap.attachments?.totals || { count: 0, high: 0 },
448
- referenceCost: snap.referenceCost || null,
528
+ referenceCost: settings.showCost ? (snap.referenceCost || null) : null,
529
+ usageServiceAvailable: snap.usageServiceAvailable ?? null,
530
+ showCost: settings.showCost,
449
531
  updatedAt: snap.updatedAt
450
532
  };
451
533
  },
452
534
  ingestRendererSnapshot(payload = {}) {
453
535
  if (!payload || typeof payload !== 'object') return { ok: false };
454
- latestSnapshot = { ...(latestSnapshot || {}), ...payload, updatedAt: Date.now() };
455
- host.state.set('state:context.snapshot@1', latestSnapshot);
536
+ const settings = loadSettings();
537
+ latestSnapshot = {
538
+ ...(latestSnapshot || {}),
539
+ ...payload,
540
+ displayLocation: payload.displayLocation ?? settings.displayLocation,
541
+ showSpeed: payload.showSpeed ?? settings.showSpeed,
542
+ showCost: payload.showCost ?? settings.showCost,
543
+ compactPolicy: payload.compactPolicy ?? settings.compactPolicy,
544
+ updatedAt: Date.now()
545
+ };
546
+ host.state?.set?.('state:context.snapshot@1', latestSnapshot);
456
547
  return { ok: true, snapshot: latestSnapshot };
548
+ },
549
+ ingestLiveState(payload = {}) {
550
+ if (payload === null) {
551
+ host.state?.set?.('state:context.live@1', null);
552
+ return { ok: true, live: null };
553
+ }
554
+ if (!payload || typeof payload !== 'object') return { ok: false };
555
+ const live = {
556
+ cascadeId: payload.cascadeId ? String(payload.cascadeId) : null,
557
+ busy: Boolean(payload.busy),
558
+ phase: String(payload.phase || (payload.busy ? 'waiting' : 'idle')),
559
+ tps: payload.tps === null || payload.tps === undefined ? null : Number(payload.tps),
560
+ ttft: payload.ttft === null || payload.ttft === undefined ? null : Number(payload.ttft),
561
+ estimatedOutputTokens: Number(payload.estimatedOutputTokens || 0),
562
+ updatedAt: Number(payload.updatedAt) || Date.now()
563
+ };
564
+ host.state?.set?.('state:context.live@1', live);
565
+ return { ok: true, live };
457
566
  }
458
567
  };
459
568
 
@@ -462,31 +571,74 @@ async function activate(host) {
462
571
  const stopRescanRoute = await host.bridge.registerRoute('/rescan', async (body) => serviceMethods.rescan(body || {}));
463
572
  const stopAuditRoute = await host.bridge.registerRoute('/audit-attachments', async (body) => serviceMethods.auditAttachments(body?.media || []));
464
573
  const stopIngestRoute = await host.bridge.registerRoute('/ingest-renderer-snapshot', async (body) => serviceMethods.ingestRendererSnapshot(body || {}));
574
+ const stopLiveRoute = await host.bridge.registerRoute('/live-state', async (body) => serviceMethods.ingestLiveState(body ?? null));
465
575
  const stopSettingsSub = typeof host.settings?.onChange === 'function'
466
- ? host.settings.onChange((_nextValues, changedKeys) => {
467
- const keys = Array.isArray(changedKeys) ? changedKeys : [];
468
- if (
469
- keys.length === 0 ||
470
- keys.includes('warnThreshold') ||
471
- keys.includes('cliffThreshold') ||
472
- keys.includes('warnThresholdTokens') ||
473
- keys.includes('cliffThresholdTokens')
474
- ) {
475
- recomputeAlertsFromSettings();
476
- }
576
+ ? host.settings.onChange(() => {
577
+ syncSnapshotFromSettings();
477
578
  })
478
579
  : () => {};
580
+ const stopUsageStateSub = typeof host.state?.subscribe === 'function'
581
+ ? await Promise.resolve(host.state.subscribe('state:usage.summary@1', (rawVal) => {
582
+ if (deactivated) return;
583
+ const val = (rawVal && typeof rawVal === 'object' && 'value' in rawVal) ? rawVal.value : rawVal;
584
+ if (!val || typeof val !== 'object') return;
585
+ const settings = loadSettings();
586
+ const curKey = `${val.currency || ''}:${val.exchangeRate || ''}:${val.currencySymbol || ''}`;
587
+ const currencyChanged = Boolean(val.currency) && curKey !== lastUsageCurrencyKey;
588
+ if (val.currency) lastUsageCurrencyKey = curKey;
589
+
590
+ if (!settings.showCost || !latestSnapshot?.hasSession) return;
591
+ if (latestSnapshot.referenceCost && currencyChanged && Number.isFinite(Number(latestSnapshot.referenceCost.totalUsd))) {
592
+ const rate = Number(val.exchangeRate) > 0 ? Number(val.exchangeRate) : (val.currency === 'CNY' ? 7.25 : 1);
593
+ const symbol = val.currencySymbol || (val.currency === 'CNY' ? '¥' : '$');
594
+ const nextCost = {
595
+ ...latestSnapshot.referenceCost,
596
+ currency: val.currency,
597
+ exchangeRate: rate,
598
+ currencySymbol: symbol,
599
+ totalDisplayCost: Number((Number(latestSnapshot.referenceCost.totalUsd) * rate).toFixed(4))
600
+ };
601
+ latestSnapshot = {
602
+ ...latestSnapshot,
603
+ referenceCost: nextCost,
604
+ usageServiceAvailable: true,
605
+ updatedAt: Date.now()
606
+ };
607
+ host.storage.writeJson('latest-snapshot.json', latestSnapshot);
608
+ host.state?.set?.('state:context.snapshot@1', latestSnapshot);
609
+ return;
610
+ }
611
+ if (!latestSnapshot.referenceCost && lastSessionCalls.length > 0) {
612
+ void host.services.call('usage', 'estimateCallsCost', [lastSessionCalls], { optional: true, timeoutMs: 2000 })
613
+ .then((res) => {
614
+ if (deactivated || !res?.ok || !res.value || !latestSnapshot?.hasSession) return;
615
+ latestSnapshot = {
616
+ ...latestSnapshot,
617
+ referenceCost: res.value,
618
+ usageServiceAvailable: true,
619
+ updatedAt: Date.now()
620
+ };
621
+ host.storage.writeJson('latest-snapshot.json', latestSnapshot);
622
+ host.state?.set?.('state:context.snapshot@1', latestSnapshot);
623
+ })
624
+ .catch(() => {});
625
+ }
626
+ }))
627
+ : () => {};
479
628
  const stopRescanCmd = typeof host.commands?.register === 'function'
480
629
  ? await host.commands.register('context.rescan', async (opts = {}) => serviceMethods.rescan(opts || {}))
481
630
  : () => {};
482
631
 
483
632
  disposers.push(
633
+ () => { deactivated = true; },
484
634
  stopSvc,
485
635
  stopSnapRoute,
486
636
  stopRescanRoute,
487
637
  stopAuditRoute,
488
638
  stopIngestRoute,
639
+ stopLiveRoute,
489
640
  stopSettingsSub,
641
+ stopUsageStateSub,
490
642
  stopRescanCmd
491
643
  );
492
644
  }
@@ -496,6 +648,12 @@ async function deactivate() {
496
648
  try { if (typeof fn === 'function') fn(); } catch {}
497
649
  }
498
650
  disposers = [];
651
+ const host = activeHost;
652
+ activeHost = null;
653
+ try {
654
+ host?.state?.set?.('state:context.snapshot@1', null);
655
+ host?.state?.set?.('state:context.live@1', null);
656
+ } catch {}
499
657
  }
500
658
 
501
659
  module.exports = {
@@ -259,6 +259,44 @@ const CONTEXT_PANEL_CSS = `
259
259
  color: var(--ag-text-secondary);
260
260
  }
261
261
 
262
+ .ag-ctx-cost-row {
263
+ display: flex;
264
+ align-items: baseline;
265
+ justify-content: space-between;
266
+ gap: 8px;
267
+ padding-top: 6px;
268
+ margin-top: 2px;
269
+ border-top: 1px dashed var(--ag-border-subcard);
270
+ }
271
+
272
+ .ag-ctx-cost-label {
273
+ display: inline-flex;
274
+ align-items: baseline;
275
+ gap: 5px;
276
+ font-size: 11px;
277
+ color: var(--ag-text-secondary);
278
+ min-width: 0;
279
+ }
280
+
281
+ .ag-ctx-cost-note {
282
+ font-size: 10.5px;
283
+ color: var(--ag-text-muted);
284
+ }
285
+
286
+ .ag-ctx-cost-val {
287
+ font-size: 13.5px;
288
+ font-weight: 600;
289
+ font-variant-numeric: tabular-nums;
290
+ letter-spacing: -0.01em;
291
+ color: var(--ag-text-primary);
292
+ white-space: nowrap;
293
+ }
294
+
295
+ .ag-ctx-cost-val[data-muted="true"] {
296
+ color: var(--ag-text-muted);
297
+ font-weight: 500;
298
+ }
299
+
262
300
  .ag-ctx-help-list {
263
301
  margin: 6px 0 0;
264
302
  padding-left: 14px;
@@ -1,8 +1,9 @@
1
1
  'use strict';
2
2
 
3
- const { formatTokensShort, getRingAccentToken } = require('./context-analyzer');
3
+ const { formatTokensShort, formatReferenceCost, getRingAccentToken } = require('./context-analyzer');
4
4
 
5
5
  const SESSION_STACK_ICON_SVG = '<svg width="11.5" height="11.5" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 2.5 2.5 5.5 8 8.5l5.5-3L8 2.5Z"/><path d="M2.5 8.5 8 11.5l5.5-3"/><path d="M2.5 11.5 8 14.5l5.5-3"/></svg>';
6
+ const COST_COIN_ICON_SVG = '<svg width="11.5" height="11.5" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="8" r="5.6"/><path d="M8 4.6v6.8"/><path d="M10.1 6.1c0-.9-.95-1.4-2.1-1.4s-2.1.5-2.1 1.4c0 1.8 4.2.9 4.2 2.8 0 .95-.95 1.5-2.1 1.5s-2.1-.55-2.1-1.5"/></svg>';
6
7
  const SPEED_BOLT_ICON_SVG = '<svg width="11.5" height="11.5" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9.2 1.8 3.6 9h4.1l-.9 5.2L12.4 7H8.3l.9-5.2Z"/></svg>';
7
8
  const ALERT_TRIANGLE_ICON_SVG = '<svg width="11.5" height="11.5" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 2.3 14 13H2L8 2.3Z"/><path d="M8 6.4v3.2"/><circle cx="8" cy="11.4" r="0.55" fill="currentColor" stroke="none"/></svg>';
8
9
  const COMPACT_ICON_SVG = '<svg width="11" height="11" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 2v4.5M5.5 4.2 8 6.7l2.5-2.5"/><path d="M8 14V9.5M5.5 11.8 8 9.3l2.5 2.5"/><path d="M2.5 8h11"/></svg>';
@@ -190,6 +191,17 @@ function buildCapsuleSegments(snap, opts = {}) {
190
191
  }
191
192
  ];
192
193
 
194
+ if (opts.showCost !== false && snap.showCost !== false) {
195
+ const costInfo = formatReferenceCost(snap.referenceCost);
196
+ if (costInfo && costInfo.hasCost) {
197
+ segments.push({
198
+ kind: 'cost',
199
+ iconSvg: COST_COIN_ICON_SVG,
200
+ text: costInfo.compactText
201
+ });
202
+ }
203
+ }
204
+
193
205
  if (opts.showSpeed !== false) {
194
206
  const live = opts.liveSpeed;
195
207
  if (live && live.active) {
@@ -244,6 +256,15 @@ function buildCapsuleTooltip(snap, opts = {}) {
244
256
  `当前对话累计: ${formatTokensShort(sessionTotal)} (${su.callsCount || 0} 次调用 · 输出 ${formatTokensShort(su.outputTokens ?? snap.outputTokens ?? 0)})`,
245
257
  speedLine
246
258
  ];
259
+ if (opts.showCost !== false && snap.showCost !== false) {
260
+ const costInfo = formatReferenceCost(snap.referenceCost);
261
+ if (costInfo && costInfo.hasCost) {
262
+ const partialNote = costInfo.partial ? ` · 含 ${costInfo.unpricedCount} 次未知模型` : '';
263
+ lines.push(`当前会话参考费用: ${costInfo.displayText} (${costInfo.currency} API 费率折算${partialNote})`);
264
+ } else if (costInfo && costInfo.unpriced) {
265
+ lines.push('当前会话参考费用: -- (当前模型暂无公开单价)');
266
+ }
267
+ }
247
268
  if (Array.isArray(snap.alerts) && snap.alerts.length) {
248
269
  lines.push(`风险提示: ${snap.alerts.map((a) => a.message).join(';')}`);
249
270
  }
@@ -264,7 +285,12 @@ function createPulseCapsuleController(options = {}) {
264
285
  const onCompactClick = typeof options.onCompactClick === 'function' ? options.onCompactClick : () => {};
265
286
  const mountedEntries = new Set(); // { wrap, btn, compactBtn }
266
287
  let lastSnapshot = null;
267
- let lastState = { showSpeed: options.showSpeed !== false, liveSpeed: null, showQuickCompact: false };
288
+ let lastState = {
289
+ showSpeed: options.showSpeed !== false,
290
+ showCost: options.showCost !== false,
291
+ liveSpeed: null,
292
+ showQuickCompact: false
293
+ };
268
294
  let enabled = options.enabled !== false;
269
295
 
270
296
  function applyStyleAndContent(entry, snap, stateOpts = lastState) {
@@ -427,6 +453,7 @@ function createPulseCapsuleController(options = {}) {
427
453
  if (stateOpts && typeof stateOpts === 'object') {
428
454
  lastState = {
429
455
  showSpeed: stateOpts.showSpeed !== undefined ? stateOpts.showSpeed !== false : lastState.showSpeed,
456
+ showCost: stateOpts.showCost !== undefined ? stateOpts.showCost !== false : lastState.showCost,
430
457
  liveSpeed: stateOpts.liveSpeed !== undefined ? stateOpts.liveSpeed : lastState.liveSpeed,
431
458
  showQuickCompact: stateOpts.showQuickCompact !== undefined ? Boolean(stateOpts.showQuickCompact) : lastState.showQuickCompact
432
459
  };
@@ -471,6 +498,7 @@ function createPulseCapsuleController(options = {}) {
471
498
 
472
499
  module.exports = {
473
500
  SESSION_STACK_ICON_SVG,
501
+ COST_COIN_ICON_SVG,
474
502
  SPEED_BOLT_ICON_SVG,
475
503
  ALERT_TRIANGLE_ICON_SVG,
476
504
  COMPACT_ICON_SVG,