@niracler/encore 0.4.0 → 0.4.1

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,122 @@
1
+ import { spawnSync } from 'node:child_process'
2
+ import { existsSync } from 'node:fs'
3
+ import { join } from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
5
+ import { createRequire } from 'node:module'
6
+
7
+ const require = createRequire(import.meta.url)
8
+
9
+ export function readAntigravityDatabase(path, read) {
10
+ if (!existsSync(path)) return
11
+ let db
12
+ try {
13
+ const Database = process.getBuiltinModule?.('node:sqlite')?.DatabaseSync
14
+ db = Database && new Database(path, { readOnly: true })
15
+ const query = sql => {
16
+ if (db) return db.prepare(sql).all()
17
+ const result = spawnSync('sqlite3', ['-readonly', '-json', path, sql], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 })
18
+ if (result.error || result.status !== 0) throw result.error || new Error(result.stderr)
19
+ return JSON.parse(result.stdout || '[]')
20
+ }
21
+ return read(query, !!db)
22
+ } catch {
23
+ // Older versions, unavailable SQLite readers and incomplete native metadata
24
+ // can still export a Replay directly from the transcript.
25
+ return undefined
26
+ } finally {
27
+ db?.close()
28
+ }
29
+ }
30
+
31
+ let generationType
32
+ const categoryFor = type => ({ 2: 'schema', 3: 'mem', 4: 'schema', 5: 'skill' })[type] || 'sys'
33
+
34
+ function openingContext(chat, breakdown, includeMemory) {
35
+ const context = {}
36
+ const sections = new Map(chat.promptSections.map(section => [section.title, section]))
37
+ const tools = new Map(chat.tools.map(tool => [tool.name, tool]))
38
+ let nextId = 0
39
+ function add(category, title, payload, tokEst) {
40
+ // A monolithic prompt can inline cross-session memory alongside system rules.
41
+ const sensitive = category === 'mem' || /user_information|user_rules|MEMORY_SUMMARY|<conversation_history>/i.test(title + '\n' + payload)
42
+ const record = { id: 'agy-init-' + nextId++, title,
43
+ payload: sensitive && !includeMemory ? '[Private context omitted · --include-memory]' : payload }
44
+ if (tokEst !== undefined) record.tokEst = tokEst
45
+ context[category] ||= []
46
+ context[category].push(record)
47
+ }
48
+ function addNamed(category, name, count) {
49
+ const tool = category === 'schema' && tools.get(name)
50
+ const section = sections.get(name)
51
+ if (tool) {
52
+ add(category, name, [tool.description, tool.jsonSchemaString].filter(Boolean).join('\n\n'), count)
53
+ tools.delete(name)
54
+ } else {
55
+ add(category, name, section?.content || '', count)
56
+ sections.delete(name)
57
+ }
58
+ }
59
+ if (breakdown?.groups.length) {
60
+ // TOKEN_SOURCE_SYSTEM (1) identifies mounted input. Chat Messages (7)
61
+ // include the first user turn and never belong to the opening baseline.
62
+ const mounted = breakdown.groups.filter(group => group.source === 1 && group.type !== 7)
63
+ if (mounted.length && breakdown.groups.reduce((n, group) => n + group.numTokens, 0) === breakdown.totalTokens) {
64
+ context.estimatedTokens = mounted.reduce((n, group) => n + group.numTokens, 0)
65
+ }
66
+ for (const group of mounted) {
67
+ const category = categoryFor(group.type)
68
+ if (group.children.length) {
69
+ for (const child of group.children) addNamed(category, child.name, child.numTokens)
70
+ } else addNamed(category, group.name, group.numTokens)
71
+ }
72
+ }
73
+ for (const section of sections.values()) add(categoryFor(section.tokenType), section.title, section.content)
74
+ for (const tool of tools.values()) addNamed('schema', tool.name)
75
+ if (!chat.promptSections.length && chat.systemPrompt) add('sys', 'System Prompt', chat.systemPrompt)
76
+ return Object.keys(context).length ? context : undefined
77
+ }
78
+
79
+ export function readAntigravityContext(native, records, includeMemory) {
80
+ const requests = records.filter(row => row.type === 'PLANNER_RESPONSE').map(row => row.step_index)
81
+ if (!native || !requests.length) return
82
+ const dbPath = join(native.root, '..', '..', 'conversations', native.id + '.db')
83
+ return readAntigravityDatabase(dbPath, (query, binary) => {
84
+ generationType ||= require('protobufjs').loadSync(fileURLToPath(new URL('./antigravity-context.proto', import.meta.url))).lookupType('CortexStepGeneratorMetadata')
85
+ const windows = new Map()
86
+ const breakdowns = new Map()
87
+ let initialContext
88
+ let cursor = -1
89
+ for (;;) {
90
+ const rows = query('SELECT idx, ' + (binary ? 'data' : 'hex(data)') + ' AS payload FROM gen_metadata WHERE idx > ' + cursor + ' ORDER BY idx LIMIT 16')
91
+ if (!rows.length) break
92
+ for (const row of rows) {
93
+ cursor = row.idx
94
+ const bytes = binary ? row.payload : Buffer.from(row.payload, 'hex')
95
+ let generation
96
+ try {
97
+ generation = generationType.decode(bytes)
98
+ } catch {
99
+ // A damaged generation must not discard valid measurements from its neighbours.
100
+ continue
101
+ }
102
+ const { chatModel: chat, stepIndices } = generation
103
+ const window = chat?.chatStartMetadata?.contextWindowMetadata
104
+ if (window?.tokenBreakdown?.groups.length) {
105
+ const estimates = {}
106
+ for (const group of window.tokenBreakdown.groups) {
107
+ if (group.source !== 1 || group.type === 7) continue
108
+ const category = categoryFor(group.type)
109
+ estimates[category] = (estimates[category] || 0) + group.numTokens
110
+ }
111
+ for (const step of stepIndices) breakdowns.set(step, estimates)
112
+ }
113
+ if (window?.maxContextTokens > 0) for (const step of stepIndices) windows.set(step, window.maxContextTokens)
114
+ if (row.idx === 0 && chat && stepIndices.includes(requests[0]) && records[0]?.step_index === 0) {
115
+ initialContext = openingContext(chat, window?.tokenBreakdown, includeMemory)
116
+ }
117
+ }
118
+ }
119
+ const limits = new Set(requests.map(step => windows.get(step)))
120
+ return { initialContext, contextWindow: windows.get(requests[0]), variableWindows: limits.size > 1, windows, breakdowns }
121
+ })
122
+ }
@@ -0,0 +1,43 @@
1
+ // Read-only projection of Antigravity's gen_metadata.data. Keep native field
2
+ // numbers; message history and tool results are intentionally outside this view.
3
+ syntax = "proto3";
4
+ message CortexStepGeneratorMetadata {
5
+ ChatModelMetadata chat_model = 1;
6
+ repeated int32 step_indices = 2;
7
+ }
8
+ message ChatModelMetadata {
9
+ string system_prompt = 1;
10
+ repeated ChatToolDefinition tools = 8;
11
+ ChatStartMetadata chat_start_metadata = 9;
12
+ repeated PromptSection prompt_sections = 16;
13
+ }
14
+ message ChatToolDefinition {
15
+ string name = 1;
16
+ string description = 2;
17
+ string json_schema_string = 3;
18
+ }
19
+ message PromptSection {
20
+ string title = 1;
21
+ string content = 2;
22
+ int32 token_type = 6;
23
+ }
24
+ message ChatStartMetadata { ContextWindowMetadata context_window_metadata = 10; }
25
+ message ContextWindowMetadata {
26
+ TokenBreakdown token_breakdown = 3;
27
+ int32 max_context_tokens = 4;
28
+ }
29
+ message TokenBreakdown {
30
+ repeated TopLevelTokenGroup groups = 1;
31
+ int32 total_tokens = 2;
32
+ }
33
+ message TopLevelTokenGroup {
34
+ string name = 1;
35
+ int32 type = 2;
36
+ int32 source = 3;
37
+ int32 num_tokens = 4;
38
+ repeated TokenGroup children = 5;
39
+ }
40
+ message TokenGroup {
41
+ string name = 1;
42
+ int32 num_tokens = 3;
43
+ }
@@ -1,4 +1,4 @@
1
- import { spawnSync } from 'node:child_process'
1
+ import { readAntigravityDatabase, readAntigravityContext } from './antigravity-context.mjs'
2
2
  import { fileURLToPath } from 'node:url'
