@agy-daddy/plugin-context 0.0.0-stage → 1.0.0

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.
@@ -0,0 +1,995 @@
1
+ 'use strict';
2
+
3
+ const {
4
+ formatTokensShort,
5
+ formatThresholdLabel,
6
+ resolveThresholdTokens,
7
+ getRingAccentToken
8
+ } = require('./context-analyzer');
9
+ const {
10
+ PULSE_CAPSULE_CSS,
11
+ buildDualRatioSvg,
12
+ formatSpeedCompact,
13
+ buildCapsuleSegments,
14
+ buildCapsuleTooltip,
15
+ createPulseCapsuleController
16
+ } = require('./pulse-capsule');
17
+ const { CONTEXT_PANEL_CSS } = require('./panel-styles');
18
+ const { createStreamSpeedTracker } = require('./stream-speed-tracker');
19
+
20
+ let disposers = [];
21
+
22
+ const GROUP_LABELS = Object.freeze({
23
+ system: '系统',
24
+ user: '用户',
25
+ assistant: '回复',
26
+ tool: '工具',
27
+ thinking: '思考'
28
+ });
29
+
30
+ const STATUS_BADGE_MAP = Object.freeze({
31
+ estimated: { text: '估算', tone: 'muted' },
32
+ exceeded: { text: '窗口超限', tone: 'danger' },
33
+ network: { text: '网络异常', tone: 'danger' },
34
+ quota_exhausted: { text: '额度耗尽', tone: 'danger' },
35
+ rate_limited: { text: '请求限流', tone: 'warn' },
36
+ auth_error: { text: '认证异常', tone: 'danger' },
37
+ service_unavailable: { text: '服务过载', tone: 'warn' },
38
+ canceled: { text: '已取消', tone: 'muted' },
39
+ failed: { text: '请求失败', tone: 'danger' }
40
+ });
41
+
42
+ function formatStatusBadge(snap, liveSpeed = null) {
43
+ if (liveSpeed?.active) {
44
+ return { text: '流式生成中', tone: '' };
45
+ }
46
+ const status = String(snap?.status || '').trim();
47
+ if (!status || status === 'reported' || status === 'idle' || status === 'pending') {
48
+ return null;
49
+ }
50
+ return STATUS_BADGE_MAP[status] || null;
51
+ }
52
+
53
+ function normalizeContextSettings(raw = {}) {
54
+ const src = raw && typeof raw === 'object' ? raw : {};
55
+ let displayLocation = 'composer';
56
+ if (src.displayLocation === 'topbar' || src.displayLocation === 'composer') {
57
+ displayLocation = src.displayLocation;
58
+ } else if (src.showPulseCapsule === false) {
59
+ displayLocation = 'topbar';
60
+ }
61
+ const showSpeed = src.showSpeed !== undefined
62
+ ? src.showSpeed !== false
63
+ : src.showSpeedInTopbar !== false;
64
+ const VALID_COMPACT_POLICIES = new Set(['remind', 'idle_prompt', 'cliff_auto', 'idle_and_cliff']);
65
+ const compactPolicy = VALID_COMPACT_POLICIES.has(src.compactPolicy)
66
+ ? src.compactPolicy
67
+ : 'remind';
68
+ const warnThreshold = String(src.warnThreshold ?? (src.warnThresholdTokens ? String(src.warnThresholdTokens) : '240K')).trim() || '240K';
69
+ const cliffThreshold = String(src.cliffThreshold ?? (src.cliffThresholdTokens ? String(src.cliffThresholdTokens) : '328K')).trim() || '328K';
70
+ return {
71
+ displayLocation,
72
+ showSpeed,
73
+ pollIntervalMs: Number(src.pollIntervalMs) >= 1000 ? Number(src.pollIntervalMs) : 3000,
74
+ warnThreshold,
75
+ cliffThreshold,
76
+ compactPolicy,
77
+ autoCompactOnCacheDrop: src.autoCompactOnCacheDrop === true,
78
+ autoCompactCooldownMs: Number(src.autoCompactCooldownMs) > 0 ? Number(src.autoCompactCooldownMs) : 300000
79
+ };
80
+ }
81
+
82
+ function formatTopbarRingLabel(snapshot, showSpeed = true, liveSpeed = null) {
83
+ if (!snapshot || !snapshot.hasSession || snapshot.used === null) {
84
+ return '--';
85
+ }
86
+ const ratio = `${formatTokensShort(snapshot.used)}/${formatTokensShort(snapshot.budget)}`;
87
+ const sessionTotal = snapshot.sessionUsage?.totalTokens ?? snapshot.used;
88
+ const parts = [ratio, formatTokensShort(sessionTotal)];
89
+ if (showSpeed) {
90
+ if (liveSpeed?.active) {
91
+ parts.push(liveSpeed.tps ? `~${formatSpeedCompact(liveSpeed.tps)}` : '…');
92
+ } else if (snapshot.speed?.tps) {
93
+ parts.push(formatSpeedCompact(snapshot.speed.tps));
94
+ }
95
+ }
96
+ return parts.join(' · ');
97
+ }
98
+
99
+ function buildTopbarRingSvg(percent = 0, color = 'var(--ag-custom-token-accent, var(--ag-token-accent-default, currentColor))') {
100
+ const pct = Math.max(0, Math.min(100, Number(percent) || 0));
101
+ const r = 5.2;
102
+ const c = Number((2 * Math.PI * r).toFixed(2));
103
+ const dash = Number(((pct / 100) * c).toFixed(2));
104
+ return `<svg width="14" height="14" viewBox="0 0 14 14" aria-hidden="true">`
105
+ + `<circle cx="7" cy="7" r="${r}" fill="none" stroke="rgba(113,113,122,0.24)" stroke-width="2"/>`
106
+ + `<circle cx="7" cy="7" r="${r}" fill="none" stroke="${color}" stroke-width="2" stroke-linecap="round" stroke-dasharray="${dash} ${c}" transform="rotate(-90 7 7)"/>`
107
+ + `</svg>`;
108
+ }
109
+
110
+ function resolveGroupTokens(groupVal) {
111
+ if (typeof groupVal === 'number') return groupVal;
112
+ if (!groupVal || typeof groupVal !== 'object') return 0;
113
+ return Number(groupVal.tokens ?? groupVal.high ?? groupVal.low ?? 0) || 0;
114
+ }
115
+
116
+ function buildSortedGroups(groupsObj) {
117
+ if (!groupsObj || typeof groupsObj !== 'object') return [];
118
+ const defs = [
119
+ { key: 'system', label: GROUP_LABELS.system, val: resolveGroupTokens(groupsObj.system), present: groupsObj.system !== undefined },
120
+ { key: 'user', label: GROUP_LABELS.user, val: resolveGroupTokens(groupsObj.user), present: groupsObj.user !== undefined },
121
+ { key: 'assistant', label: GROUP_LABELS.assistant, val: resolveGroupTokens(groupsObj.assistant), present: groupsObj.assistant !== undefined },
122
+ { key: 'tool', label: GROUP_LABELS.tool, val: resolveGroupTokens(groupsObj.tool ?? groupsObj.tools), present: groupsObj.tool !== undefined || groupsObj.tools !== undefined },
123
+ { key: 'thinking', label: GROUP_LABELS.thinking, val: resolveGroupTokens(groupsObj.thinking ?? groupsObj.summaries), present: groupsObj.thinking !== undefined || groupsObj.summaries !== undefined }
124
+ ].filter((d) => d.present);
125
+
126
+ const hasNonZero = defs.some((d) => d.val > 0);
127
+ return defs
128
+ .filter((d) => !hasNonZero || d.val > 0)
129
+ .sort((a, b) => b.val - a.val);
130
+ }
131
+
132
+ function formatAttachmentMeta(attachments) {
133
+ const count = Number(attachments?.totals?.count || 0);
134
+ const high = Number(attachments?.totals?.high || 0);
135
+ if (count <= 0) return '无附件';
136
+ return high > 0 ? `附件 ${count} 项 · 约 ${formatTokensShort(high)}` : `附件 ${count} 项`;
137
+ }
138
+
139
+ function renderPanelHtml(snapshot, onRescan, liveSpeed = null) {
140
+ if (!snapshot || !snapshot.hasSession) {
141
+ return '暂无活跃 Antigravity 会话,点击刷新以采样。';
142
+ }
143
+ const su = snapshot.sessionUsage || {};
144
+ const sessionTotal = su.totalTokens ?? snapshot.used ?? 0;
145
+ const speedText = liveSpeed?.active
146
+ ? (liveSpeed.tps ? `~${formatSpeedCompact(liveSpeed.tps)} (流式估算)` : '生成中…')
147
+ : (snapshot.speed?.tps ? `${snapshot.speed.tps} tok/s` : '--');
148
+ const badge = formatStatusBadge(snapshot, liveSpeed);
149
+ const statusStr = badge ? ` (${badge.text})` : '';
150
+ const lines = [
151
+ `模型: ${snapshot.model || 'Unknown'}${statusStr}`,
152
+ `上下文窗口: ${formatTokensShort(snapshot.used)} / ${formatTokensShort(snapshot.budget)} (${snapshot.percent ?? '--'}%) · 剩余 ${snapshot.remainPercent ?? '--'}%`,
153
+ `单轮缓存: 命中 ${snapshot.cacheHitRate ?? 0}% (${formatTokensShort(snapshot.cachedTokens)} / ${formatTokensShort(snapshot.inputTokens)})`,
154
+ `本对话累计: ${formatTokensShort(sessionTotal)} · 输出 ${formatTokensShort(su.outputTokens ?? snapshot.outputTokens)} · 缓存读 ${formatTokensShort(su.cachedTokens ?? snapshot.cachedTokens)} · ${su.callsCount || 0} 次`,
155
+ `生成速度: ${speedText} · 纯吐字 ${snapshot.speed?.streamingTps ?? '--'} tok/s · TTFT ${liveSpeed?.active ? (liveSpeed.ttft ?? '--') : (snapshot.speed?.ttft ?? '--')}s`,
156
+ formatAttachmentMeta(snapshot.attachments)
157
+ ];
158
+ const groups = buildSortedGroups(snapshot.groups);
159
+ if (groups.length) {
160
+ lines.push(`上下文构成: ${groups.map((d) => `${d.label} ${formatTokensShort(d.val)}`).join(' · ')}`);
161
+ }
162
+ if (Array.isArray(snapshot.alerts) && snapshot.alerts.length) {
163
+ lines.push(`提示: ${snapshot.alerts.map((a) => a.message).join(';')}`);
164
+ }
165
+ if (typeof onRescan === 'function' && snapshot.__triggerRescan) {
166
+ onRescan();
167
+ }
168
+ return lines.join('\n');
169
+ }
170
+
171
+ const SEG_COLORS = [
172
+ 'var(--ag-text-primary, #18181b)',
173
+ 'var(--ag-text-secondary, #52525b)',
174
+ 'var(--ag-text-muted, #71717a)',
175
+ 'rgba(113, 113, 122, 0.5)',
176
+ 'rgba(113, 113, 122, 0.26)'
177
+ ];
178
+
179
+ const REFRESH_ICON_SVG = '<svg width="11.5" height="11.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a9 9 0 1 1-2.64-6.36"/><path d="M21 3v6h-6"/></svg>';
180
+
181
+ function extractAnchorRect(el) {
182
+ if (!el || typeof el.getBoundingClientRect !== 'function') return null;
183
+ const r = el.getBoundingClientRect();
184
+ if (!r) return null;
185
+ const top = Number(r.top);
186
+ const left = Number(r.left);
187
+ const right = Number(r.right);
188
+ const bottom = Number(r.bottom);
189
+ const width = Number(r.width);
190
+ const height = Number(r.height);
191
+ if (![top, left, right, bottom, width, height].every(Number.isFinite)) return null;
192
+ if (width <= 0 && height <= 0) return null;
193
+ return { top, left, right, bottom, width, height };
194
+ }
195
+
196
+ async function mount(ctx) {
197
+ dispose();
198
+
199
+ let settings = normalizeContextSettings(typeof ctx.settings?.get === 'function' ? ctx.settings.get() : {});
200
+ let latestSnapshot = null;
201
+ let latestLiveSpeed = null;
202
+ let helpExpanded = false;
203
+ let showQuickCompact = false;
204
+ let lastAutoCompactAt = 0;
205
+ let isSendingCompact = false;
206
+ let pendingAutoCompact = null;
207
+ let unitNode = null;
208
+ let stopUnit = null;
209
+ let panelNode = null;
210
+ let popoverHandle = null;
211
+ let stopPoll = null;
212
+ let stopLiveTick = null;
213
+ const trackedTimers = new Set();
214
+
215
+ const docRefGlobal = globalThis.document;
216
+ const speedTracker = createStreamSpeedTracker();
217
+
218
+ const stopPulseStyles = typeof ctx.styles?.inject === 'function'
219
+ ? ctx.styles.inject(PULSE_CAPSULE_CSS, { scope: 'document', id: 'context-pulse-styles' })
220
+ : () => {};
221
+
222
+ const stopPanelStyles = typeof ctx.styles?.inject === 'function'
223
+ ? ctx.styles.inject(CONTEXT_PANEL_CSS, { scope: 'shadow', id: 'context-panel-styles' })
224
+ : () => {};
225
+
226
+ function buildEl(docRef, tag, cls, text) {
227
+ const el = docRef.createElement(tag);
228
+ if (cls) el.className = cls;
229
+ if (text !== undefined) el.textContent = text;
230
+ return el;
231
+ }
232
+
233
+ function renderMetricRow(docRef, items) {
234
+ const grid = buildEl(docRef, 'div', 'ag-ctx-metrics');
235
+ for (const k of items) {
236
+ const cell = buildEl(docRef, 'div', 'ag-ctx-metric');
237
+ cell.appendChild(buildEl(docRef, 'span', 'ag-ctx-metric-label', k.label));
238
+ cell.appendChild(buildEl(docRef, 'span', 'ag-ctx-metric-val', k.value));
239
+ grid.appendChild(cell);
240
+ }
241
+ return grid;
242
+ }
243
+
244
+ function restoreDraftSafely(editor, prevDraft) {
245
+ const curEd = ctx.anchors.query('composer.editor') || editor;
246
+ if (!curEd) return;
247
+ const curText = String(curEd.textContent || '').replace(/[\u200B-\u200D\uFEFF]/g, '').trim();
248
+ if (typeof docRefGlobal?.execCommand === 'function') {
249
+ if (curText) return;
250
+ isSendingCompact = true;
251
+ try {
252
+ curEd.focus?.();
253
+ const sel = typeof globalThis.getSelection === 'function' ? globalThis.getSelection() : null;
254
+ if (sel && typeof docRefGlobal.createRange === 'function') {
255
+ const range = docRefGlobal.createRange();
256
+ range.selectNodeContents(curEd);
257
+ range.collapse(false);
258
+ sel.removeAllRanges();
259
+ sel.addRange(range);
260
+ }
261
+ let capturedBeforeInput = null;
262
+ const onBeforeInput = (ev) => {
263
+ if (ev && (!ev.inputType || ev.inputType === 'insertText')) {
264
+ capturedBeforeInput = ev;
265
+ }
266
+ };
267
+ const canListenDoc = typeof docRefGlobal.addEventListener === 'function' && typeof docRefGlobal.removeEventListener === 'function';
268
+ const canListenEd = typeof curEd.addEventListener === 'function' && typeof curEd.removeEventListener === 'function';
269
+ if (canListenDoc) docRefGlobal.addEventListener('beforeinput', onBeforeInput, true);
270
+ if (canListenEd) curEd.addEventListener('beforeinput', onBeforeInput, true);
271
+ let inserted = false;
272
+ try {
273
+ inserted = Boolean(docRefGlobal.execCommand('insertText', false, prevDraft));
274
+ } finally {
275
+ if (canListenDoc) docRefGlobal.removeEventListener('beforeinput', onBeforeInput, true);
276
+ if (canListenEd) curEd.removeEventListener('beforeinput', onBeforeInput, true);
277
+ }
278
+ const prevented = Boolean(capturedBeforeInput && capturedBeforeInput.defaultPrevented);
279
+ const afterText = String(curEd.textContent || '').replace(/[\u200B-\u200D\uFEFF]/g, '').trim();
280
+ if (!inserted && !prevented && !afterText) {
281
+ curEd.textContent = prevDraft;
282
+ }
283
+ } catch {
284
+ curEd.textContent = prevDraft;
285
+ } finally {
286
+ isSendingCompact = false;
287
+ }
288
+ return;
289
+ }
290
+ if (!curText || curText === '/compact') {
291
+ curEd.textContent = prevDraft;
292
+ }
293
+ }
294
+
295
+ function sendCompactSafely({ preserveDraft = true, reason = 'manual', thresholdTokens = null } = {}) {
296
+ if (isSendingCompact) return { ok: false, reason: 'in_flight' };
297
+ const editor = ctx.anchors.query('composer.editor');
298
+ const prevDraft = preserveDraft && editor ? String(editor.textContent || '') : '';
299
+ const hasDraft = Boolean(prevDraft.trim());
300
+ const prevAutoCompactAt = lastAutoCompactAt;
301
+ if (reason !== 'manual') {
302
+ lastAutoCompactAt = Date.now();
303
+ }
304
+ let sent = false;
305
+ isSendingCompact = true;
306
+ try {
307
+ sent = Boolean(ctx.hostDom?.sendText?.('/compact'));
308
+ } finally {
309
+ isSendingCompact = false;
310
+ }
311
+ if (!sent) {
312
+ if (reason !== 'manual') {
313
+ lastAutoCompactAt = prevAutoCompactAt;
314
+ }
315
+ return { ok: false, reason: 'send_failed' };
316
+ }
317
+
318
+ if (hasDraft && editor) {
319
+ const restoreDelayMs = typeof docRefGlobal?.execCommand === 'function' ? 320 : 80;
320
+ const tid = setTimeout(() => {
321
+ trackedTimers.delete(tid);
322
+ restoreDraftSafely(editor, prevDraft);
323
+ }, restoreDelayMs);
324
+ trackedTimers.add(tid);
325
+ }
326
+
327
+ if (reason !== 'manual') {
328
+ ctx.events?.emit?.('context:auto-compact-triggered@1', {
329
+ reason,
330
+ used: latestSnapshot?.used ?? null,
331
+ budget: latestSnapshot?.budget ?? null,
332
+ thresholdTokens,
333
+ preservedDraft: hasDraft
334
+ });
335
+ }
336
+ return { ok: true, preservedDraft: hasDraft };
337
+ }
338
+
339
+ function evaluateCompactState(snap, opts = {}) {
340
+ if (isSendingCompact) {
341
+ return { showQuickCompact, triggered: false, reason: 'in_flight' };
342
+ }
343
+ if (!snap || !snap.hasSession || typeof snap.used !== 'number') {
344
+ showQuickCompact = false;
345
+ pendingAutoCompact = null;
346
+ return { showQuickCompact: false, triggered: false, reason: 'no_session' };
347
+ }
348
+
349
+ const warnInfo = formatThresholdLabel(settings.warnThreshold, snap.budget, 240000);
350
+ const cliffInfo = formatThresholdLabel(settings.cliffThreshold, snap.budget, 328000);
351
+ const warnHit = snap.used >= warnInfo.tokens;
352
+ const cliffHit = snap.used >= cliffInfo.tokens;
353
+ const cacheDrop = Boolean(snap.cacheDropDetected);
354
+ const busy = Boolean(ctx.hostDom?.isAssistantBusy?.());
355
+ const editor = ctx.anchors.query('composer.editor');
356
+ const hasDraft = Boolean(String(editor?.textContent || '').trim());
357
+
358
+ const enableIdlePrompt = settings.compactPolicy === 'idle_prompt' || settings.compactPolicy === 'idle_and_cliff';
359
+ const enableCliffAuto = settings.compactPolicy === 'cliff_auto' || settings.compactPolicy === 'idle_and_cliff';
360
+
361
+ const nextQuickCompact = Boolean(
362
+ enableIdlePrompt &&
363
+ (warnHit || cacheDrop) &&
364
+ !busy &&
365
+ !hasDraft
366
+ );
367
+ showQuickCompact = nextQuickCompact;
368
+
369
+ if (opts?.allowAutoTrigger === false) {
370
+ return {
371
+ showQuickCompact: nextQuickCompact,
372
+ triggered: false,
373
+ reason: 'input_only',
374
+ warnTokens: warnInfo.tokens,
375
+ cliffTokens: cliffInfo.tokens
376
+ };
377
+ }
378
+
379
+ let autoReason = null;
380
+ let triggerThreshold = null;
381
+ if (settings.autoCompactOnCacheDrop && cacheDrop) {
382
+ autoReason = 'cache_drop';
383
+ } else if (enableCliffAuto && cliffHit) {
384
+ autoReason = 'cliff';
385
+ triggerThreshold = cliffInfo.tokens;
386
+ }
387
+
388
+ if (!autoReason) {
389
+ pendingAutoCompact = null;
390
+ return {
391
+ showQuickCompact: nextQuickCompact,
392
+ triggered: false,
393
+ reason: 'not_triggered',
394
+ warnTokens: warnInfo.tokens,
395
+ cliffTokens: cliffInfo.tokens
396
+ };
397
+ }
398
+
399
+ if (busy) {
400
+ pendingAutoCompact = { reason: autoReason, thresholdTokens: triggerThreshold };
401
+ return {
402
+ showQuickCompact: nextQuickCompact,
403
+ triggered: false,
404
+ pending: true,
405
+ reason: 'assistant_busy',
406
+ warnTokens: warnInfo.tokens,
407
+ cliffTokens: cliffInfo.tokens
408
+ };
409
+ }
410
+
411
+ const now = Date.now();
412
+ if (!opts?.bypassCooldown && lastAutoCompactAt > 0 && now - lastAutoCompactAt < settings.autoCompactCooldownMs) {
413
+ return {
414
+ showQuickCompact: nextQuickCompact,
415
+ triggered: false,
416
+ reason: 'cooldown',
417
+ warnTokens: warnInfo.tokens,
418
+ cliffTokens: cliffInfo.tokens
419
+ };
420
+ }
421
+
422
+ pendingAutoCompact = null;
423
+ const sendRes = sendCompactSafely({
424
+ preserveDraft: true,
425
+ reason: autoReason,
426
+ thresholdTokens: triggerThreshold
427
+ });
428
+ return {
429
+ showQuickCompact: nextQuickCompact,
430
+ triggered: Boolean(sendRes.ok),
431
+ reason: sendRes.ok ? autoReason : 'send_failed',
432
+ preservedDraft: Boolean(sendRes.preservedDraft),
433
+ warnTokens: warnInfo.tokens,
434
+ cliffTokens: cliffInfo.tokens
435
+ };
436
+ }
437
+
438
+ function updatePanelDom(snap, liveSpeed = latestLiveSpeed) {
439
+ if (!panelNode) return;
440
+ const docRef = panelNode.ownerDocument || globalThis.document;
441
+ if (!docRef?.createElement) {
442
+ panelNode.textContent = renderPanelHtml(snap, null, liveSpeed);
443
+ return;
444
+ }
445
+
446
+ panelNode.textContent = '';
447
+
448
+ // 1. Header: 模型名 + 仅在异常/流式时出现的状态标签 + 安静幽灵刷新按钮
449
+ const header = buildEl(docRef, 'div', 'ag-ctx-header');
450
+ const modelWrap = buildEl(docRef, 'div', 'ag-ctx-model-wrap');
451
+ modelWrap.appendChild(buildEl(docRef, 'span', 'ag-ctx-model', snap?.hasSession ? (snap.model || 'Unknown') : '等待会话采样'));
452
+ if (snap?.hasSession) {
453
+ const badge = formatStatusBadge(snap, liveSpeed);
454
+ if (badge) {
455
+ const chip = buildEl(docRef, 'span', 'ag-chip', badge.text);
456
+ if (badge.tone) chip.setAttribute('data-tone', badge.tone);
457
+ modelWrap.appendChild(chip);
458
+ }
459
+ }
460
+ header.appendChild(modelWrap);
461
+
462
+ const rescanBtn = buildEl(docRef, 'button', 'ag-ctx-refresh');
463
+ rescanBtn.type = 'button';
464
+ rescanBtn.setAttribute('aria-label', '重新扫描');
465
+ rescanBtn.setAttribute('title', '重新扫描当前会话');
466
+ const rescanIcon = buildEl(docRef, 'span', 'ag-svg-icon');
467
+ rescanIcon.setAttribute('aria-hidden', 'true');
468
+ rescanIcon.innerHTML = REFRESH_ICON_SVG;
469
+ rescanBtn.appendChild(rescanIcon);
470
+ rescanBtn.appendChild(buildEl(docRef, 'span', '', '刷新'));
471
+ rescanBtn.addEventListener('click', () => { void refresh(true); });
472
+ header.appendChild(rescanBtn);
473
+ panelNode.appendChild(header);
474
+
475
+ if (!snap || !snap.hasSession) {
476
+ panelNode.appendChild(buildEl(docRef, 'div', 'ag-ctx-empty', '暂无活跃 Antigravity 会话,点击刷新以采样。'));
477
+ return;
478
+ }
479
+
480
+ // 2. 上下文窗口
481
+ const pct = Math.max(0, Math.min(100, Number(snap.percent || 0)));
482
+ const warnInfo = formatThresholdLabel(settings.warnThreshold, snap.budget, 240000);
483
+ const cliffInfo = formatThresholdLabel(settings.cliffThreshold, snap.budget, 328000);
484
+ const riskTone = (snap.cacheCliffRisk === 'critical' || snap.cacheDropDetected)
485
+ ? 'danger'
486
+ : (snap.cacheCliffRisk === 'warn' ? 'warn' : '');
487
+ const winSec = buildEl(docRef, 'section', 'ag-ctx-section');
488
+ const winHead = buildEl(docRef, 'div', 'ag-ctx-sec-head');
489
+ winHead.appendChild(buildEl(docRef, 'span', 'ag-ctx-sec-title', '上下文窗口'));
490
+ winHead.appendChild(buildEl(docRef, 'span', 'ag-ctx-sec-meta', `预警 ${warnInfo.shortLabel} · 断崖 ${cliffInfo.shortLabel}`));
491
+ winSec.appendChild(winHead);
492
+
493
+ const heroRow = buildEl(docRef, 'div', 'ag-ctx-hero-row');
494
+ const heroVal = buildEl(docRef, 'div', 'ag-ctx-hero-val');
495
+ heroVal.appendChild(buildEl(docRef, 'span', '', formatTokensShort(snap.used)));
496
+ heroVal.appendChild(buildEl(docRef, 'span', 'ag-ctx-hero-budget', `/ ${formatTokensShort(snap.budget)}`));
497
+ heroRow.appendChild(heroVal);
498
+
499
+ const pctEl = buildEl(docRef, 'span', 'ag-ctx-hero-pct', `${snap.percent ?? '--'}%`);
500
+ if (riskTone) pctEl.setAttribute('data-tone', riskTone);
501
+ heroRow.appendChild(pctEl);
502
+ winSec.appendChild(heroRow);
503
+
504
+ const track = buildEl(docRef, 'div', 'ag-ctx-track');
505
+ const fill = buildEl(docRef, 'div', 'ag-ctx-fill');
506
+ if (riskTone) fill.setAttribute('data-tone', riskTone);
507
+ fill.style?.setProperty?.('width', `${pct}%`);
508
+ track.appendChild(fill);
509
+
510
+ const budgetNum = Number(snap.budget || 0);
511
+ if (budgetNum > 0) {
512
+ const warnPct = (warnInfo.tokens / budgetNum) * 100;
513
+ if (warnPct >= 5 && warnPct <= 95) {
514
+ const tWarn = buildEl(docRef, 'span', 'ag-ctx-tick');
515
+ tWarn.setAttribute('data-kind', 'warn');
516
+ tWarn.setAttribute('title', `预警阈值 ${warnInfo.shortLabel} (${formatTokensShort(warnInfo.tokens)})`);
517
+ tWarn.style?.setProperty?.('left', `${warnPct.toFixed(1)}%`);
518
+ track.appendChild(tWarn);
519
+ }
520
+ const cliffPct = (cliffInfo.tokens / budgetNum) * 100;
521
+ if (cliffPct >= 5 && cliffPct <= 95) {
522
+ const tCliff = buildEl(docRef, 'span', 'ag-ctx-tick');
523
+ tCliff.setAttribute('data-kind', 'cliff');
524
+ tCliff.setAttribute('title', `断崖阈值 ${cliffInfo.shortLabel} (${formatTokensShort(cliffInfo.tokens)})`);
525
+ tCliff.style?.setProperty?.('left', `${cliffPct.toFixed(1)}%`);
526
+ track.appendChild(tCliff);
527
+ }
528
+ }
529
+ winSec.appendChild(track);
530
+
531
+ const winSub = buildEl(docRef, 'div', 'ag-ctx-subline');
532
+ winSub.appendChild(buildEl(docRef, 'span', '', snap.remainPercent != null ? `剩余 ${snap.remainPercent}%` : '剩余 --'));
533
+ winSub.appendChild(buildEl(docRef, 'span', '', `缓存命中 ${snap.cacheHitRate ?? 0}% (${formatTokensShort(snap.cachedTokens)}/${formatTokensShort(snap.inputTokens)})`));
534
+ winSec.appendChild(winSub);
535
+
536
+ const needCompactHint = Boolean(snap.cacheDropDetected || snap.cacheCliffRisk === 'warn' || snap.cacheCliffRisk === 'critical');
537
+ if ((Array.isArray(snap.alerts) && snap.alerts.length) || needCompactHint) {
538
+ const alertRow = buildEl(docRef, 'div', 'ag-ctx-alerts');
539
+ for (const a of (snap.alerts || [])) {
540
+ const chip = buildEl(docRef, 'span', 'ag-chip', a.message);
541
+ chip.setAttribute('data-tone', a.level === 'danger' ? 'danger' : (a.level === 'warn' ? 'warn' : 'muted'));
542
+ alertRow.appendChild(chip);
543
+ }
544
+ if (needCompactHint) {
545
+ const compactBtn = buildEl(docRef, 'button', 'ag-ctx-refresh', '立即压缩');
546
+ compactBtn.type = 'button';
547
+ compactBtn.setAttribute('data-panel-compact', '1');
548
+ compactBtn.setAttribute('title', '发送 /compact 压缩当前对话上下文');
549
+ compactBtn.addEventListener('click', () => {
550
+ sendCompactSafely({ preserveDraft: false, reason: 'manual' });
551
+ });
552
+ alertRow.appendChild(compactBtn);
553
+ }
554
+ winSec.appendChild(alertRow);
555
+ }
556
+ panelNode.appendChild(winSec);
557
+
558
+ // 3. 本对话累计 Token
559
+ const su = snap.sessionUsage || {};
560
+ const sessSec = buildEl(docRef, 'section', 'ag-ctx-section');
561
+ const sessHead = buildEl(docRef, 'div', 'ag-ctx-sec-head');
562
+ sessHead.appendChild(buildEl(docRef, 'span', 'ag-ctx-sec-title', '本对话累计'));
563
+ sessHead.appendChild(buildEl(docRef, 'span', 'ag-ctx-sec-meta', `${su.callsCount || 0} 次调用`));
564
+ sessSec.appendChild(sessHead);
565
+
566
+ sessSec.appendChild(renderMetricRow(docRef, [
567
+ { label: '总计', value: formatTokensShort(su.totalTokens ?? snap.used) },
568
+ { label: '输出', value: formatTokensShort(su.outputTokens ?? snap.outputTokens) },
569
+ { label: '缓存读', value: formatTokensShort(su.cachedTokens ?? snap.cachedTokens) },
570
+ { label: '新输入', value: formatTokensShort(su.inputTokens ?? snap.inputTokens) }
571
+ ]));
572
+
573
+ const sessSub = buildEl(docRef, 'div', 'ag-ctx-subline');
574
+ sessSub.appendChild(buildEl(docRef, 'span', '', `思考 ${formatTokensShort(su.thinkingTokens || 0)} · 回答 ${formatTokensShort(su.responseTokens ?? su.outputTokens ?? 0)}`));
575
+ sessSub.appendChild(buildEl(docRef, 'span', '', '独立于顶栏用量'));
576
+ sessSec.appendChild(sessSub);
577
+ panelNode.appendChild(sessSec);
578
+
579
+ // 4. 生成速度
580
+ const speedSec = buildEl(docRef, 'section', 'ag-ctx-section');
581
+ const speedHead = buildEl(docRef, 'div', 'ag-ctx-sec-head');
582
+ speedHead.appendChild(buildEl(docRef, 'span', 'ag-ctx-sec-title', '生成速度'));
583
+ const speedModeLabel = liveSpeed?.active ? '流式估算' : (snap.speed?.tps ? '实测' : '待采样');
584
+ const speedChip = buildEl(docRef, 'span', 'ag-chip', speedModeLabel);
585
+ if (!liveSpeed?.active && !snap.speed?.tps) speedChip.setAttribute('data-tone', 'muted');
586
+ speedHead.appendChild(speedChip);
587
+ speedSec.appendChild(speedHead);
588
+
589
+ const activeTpsVal = liveSpeed?.active
590
+ ? (liveSpeed.tps ? `~${formatSpeedCompact(liveSpeed.tps)}` : '生成中…')
591
+ : (snap.speed?.tps ? `${snap.speed.tps}/s` : '--');
592
+ const pureStreamVal = snap.speed?.streamingTps ? `${snap.speed.streamingTps}/s` : '--';
593
+ const ttftRaw = liveSpeed?.active ? liveSpeed.ttft : snap.speed?.ttft;
594
+ const ttftVal = ttftRaw !== null && ttftRaw !== undefined ? `${ttftRaw}s` : '--';
595
+ const avgVal = su.avgTps ? `${su.avgTps}/s` : '--';
596
+
597
+ speedSec.appendChild(renderMetricRow(docRef, [
598
+ { label: '总速率', value: activeTpsVal },
599
+ { label: '纯吐字', value: pureStreamVal },
600
+ { label: '首字', value: ttftVal },
601
+ { label: '均速', value: avgVal }
602
+ ]));
603
+
604
+ const stepOut = liveSpeed?.active
605
+ ? formatTokensShort(liveSpeed.estimatedOutputTokens)
606
+ : formatTokensShort(snap.speed?.outputTokens ?? snap.outputTokens);
607
+ const stepDur = liveSpeed?.active ? (liveSpeed.elapsedSec ?? 0) : (snap.speed?.duration ?? '--');
608
+ const speedSub = buildEl(docRef, 'div', 'ag-ctx-subline');
609
+ speedSub.appendChild(buildEl(docRef, 'span', '', `本步 ${stepOut} · ${stepDur}s`));
610
+ if (su.avgStreamingTps) {
611
+ speedSub.appendChild(buildEl(docRef, 'span', '', `纯吐字均速 ${su.avgStreamingTps}/s`));
612
+ }
613
+ speedSec.appendChild(speedSub);
614
+ panelNode.appendChild(speedSec);
615
+
616
+ // 5. 上下文构成(按占比降序、中文标签)
617
+ const groups = buildSortedGroups(snap.groups);
618
+ if (groups.length) {
619
+ const gSec = buildEl(docRef, 'section', 'ag-ctx-section');
620
+ const gHead = buildEl(docRef, 'div', 'ag-ctx-sec-head');
621
+ gHead.appendChild(buildEl(docRef, 'span', 'ag-ctx-sec-title', '上下文构成'));
622
+ gHead.appendChild(buildEl(docRef, 'span', 'ag-ctx-sec-meta', formatAttachmentMeta(snap.attachments)));
623
+ gSec.appendChild(gHead);
624
+
625
+ const total = groups.reduce((acc, d) => acc + d.val, 0) || 1;
626
+ const segTrack = buildEl(docRef, 'div', 'ag-seg-track');
627
+ const segLegend = buildEl(docRef, 'div', 'ag-seg-legend');
628
+ groups.forEach((d, idx) => {
629
+ const share = Math.max(0, (d.val / total) * 100);
630
+ const color = SEG_COLORS[idx % SEG_COLORS.length];
631
+ if (share > 0) {
632
+ const seg = buildEl(docRef, 'div');
633
+ seg.style?.setProperty?.('width', `${share.toFixed(1)}%`);
634
+ seg.style?.setProperty?.('background', color);
635
+ segTrack.appendChild(seg);
636
+ }
637
+ const item = buildEl(docRef, 'span', 'ag-seg-item');
638
+ const dot = buildEl(docRef, 'span', 'ag-seg-dot');
639
+ dot.style?.setProperty?.('background', color);
640
+ item.appendChild(dot);
641
+ item.appendChild(buildEl(docRef, 'span', '', `${d.label} ${formatTokensShort(d.val)}`));
642
+ segLegend.appendChild(item);
643
+ });
644
+ gSec.appendChild(segTrack);
645
+ gSec.appendChild(segLegend);
646
+ panelNode.appendChild(gSec);
647
+ }
648
+
649
+ // 6. 渐进披露指标说明(默认折叠,不干扰扫读)
650
+ const helpDetails = buildEl(docRef, 'details', 'ag-ctx-help');
651
+ helpDetails.open = helpExpanded;
652
+ helpDetails.addEventListener('toggle', () => {
653
+ helpExpanded = Boolean(helpDetails.open);
654
+ });
655
+ helpDetails.appendChild(buildEl(docRef, 'summary', '', '指标说明'));
656
+ const helpList = buildEl(docRef, 'ul', 'ag-ctx-help-list');
657
+ for (const tip of [
658
+ '上下文窗口:单次请求的记忆容量(外环=占用、内环=缓存命中),刻度线为预警/断崖阈值,建议超 240K 时执行 /compact。',
659
+ '本对话累计:仅汇总当前对话全轮次模型消耗,与顶栏「用量」的跨会话历史总账相互独立。',
660
+ '生成速度:总速率含首字等待 (TTFT),纯吐字仅计流式输出阶段;生成中带 ~ 为实时估算,完成后切回实测值。'
661
+ ]) {
662
+ helpList.appendChild(buildEl(docRef, 'li', '', tip));
663
+ }
664
+ helpDetails.appendChild(helpList);
665
+ panelNode.appendChild(helpDetails);
666
+ }
667
+
668
+ async function updateUnitDom(snap, liveSpeed = latestLiveSpeed) {
669
+ if (settings.displayLocation !== 'topbar' || !stopUnit) return;
670
+
671
+ const color = getRingAccentToken(snap?.percent || 0, {
672
+ isCacheDrop: Boolean(snap?.cacheDropDetected),
673
+ isCliff328k: snap?.cacheCliffRisk === 'critical',
674
+ isWarn240k: snap?.cacheCliffRisk === 'warn'
675
+ });
676
+ const labelText = formatTopbarRingLabel(snap, settings.showSpeed, liveSpeed);
677
+ const svgHtml = buildTopbarRingSvg(snap?.percent || 0, color);
678
+ const segments = buildCapsuleSegments(snap, {
679
+ showSpeed: settings.showSpeed,
680
+ liveSpeed
681
+ });
682
+ const tooltip = buildCapsuleTooltip(snap, { liveSpeed });
683
+ const tone = (snap?.cacheCliffRisk === 'critical' || snap?.cacheDropDetected)
684
+ ? 'danger'
685
+ : (snap?.cacheCliffRisk === 'warn' ? 'warn' : '');
686
+
687
+ if (typeof ctx.topbar?.updateUnit === 'function') {
688
+ try {
689
+ await ctx.topbar.updateUnit('ring', {
690
+ label: labelText,
691
+ iconSvg: svgHtml,
692
+ segments,
693
+ title: tooltip,
694
+ tone
695
+ });
696
+ return;
697
+ } catch {}
698
+ }
699
+
700
+ if (!unitNode) return;
701
+ const docRef = unitNode.ownerDocument || globalThis.document;
702
+ if (docRef?.createElement) {
703
+ unitNode.textContent = '';
704
+ for (const seg of segments) {
705
+ const segEl = docRef.createElement('span');
706
+ segEl.className = 'ag-unit-seg';
707
+ if (seg.tone) segEl.setAttribute('data-tone', seg.tone);
708
+ if (seg.iconSvg) {
709
+ const iconSpan = docRef.createElement('span');
710
+ iconSpan.className = 'ag-unit-icon';
711
+ iconSpan.innerHTML = seg.iconSvg;
712
+ segEl.appendChild(iconSpan);
713
+ }
714
+ if (seg.text) {
715
+ const textSpan = docRef.createElement('span');
716
+ textSpan.className = 'ag-unit-label';
717
+ textSpan.textContent = seg.text;
718
+ segEl.appendChild(textSpan);
719
+ }
720
+ unitNode.appendChild(segEl);
721
+ }
722
+ } else {
723
+ unitNode.textContent = labelText;
724
+ }
725
+ unitNode.setAttribute?.('title', tooltip);
726
+ if (tone) {
727
+ unitNode.setAttribute?.('data-tone', tone);
728
+ unitNode.setAttribute?.('data-risk', tone);
729
+ } else {
730
+ unitNode.removeAttribute?.('data-tone');
731
+ unitNode.removeAttribute?.('data-risk');
732
+ }
733
+ }
734
+
735
+ popoverHandle = ctx.topbar.registerPopover({
736
+ id: 'context-panel',
737
+ anchorId: 'ring',
738
+ title: '当前对话实时状态',
739
+ render(bodyNode) {
740
+ bodyNode.id = 'agy-context-panel';
741
+ panelNode = bodyNode;
742
+ updatePanelDom(latestSnapshot, latestLiveSpeed);
743
+ },
744
+ onToggle(open) {
745
+ if (open) {
746
+ updatePanelDom(latestSnapshot, latestLiveSpeed);
747
+ void refresh(false);
748
+ }
749
+ }
750
+ });
751
+
752
+ const pulseController = createPulseCapsuleController({
753
+ doc: globalThis.document,
754
+ anchors: ctx.anchors,
755
+ enabled: settings.displayLocation === 'composer',
756
+ showSpeed: settings.showSpeed,
757
+ onClick(btnEl) {
758
+ const anchorRect = extractAnchorRect(btnEl);
759
+ popoverHandle?.toggle(undefined, { anchorRect, placement: 'top' });
760
+ },
761
+ onCompactClick() {
762
+ sendCompactSafely({ preserveDraft: false, reason: 'manual' });
763
+ }
764
+ });
765
+
766
+ function syncDisplayLocation() {
767
+ if (settings.displayLocation === 'topbar') {
768
+ pulseController.setEnabled(false);
769
+ ctx.topbar?.setAvailable?.(true);
770
+ if (!stopUnit) {
771
+ stopUnit = ctx.topbar.registerUnit({
772
+ id: 'ring',
773
+ order: 10,
774
+ label: '--',
775
+ iconSvg: buildTopbarRingSvg(0),
776
+ segments: buildCapsuleSegments(latestSnapshot, { showSpeed: settings.showSpeed, liveSpeed: latestLiveSpeed }),
777
+ title: buildCapsuleTooltip(latestSnapshot, { liveSpeed: latestLiveSpeed }),
778
+ render(node) {
779
+ unitNode = node;
780
+ },
781
+ onClick() {
782
+ popoverHandle?.toggle(undefined, { placement: 'bottom' });
783
+ }
784
+ });
785
+ }
786
+ void updateUnitDom(latestSnapshot, latestLiveSpeed);
787
+ } else {
788
+ if (typeof stopUnit === 'function') {
789
+ try { stopUnit(); } catch {}
790
+ stopUnit = null;
791
+ }
792
+ unitNode = null;
793
+ ctx.topbar?.setAvailable?.(false);
794
+ pulseController.setEnabled(true);
795
+ pulseController.update(latestSnapshot, {
796
+ showSpeed: settings.showSpeed,
797
+ liveSpeed: latestLiveSpeed,
798
+ showQuickCompact
799
+ });
800
+ }
801
+ }
802
+
803
+ function syncActiveDisplays() {
804
+ if (settings.displayLocation === 'topbar') {
805
+ void updateUnitDom(latestSnapshot, latestLiveSpeed);
806
+ } else {
807
+ pulseController.update(latestSnapshot, {
808
+ showSpeed: settings.showSpeed,
809
+ liveSpeed: latestLiveSpeed,
810
+ showQuickCompact
811
+ });
812
+ }
813
+ updatePanelDom(latestSnapshot, latestLiveSpeed);
814
+ }
815
+
816
+ function getLiveAssistantText() {
817
+ const list = ctx.anchors.query('chat.messageList');
818
+ if (list && typeof list.querySelectorAll === 'function') {
819
+ const responses = list.querySelectorAll('[data-testid="agent-response"]');
820
+ if (responses && responses.length > 0) {
821
+ return String(responses[responses.length - 1]?.textContent || '');
822
+ }
823
+ return String(list.textContent || '');
824
+ }
825
+ if (docRefGlobal && typeof docRefGlobal.querySelectorAll === 'function') {
826
+ const responses = docRefGlobal.querySelectorAll('[data-testid="agent-response"]');
827
+ if (responses && responses.length > 0) {
828
+ return String(responses[responses.length - 1]?.textContent || '');
829
+ }
830
+ }
831
+ return String(list?.textContent || '');
832
+ }
833
+
834
+ function sampleLiveStreaming() {
835
+ const busy = Boolean(ctx.hostDom?.isAssistantBusy?.());
836
+ const text = busy ? getLiveAssistantText() : '';
837
+ const { live, completed } = speedTracker.sample({ busy, text });
838
+ const prevKey = latestLiveSpeed
839
+ ? `${latestLiveSpeed.phase}:${latestLiveSpeed.tps}:${latestLiveSpeed.estimatedOutputTokens}`
840
+ : 'idle';
841
+ const nextKey = live
842
+ ? `${live.phase}:${live.tps}:${live.estimatedOutputTokens}`
843
+ : 'idle';
844
+ latestLiveSpeed = live;
845
+
846
+ const prevQuick = showQuickCompact;
847
+ evaluateCompactState(latestSnapshot);
848
+ if (prevKey !== nextKey || prevQuick !== showQuickCompact || busy) {
849
+ syncActiveDisplays();
850
+ }
851
+ if (completed) {
852
+ void refresh(true);
853
+ }
854
+ }
855
+
856
+ async function refresh(force = false) {
857
+ try {
858
+ const endpoint = force ? '/rescan' : '/snapshot';
859
+ const cascadeId = ctx.hostDom?.getSessionId?.() || null;
860
+ const snap = await ctx.bridge.post(endpoint, { cascadeId, force });
861
+ if (snap && typeof snap === 'object') {
862
+ latestSnapshot = snap;
863
+ evaluateCompactState(snap);
864
+ syncActiveDisplays();
865
+ try { await ctx.state.set('state:context.snapshot@1', snap); } catch {}
866
+ }
867
+ return snap;
868
+ } catch {
869
+ return null;
870
+ }
871
+ }
872
+
873
+ function startPollLoop() {
874
+ if (typeof stopPoll === 'function') {
875
+ try { stopPoll(); } catch {}
876
+ stopPoll = null;
877
+ }
878
+ stopPoll = ctx.schedule.every(settings.pollIntervalMs, () => {
879
+ void refresh(false);
880
+ });
881
+ }
882
+
883
+ function startLiveSpeedLoop() {
884
+ if (typeof stopLiveTick === 'function') {
885
+ try { stopLiveTick(); } catch {}
886
+ stopLiveTick = null;
887
+ }
888
+ stopLiveTick = ctx.schedule.every(400, () => {
889
+ sampleLiveStreaming();
890
+ });
891
+ }
892
+
893
+ const onDocInput = () => {
894
+ if (isSendingCompact) return;
895
+ const prevQuick = showQuickCompact;
896
+ evaluateCompactState(latestSnapshot, { allowAutoTrigger: false });
897
+ if (prevQuick !== showQuickCompact && settings.displayLocation === 'composer') {
898
+ pulseController.update(latestSnapshot, { showQuickCompact });
899
+ }
900
+ };
901
+ docRefGlobal?.addEventListener?.('input', onDocInput, true);
902
+
903
+ const stopSettingsSub = typeof ctx.settings?.onChange === 'function'
904
+ ? ctx.settings.onChange((nextValues, changedKeys) => {
905
+ const prevPoll = settings.pollIntervalMs;
906
+ const prevLocation = settings.displayLocation;
907
+ settings = normalizeContextSettings(nextValues);
908
+ const keys = Array.isArray(changedKeys) ? changedKeys : [];
909
+ if (settings.displayLocation !== prevLocation || keys.includes('displayLocation') || keys.includes('showPulseCapsule')) {
910
+ popoverHandle?.toggle(false);
911
+ syncDisplayLocation();
912
+ }
913
+ if (latestSnapshot && latestSnapshot.hasSession) {
914
+ const warnTokens = resolveThresholdTokens(settings.warnThreshold, latestSnapshot.budget, 240000);
915
+ const cliffTokens = resolveThresholdTokens(settings.cliffThreshold, latestSnapshot.budget, 328000);
916
+ const used = Number(latestSnapshot.used || 0);
917
+ latestSnapshot = {
918
+ ...latestSnapshot,
919
+ warnThreshold: settings.warnThreshold,
920
+ cliffThreshold: settings.cliffThreshold,
921
+ warnThresholdTokens: warnTokens,
922
+ cliffThresholdTokens: cliffTokens,
923
+ cacheCliffRisk: used >= cliffTokens ? 'critical' : (used >= warnTokens ? 'warn' : 'none')
924
+ };
925
+ if (keys.length === 0 || keys.includes('warnThreshold') || keys.includes('cliffThreshold') || keys.includes('warnThresholdTokens') || keys.includes('cliffThresholdTokens')) {
926
+ void refresh(false);
927
+ }
928
+ evaluateCompactState(latestSnapshot);
929
+ }
930
+ syncActiveDisplays();
931
+ if (settings.pollIntervalMs !== prevPoll) {
932
+ startPollLoop();
933
+ }
934
+ })
935
+ : () => {};
936
+
937
+ const stopUiSvc = ctx.services.provide('context-ui', {
938
+ getSnapshot: () => latestSnapshot,
939
+ rescan: () => refresh(true),
940
+ evaluateCompactState: (snapOverride, opts) => {
941
+ if (snapOverride) latestSnapshot = snapOverride;
942
+ const res = evaluateCompactState(latestSnapshot, opts);
943
+ syncActiveDisplays();
944
+ return res;
945
+ },
946
+ triggerCompact: (opts) => sendCompactSafely(opts),
947
+ togglePanel(force, opts) {
948
+ let resolvedOpts = opts;
949
+ if (!resolvedOpts && settings.displayLocation === 'composer') {
950
+ const btn = docRefGlobal?.querySelector?.('[data-agy-context-capsule="1"]');
951
+ resolvedOpts = { anchorRect: extractAnchorRect(btn), placement: 'top' };
952
+ }
953
+ return popoverHandle?.toggle(force, resolvedOpts);
954
+ },
955
+ sampleLiveStreaming: () => sampleLiveStreaming()
956
+ });
957
+
958
+ syncDisplayLocation();
959
+ await refresh(false);
960
+ startPollLoop();
961
+ startLiveSpeedLoop();
962
+
963
+ disposers.push(
964
+ () => { if (typeof stopPoll === 'function') stopPoll(); stopPoll = null; },
965
+ () => { if (typeof stopLiveTick === 'function') stopLiveTick(); stopLiveTick = null; },
966
+ () => docRefGlobal?.removeEventListener?.('input', onDocInput, true),
967
+ () => {
968
+ for (const tid of Array.from(trackedTimers)) clearTimeout(tid);
969
+ trackedTimers.clear();
970
+ },
971
+ stopSettingsSub,
972
+ stopUiSvc,
973
+ () => { if (typeof stopUnit === 'function') stopUnit(); stopUnit = null; unitNode = null; },
974
+ () => popoverHandle?.dispose(),
975
+ () => pulseController.dispose(),
976
+ stopPanelStyles,
977
+ stopPulseStyles
978
+ );
979
+ }
980
+
981
+ function dispose() {
982
+ for (const fn of disposers) {
983
+ try { if (typeof fn === 'function') fn(); } catch {}
984
+ }
985
+ disposers = [];
986
+ }
987
+
988
+ module.exports = {
989
+ normalizeContextSettings,
990
+ formatStatusBadge,
991
+ formatTopbarRingLabel,
992
+ renderPanelHtml,
993
+ mount,
994
+ dispose
995
+ };