3
3
  import { existsSync, readFileSync, realpathSync } from 'node:fs'
4
4
  import { readFile, realpath, stat } from 'node:fs/promises'
@@ -29,17 +29,7 @@ export function nativeAntigravityLog(file) {
29
29
  // Newer installations index conversation titles, activity, workspaces and App archives in SQLite.
30
30
  export function antigravitySummaries(root) {
31
31
  const path = join(dirname(root), 'conversation_summaries.db')
32
- if (!existsSync(path)) return new Map()
33
- let db
34
- try {
35
- const Database = process.getBuiltinModule?.('node:sqlite')?.DatabaseSync
36
- db = Database && new Database(path, { readOnly: true })
37
- function query(sql) {
38
- if (db) return db.prepare(sql).all()
39
- const result = spawnSync('sqlite3', ['-readonly', '-json', path, sql], { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 })
40
- if (result.error || result.status !== 0) throw result.error || new Error(result.stderr)
41
- return JSON.parse(result.stdout || '[]')
42
- }
32
+ return readAntigravityDatabase(path, query => {
43
33
  const summaries = query('SELECT conversation_id, title, last_modified_time, workspace_uris FROM conversation_summaries')
44
34
  const hasSearch = query("SELECT 1 FROM sqlite_master WHERE name = 'conversations_fts'").length
45
35
  const archived = new Set(hasSearch ? query("SELECT DISTINCT conversation_id FROM conversations_fts WHERE archived IN (1, '1')").map(r => r.conversation_id) : [])
@@ -49,12 +39,7 @@ export function antigravitySummaries(root) {
49
39
  return [row.conversation_id, { title: row.title, workspaces, archived: archived.has(row.conversation_id),
50
40
  updated: Date.parse(row.last_modified_time.replace(' ', 'T')) }]
51
41
  }))
52
- } catch {
53
- // The index is optional on older installations. The transcript and annotations remain usable.
54
- return new Map()
55
- } finally {
56
- db?.close()
57
- }
42
+ }) || new Map()
58
43
  }
59
44
 
60
45
  export function antigravityTitle(root, id) {
@@ -103,8 +88,9 @@ function reviewedFiles(name, args, cwd) {
103
88
  return []
104
89
  }
105
90
 
106
- export async function readAntigravity(records, { file, tool, native, images, assetRoots }) {
91
+ export async function readAntigravity(records, { file, tool, native, images, assetRoots, includeMemory }) {
107
92
  const transcript = createTranscript()
93
+ const metadata = readAntigravityContext(native, records, includeMemory)
108
94
  const logDir = dirname(file)
109
95
  const defaults = [process.cwd(), ...(native?.workspaces || []).filter(dir => existsSync(dir))]
110
96
  const roots = await Promise.all((assetRoots?.length ? assetRoots : defaults).map(dir => realpath(resolve(dir))))
@@ -126,10 +112,16 @@ export async function readAntigravity(records, { file, tool, native, images, ass
126
112
  } else if (type === 'PLANNER_RESPONSE') {
127
113
  pending = []
128
114
  model = record.model || model
129
- const contextTokens = (record.input_tokens || 0) + (record.cache_read_tokens || 0)
130
- tokens += contextTokens + (record.output_tokens || 0)
131
- transcript.reasoning(record.thinking, time)
132
- transcript.assistant(content, time, { cwd, ...(contextTokens && { contextTokens }) })
115
+ const usage = {}
116
+ if (Number.isInteger(record.input_tokens) || Number.isInteger(record.cache_read_tokens)) {
117
+ usage.contextTokens = (record.input_tokens || 0) + (record.cache_read_tokens || 0)
118
+ }
119
+ const estimates = metadata?.breakdowns.get(step)
120
+ if (estimates) usage.contextTokenEstimates = estimates
121
+ if (metadata?.variableWindows) usage.contextWindow = metadata.windows.get(step) || 0
122
+ tokens += (usage.contextTokens || 0) + (record.output_tokens || 0)
123
+ transcript.reasoning(record.thinking, time, usage)
124
+ transcript.assistant(content, time, { cwd, ...usage })
133
125
  for (const [i, call] of (record.tool_calls || []).entries()) {
134
126
  const id = step + '/' + i
135
127
  const args = call.args || {}
@@ -140,8 +132,7 @@ export async function readAntigravity(records, { file, tool, native, images, ass
140
132
  ...(args.CommandLine && { command: args.CommandLine }),
141
133
  ...(args.Path && { path: args.Path }),
142
134
  })
143
- const item = transcript.tool(id, { ...details, name }, time)
144
- if (contextTokens) item.contextTokens = contextTokens
135
+ const item = transcript.tool(id, { ...details, name, ...usage }, time)
145
136
  const files = reviewedFiles(base, args, cwd)
146
137
  if (files.length) item.deliverables = files
147
138
  pending.push(id)
@@ -153,10 +144,17 @@ export async function readAntigravity(records, { file, tool, native, images, ass
153
144
  const done = content.match(/^Completed At:\s*([^\r\n]+)/m)?.[1] || time
154
145
  if (id !== undefined) transcript.result(id, [output, record.error].filter(Boolean).join('\n'), done,
155
146
  images ? await loadMedia(record.media, logDir, roots) : [], cwd)
147
+ } else if (type === 'CHECKPOINT' && record.status === 'DONE' && !record.error) {
148
+ const summary = content.match(/<summary>([\s\S]*?)<\/summary>/i)?.[1]?.trim()
149
+ const text = summary && !includeMemory
150
+ ? summary.replace(/<external_system_instructions>[\s\S]*?(?:<\/external_system_instructions>|$)|========= MEMORY_SUMMARY BEGINS =========[\s\S]*?(?:========= MEMORY_SUMMARY ENDS =========|$)/gi, '[Private context omitted]')
151
+ : summary
152
+ transcript.compact(text ? { text } : {}, time)
156
153
  } else if (type === 'ERROR_MESSAGE') {
157
154
  transcript.assistant(record.error || content, time)
158
155
  }
159
156
  }
160
157
  return transcript.finish({ tool, model, tokens: tokens || undefined,
158
+ contextWindow: metadata?.contextWindow, initialContext: metadata?.initialContext,
161
159
  title: native?.title || (native && antigravityTitle(dirname(native.root), native.id)) })
162
160
  }
package/src/common.mjs CHANGED
@@ -311,9 +311,9 @@ export function createTranscript() {
311
311
  }
312
312
  else add({ type: 'assistant', text, time, key, ...extra })
313
313
  },
314
- reasoning(text, time) {
314
+ reasoning(text, time, extra) {
315
315
  text = String(text ?? '').trim()
316
- if (text) add({ type: 'reasoning', text, time })
316
+ if (text) add({ type: 'reasoning', text, time, ...extra })
317
317
  },
318
318
  tool(id, tool, time) {
319
319
  const item = add({ type: 'tool', ...tool, time })
package/src/i18n.mjs CHANGED
@@ -49,12 +49,13 @@ export const DICTS = {
49
49
  emptyHintEnd: ',体验完整对话与上下文生长',
50
50
  activeContext: '上下文快照',
51
51
  snapInitial: '初始上下文',
52
+ initialUsageMissing: '初始用量未记录',
53
+ usageMissing: '用量未记录',
54
+ notRecorded: '未记录',
55
+ unknownCapacity: '上限未知',
52
56
  snapCurrent: '第 {step} / {total} 步',
53
57
  usedSuffix: '已用',
54
58
  freeSpaceTitle: '剩余窗口 (Free Space)',
55
- autoCompactTriggerTitle: '自动压缩触发线 (80%)',
56
- headroomTitle: '压缩预留空间 (Autocompact Headroom)',
57
- outputReserveTitle: '模型最大输出预留 (Max Output Reserve)',
58
59
  legendSys: '系统提示词',
59
60
  legendSchema: '工具定义',
60
61
  legendUser: '用户消息',
@@ -186,12 +187,13 @@ export const DICTS = {
186
187
  emptyHintEnd: ' to replay the conversation and live context growth',
187
188
  activeContext: 'Context Snapshot',
188
189
  snapInitial: 'Initial Context',
190
+ initialUsageMissing: 'Initial usage not recorded',
191
+ usageMissing: 'Usage not recorded',
192
+ notRecorded: 'Not recorded',
193
+ unknownCapacity: 'Unknown limit',
189
194
  snapCurrent: 'Step {step} / {total}',
190
195
  usedSuffix: 'used',
191
196
  freeSpaceTitle: 'Free Context Space',
192
- autoCompactTriggerTitle: 'Auto-compaction Trigger (80%)',
193
- headroomTitle: 'Autocompact Headroom (12%)',
194
- outputReserveTitle: 'Max Output Reserve (8%)',
195
197
  legendSys: 'System Prompt',
196
198
  legendSchema: 'Tool Schemas',
197
199
  legendUser: 'User Messages',
package/src/index.d.ts CHANGED
@@ -13,6 +13,7 @@ export interface ContextRecord {
13
13
  }
14
14
 
15
15
  export interface InitialContext {
16
+ estimatedTokens?: number
16
17
  sys?: ContextRecord[]
17
18
  schema?: ContextRecord[]
18
19
  mem?: ContextRecord[]
@@ -66,6 +67,8 @@ export interface SessionItem {
66
67
  agent?: string
67
68
  question?: boolean
68
69
  answer?: boolean
70
+ contextWindow?: number
71
+ contextTokenEstimates?: Partial<Record<'sys' | 'schema' | 'mem' | 'skill', number>>
69
72
  contextTokens?: number
70
73
  images?: string[]
71
74
  omittedImages?: number
package/src/index.mjs CHANGED
@@ -67,7 +67,7 @@ export async function importRawSession(files, {
67
67
  const records = detectedTool === 'claude-ai' ? JSON.parse(readFileSync(fileList[0], 'utf8')) : await readJsonl(fileList, window)
68
68
  const nativeRoot = isAntigravity ? native?.workspaces?.[0] : await nativeSessionRoot(fileList[0], detectedTool, records)
69
69
  const sessionData = isAntigravity
70
- ? await readAntigravity(records, { file: fileList[0], tool: detectedTool, native, images, assetRoots })
70
+ ? await readAntigravity(records, { file: fileList[0], tool: detectedTool, native, images, assetRoots, includeMemory })
71
71
  : readers[detectedTool](records, { ...window, conversation, includeMemory })
72
72
  const raw = cutSession(sessionData, window)
73
73
 
@@ -1,7 +1,7 @@
1
1
  import { createTranslator, resolveLang } from './i18n.mjs'
2
2
  import { attachAttachmentReaders } from './attachment-reader.mjs'
3
3
  import { escapeHtml } from './markdown.mjs'
4
- import { buildPlayerData, elapsedClock, renderPlayerWidget, renderTimelineBar, wallClock } from './render.mjs'
4
+ import { buildPlayerData, categoryUsageLabel, contextUsageLabel, elapsedClock, renderPlayerWidget, renderTimelineBar, wallClock } from './render.mjs'
5
5
  import { timeline } from './timeline.mjs'
6
6
 
7
7
  const shorten = (text, length) => (text.length > length ? `${text.slice(0, length)}…` : text)
@@ -467,11 +467,18 @@ export function attachPlayerController(containerEl, playerData, { lang = 'zh', i
467
467
  }
468
468
  }
469
469
  const totEl = asidePane.querySelector('[data-context-tot]')
470
- if (totEl) totEl.textContent = `${(snap.totalTokens / 1000).toFixed(1)}k`
470
+ if (totEl) totEl.textContent = contextUsageLabel(snap, t, stepState.index < 0)
471
471
  const winEl = asidePane.querySelector('[data-context-win]')
472
- if (winEl && snap.windowLabel) winEl.textContent = snap.windowLabel
472
+ if (winEl) winEl.textContent = snap.windowLabel || t('unknownCapacity')
473
+ const unit = asidePane.querySelector('[data-capacity-unit]')
474
+ if (unit) unit.hidden = !snap.windowLabel
473
475
  const pctEl = asidePane.querySelector('[data-context-pct]')
474
- if (pctEl) pctEl.textContent = `${snap.pct}%`
476
+ if (pctEl) {
477
+ pctEl.parentElement.hidden = snap.pct == null
478
+ pctEl.textContent = snap.pct == null ? '' : snap.pct + '%'
479
+ }
480
+ const bar = asidePane.querySelector('[data-stacked-bar]')
481
+ if (bar) bar.hidden = snap.pct == null
475
482
 
476
483
  for (const [key, val] of Object.entries(snap.segments || {})) {
477
484
  const seg = asidePane.querySelector(`[data-seg="${key}"]`)
@@ -480,7 +487,7 @@ export function attachPlayerController(containerEl, playerData, { lang = 'zh', i
480
487
 
481
488
  for (const [key, val] of Object.entries(snap.tokensByKind || {})) {
482
489
  const tokEl = asidePane.querySelector(`[data-pro-tok="${key}"]`)
483
- if (tokEl) tokEl.textContent = `≈${(val / 1000).toFixed(1)}k`
490
+ if (tokEl) tokEl.textContent = categoryUsageLabel(val, t)
484
491
  }
485
492
 
486
493
  const browserBox = asidePane.querySelector('[data-context-browser]')
@@ -579,7 +586,7 @@ export function attachPlayerController(containerEl, playerData, { lang = 'zh', i
579
586
  ? `<span class="session-tl-pop-thumb"><img src="${escapeHtml(frame.img)}" alt=""></span>`
580
587
  : ''
581
588
  const headTitle = ci
582
- ? t('tlCompressTitle', { seq: ci.seq, dropped: ((ci.droppedTokens || 0) / 1000).toFixed(0) })
589
+ ? (ci.droppedTokens == null ? t('compactTitle', { seq: ci.seq }) : t('tlCompressTitle', { seq: ci.seq, dropped: (ci.droppedTokens / 1000).toFixed(0) }))
583
590
  : frame
584
591
  ? `🖼 ${frame.label}`
585
592
  : doc
@@ -587,9 +594,9 @@ export function attachPlayerController(containerEl, playerData, { lang = 'zh', i
587
594
  : s.kind === 'prompt'
588
595
  ? t('tlPromptTitle', { turn: s.turn, summary: shorten(s.summary || '', 20) })
589
596
  : shorten(s.summary || t('tlStepFallback'), 24)
590
- const tokStr = `${((s.contextSnapshot?.totalTokens || 0) / 1000).toFixed(1)}k`
597
+ const tokStr = contextUsageLabel(s.contextSnapshot, t)
591
598
  tlPop.style.left = `clamp(min(130px, 50%), ${pct.toFixed(1)}%, max(50%, 100% - 130px))`
592
- tlPop.innerHTML = `${thumbHtml}<span class="session-tl-pop-meta"><small>${escapeHtml(t('tlStepMeta', { step: idx + 1, time: elapsedClock(s.t) }))}</small><b>${escapeHtml(headTitle)}</b><span>${escapeHtml(t('contextLabel'))} ≈${escapeHtml(tokStr)}</span></span>`
599
+ tlPop.innerHTML = `${thumbHtml}<span class="session-tl-pop-meta"><small>${escapeHtml(t('tlStepMeta', { step: idx + 1, time: elapsedClock(s.t) }))}</small><b>${escapeHtml(headTitle)}</b><span>${escapeHtml(t('contextLabel'))} ${escapeHtml(tokStr)}</span></span>`
593
600
  tlPop.hidden = false
594
601
  }
595
602
 
package/src/render.mjs CHANGED
@@ -243,9 +243,19 @@ function renderBrowserCategories(categories = [], t) {
243
243
  }).join('')
244
244
  }
245
245
 
246
+ export function contextUsageLabel(snapshot, t, opening = false) {
247
+ if (snapshot.totalTokens == null) return t(opening ? 'initialUsageMissing' : 'usageMissing')
248
+ if (snapshot.estimated != null) return (snapshot.estimated ? '≈' : '') + snapshot.totalTokens.toLocaleString(t.lang)
249
+ return (snapshot.totalTokens / 1000).toFixed(1) + 'k'
250
+ }
251
+
252
+ export function categoryUsageLabel(value, t) {
253
+ return value == null ? t('notRecorded') : `≈${(value / 1000).toFixed(1)}k`
254
+ }
255
+
246
256
  function contextSidebar(line, t) {
247
257
  const initial = line.initialSnapshot
248
- const tok = n => `≈${(Number(n || 0) / 1000).toFixed(1)}k`
258
+ const tok = n => categoryUsageLabel(n, t)
249
259
  return `<aside class="session-context-aside" aria-label="${escape(t('activeContext'))}" data-session-aside>
250
260
  <section class="sp-aside-sec" aria-label="${escape(t('activeContext'))}">
251
261
  <div class="sp-sec-head">
@@ -253,22 +263,13 @@ function contextSidebar(line, t) {
253
263
  <span class="sp-sec-snap" data-context-snap>${escape(t('snapInitial'))}</span>
254
264
  </div>
255
265
  <div class="lc-overview-num">
256
- <b data-context-tot>${escape((initial.totalTokens / 1000).toFixed(1))}k</b>
257
- <span>/ <span data-context-win>${escape(initial.windowLabel || '1.0M')}</span> tokens</span>
258
- <span class="lc-overview-pct"><b data-context-pct>${escape(String(initial.pct))}%</b>${escape(t('usedSuffix'))}</span>
266
+ <b data-context-tot>${escape(contextUsageLabel(initial, t, true))}</b>
267
+ <span>/ <span data-context-win>${escape(initial.windowLabel || t('unknownCapacity'))}</span><span data-capacity-unit${initial.windowLabel ? '' : ' hidden'}> tokens</span></span>
268
+ <span class="lc-overview-pct"${initial.pct == null ? ' hidden' : ''}><b data-context-pct>${initial.pct == null ? '' : initial.pct + '%'}</b>${escape(t('usedSuffix'))}</span>
259
269
  </div>
260
- <div class="lc-stacked" data-stacked-bar>
261
- <div class="lc-stacked-seg is-sys" data-seg="sys" data-cat-key="sys" style="width:${initial.segments.sys}%"></div>
262
- <div class="lc-stacked-seg is-schema" data-seg="schema" data-cat-key="schema" style="width:${initial.segments.schema}%"></div>
263
- <div class="lc-stacked-seg is-user" data-seg="user" data-cat-key="user" style="width:${initial.segments.user}%"></div>
264
- <div class="lc-stacked-seg is-mem" data-seg="mem" data-cat-key="mem" style="width:${initial.segments.mem}%"></div>
265
- <div class="lc-stacked-seg is-skill" data-seg="skill" data-cat-key="skill" style="width:${initial.segments.skill}%"></div>
266
- <div class="lc-stacked-seg is-msg" data-seg="msg" data-cat-key="msg" style="width:${initial.segments.msg}%"></div>
267
- <div class="lc-stacked-seg is-tool" data-seg="tool" data-cat-key="tool" style="width:${initial.segments.tool}%"></div>
270
+ <div class="lc-stacked" data-stacked-bar${initial.pct == null ? ' hidden' : ''}>
271
+ ${Object.entries(initial.segments).map(([key, width]) => `<div class="lc-stacked-seg is-${escape(key)}" data-seg="${escape(key)}"${key === 'used' ? '' : ` data-cat-key="${escape(key)}"`} style="width:${Number(width)}%"></div>`).join('')}
268
272
  <div class="lc-stacked-free" title="${escape(t('freeSpaceTitle'))}"></div>
269
- <div class="lc-trigger" style="left:80%" title="${escape(t('autoCompactTriggerTitle'))}"></div>
270
- <div class="lc-reserve lc-reserve-headroom" style="left:80%;width:12%" title="${escape(t('headroomTitle'))}"></div>
271
- <div class="lc-reserve lc-reserve-output" style="left:92%;width:8%" title="${escape(t('outputReserveTitle'))}"></div>
272
273
  </div>
273
274
  <div class="lc-legend" data-lc-legend>
274
275
  <span class="lc-chip" data-cat-key="sys"><i class="session-cat-dot is-sys"></i><span class="lc-chip-label">${escape(t('legendSys'))}</span><span class="lc-chip-nums" data-pro-tok="sys">${escape(tok(initial.tokensByKind.sys))}</span></span>
@@ -419,9 +420,10 @@ function renderLog(session, line, { t, baseUrl = '' }) {
419
420
  const postK = ci.postTokens ? `${(ci.postTokens / 1000).toFixed(1)}k` : ''
420
421
  const dropK = ci.droppedTokens ? `${(ci.droppedTokens / 1000).toFixed(1)}k` : ''
421
422
  const tpl = ci.docId && ci.content ? `<template data-doc-html="${escape(ci.docId)}">${render(ci.content)}</template>` : ''
422
- const badgeText = ci.trigger === 'manual' ? t('compactManual') : ci.trigger === 'handoff' ? t('compactHandoff') : t('compactAuto')
423
+ const badgeText = !ci.trigger ? '' : ci.trigger === 'manual' ? t('compactManual') : ci.trigger === 'handoff' ? t('compactHandoff') : t('compactAuto')
424
+ const eventTime = item.time ? `<time datetime="${escape(item.time)}">${escape(wallClock(item.time, 0, true))}</time>` : ''
423
425
  const freedText = dropK ? t('compactFreed', { tokens: dropK }) : ''
424
- entries.push(`${stamp(item.t, stepIndex - 1)}<li class="session-entry session-compact" data-step="${stepIndex - 1}" data-echo-cat="tool" data-kind="compact" data-t="${item.t}"><div class="session-compact-card"><span class="session-compact-icon" aria-hidden="true">🗜</span><div class="session-compact-main"><div class="session-compact-head"><b>${escape(t('compactTitle', { seq: ci.seq || 1 }))}</b><span class="session-compact-tag">${escape(badgeText)}</span>${preK && postK ? `<span class="session-compact-meter">${escape(preK)} → ${escape(postK)}${escape(freedText)}</span>` : ''}</div><p class="session-compact-desc">${escape(t('compactDesc', { count: ci.archivedTools || 0 }))}</p></div>${ci.docId ? `<button type="button" class="session-compact-btn" data-doc-open="${escape(ci.docId)}" data-doc-title="${escape(ci.title || t('compactModalTitle'))}">${escape(t('compactViewBtn'))}</button>${tpl}` : ''}</div></li>`)
426
+ entries.push(`${stamp(item.t, stepIndex - 1)}<li class="session-entry session-compact" data-step="${stepIndex - 1}" data-echo-cat="tool" data-kind="compact" data-t="${item.t}"><div class="session-compact-card"><span class="session-compact-icon" aria-hidden="true">🗜</span><div class="session-compact-main"><div class="session-compact-head"><b>${escape(t('compactTitle', { seq: ci.seq || 1 }))}</b>${eventTime}${badgeText ? `<span class="session-compact-tag">${escape(badgeText)}</span>` : ''}${preK && postK ? `<span class="session-compact-meter">${escape(preK)} → ${escape(postK)}${escape(freedText)}</span>` : ''}</div>${ci.archivedTools != null ? `<p class="session-compact-desc">${escape(t('compactDesc', { count: ci.archivedTools }))}</p>` : ''}</div>${ci.docId ? `<button type="button" class="session-compact-btn" data-doc-open="${escape(ci.docId)}" data-doc-title="${escape(ci.title || t('compactModalTitle'))}">${escape(t('compactViewBtn'))}</button>${tpl}` : ''}</div></li>`)
425
427
  } else {
426
428
  entries.push(`${stamp(item.t, stepIndex - 1)}<li class="session-entry session-ai" data-step="${stepIndex - 1}" data-echo-cat="msg" data-kind="reply" data-t="${item.t}"><div class="session-bubble">${item.question ? `<span class="session-who">${escape(t('asksYou', { tool }))}</span>` : ''}<div class="session-ai-body">${render(item.text)}</div>${renderStepArtifacts(stepMeta, { renderMd: render, t, baseUrl })}</div></li>`)
427
429
  }
@@ -57,7 +57,8 @@ export async function pickSession({ lang, input = process.stdin, output = proces
57
57
  const selected = start + i === view.selected
58
58
  const source = groups[tab] === 'antigravity' ? row.toolLabel.replace(/^Antigravity /, '') : row.toolLabel
59
59
  const archive = row.archived ? (zh ? ' [已归档]' : ' [Archived]') : ''
60
- const line = fit((selected ? ' ❯ ' : ' ') + (i + 1) + '. ' + row.timeLabel + ' [' + source + ']' + archive + ' ' + row.preview, cols)
60
+ const sizeLabel = row.sizeKB == null ? '' : ' ' + row.sizeKB + ' KB'
61
+ const line = fit((selected ? ' ❯ ' : ' ') + (i + 1) + '. ' + row.timeLabel + ' [' + source + ']' + archive + ' ' + row.preview, cols - sizeLabel.length) + sizeLabel
61
62
  lines.push(selected ? '\x1b[1;36m' + line + '\x1b[0m' : line)
62
63
  }
63
64
  if (!page.length) lines.push(view.done ? (zh ? '没有匹配的会话' : 'No matching sessions') : (zh ? '正在读取会话…' : 'Loading sessions…'))