@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.
package/README.md CHANGED
@@ -93,6 +93,8 @@ A verified file matches the SHA-256 checksum recorded in the log. An export-time
93
93
 
94
94
  The counts show how the context changes during a session. Encore uses recorded counts where available and estimates missing step or category counts from content length.
95
95
 
96
+ For native Antigravity sessions, Encore reads the recorded system instructions and tool definitions from the first model request. The opening estimate (`≈`) counts system-side groups and excludes the first user message. Missing usage and window limits are labeled separately. Completed checkpoints appear on the timeline at their recorded times.
97
+
96
98
  </details>
97
99
 
98
100
  [Contributing](./AGENTS.md) · [Glossary](./GLOSSARY.md) · [npm](https://www.npmjs.com/package/@niracler/encore) · [MIT](./LICENSE)
package/README.zh-CN.md CHANGED
@@ -93,6 +93,8 @@ npx @niracler/encore@latest play ./my-replay
93
93
 
94
94
  这些数值用于观察会话中的上下文变化。日志提供统计时使用记录值,缺少的步骤或分类明细按内容长度估算。
95
95
 
96
+ 对于 Antigravity 本机会话,Encore 从首次模型请求的记录中提取已加载的系统提示词和工具定义。初始用量取自系统侧分类的估算值(标为 `≈`),首条用户消息单独计入对应步骤。日志缺少开场统计时显示「初始用量未记录」,容量缺失时显示「上限未知」。时间线按日志中的事件时间标记压缩检查点。
97
+
96
98
  </details>
97
99
 
98
100
  [开发与贡献](./AGENTS.md) · [术语表](./GLOSSARY.md) · [npm](https://www.npmjs.com/package/@niracler/encore) · [MIT](./LICENSE)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@niracler/encore",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "A curtain call for your AI agent runs. Replay Codex, Claude Code, Claude.ai, WorkBuddy, and Antigravity sessions as an interactive web stage with a live context-window inspector.",
5
5
  "type": "module",
6
6
  "types": "./src/index.d.ts",
@@ -57,6 +57,7 @@
57
57
  "dependencies": {
58
58
  "@hyzyla/pdfium": "2.1.13",
59
59
  "node-xlsx": "0.25.0",
60
+ "protobufjs": "8.8.1",
60
61
  "sharp": "^0.35.5"
61
62
  },
62
63
  "devDependencies": {
@@ -477,9 +477,11 @@ html.js-session .session-log:not(.is-staged) > * {
477
477
  .lc-overview-pct b { font-size: 16px; font-weight: 600; color: #111827; margin-right: 3px; letter-spacing: -.01em; }
478
478
 
479
479
  .lc-stacked { display: flex; width: 100%; height: 12px; border-radius: 4px; overflow: hidden; background: #e5e7eb; position: relative; }
480
+ .lc-stacked[hidden] { display: none; }
480
481
  .lc-stacked > div { height: 100%; }
481
482
  .lc-stacked-seg { cursor: pointer; }
482
483
  .session-app.is-ready .lc-stacked-seg { transition: width .42s cubic-bezier(.22, 1, .36, 1), filter .2s ease, opacity .2s ease; }
484
+ .lc-stacked-seg.is-used { background: var(--dsw-alias-label-secondary); cursor: default; }
483
485
  .lc-stacked-seg.is-sys, .session-cat-dot.is-sys { background: var(--color-indigo-500); }
484
486
  .lc-stacked-seg.is-schema, .session-cat-dot.is-schema { background: var(--color-amber-500); }
485
487
  .lc-stacked-seg.is-user, .session-cat-dot.is-user { background: var(--color-green-500); }
@@ -491,11 +493,6 @@ html.js-session .session-log:not(.is-staged) > * {
491
493
  .lc-stacked-seg-on { filter: brightness(1.16); }
492
494
  .lc-stacked-dim .lc-stacked-seg { opacity: 0.32; }
493
495
  .lc-stacked-dim .lc-stacked-seg-on { opacity: 1; }
494
- .lc-reserve { position: absolute; top: 0; bottom: 0; z-index: 1; pointer-events: auto; cursor: help; }
495
- .lc-reserve-headroom { background: repeating-linear-gradient(45deg, color-mix(in srgb, var(--dsw-alias-state-warn-primary) 28%, transparent) 0 5px, transparent 5px 10px); }
496
- .lc-reserve-output { background: repeating-linear-gradient(45deg, color-mix(in srgb, var(--dsw-alias-state-business-primary) 28%, transparent) 0 5px, transparent 5px 10px); }
497
- .lc-trigger { position: absolute; top: 0; bottom: 0; width: 9px; transform: translateX(-50%); z-index: 2; pointer-events: auto; cursor: help; }
498
- .lc-trigger::after { content: ''; position: absolute; top: 0; bottom: 0; left: 50%; width: 2px; margin-left: -1px; background: var(--dsw-alias-state-warn-primary); }
499
496
 
500
497
  .lc-legend { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 4px 12px; margin-top: 12px; }
501
498
  .lc-chip { display: flex; align-items: center; gap: 6px; min-width: 0; color: var(--dsw-alias-label-primary); padding: 2px 4px; margin: 0 -4px; border-radius: 5px; font-size: 11.5px; cursor: pointer; transition: background-color .15s ease; }
@@ -52,12 +52,13 @@ const DICTS = {
52
52
  emptyHintEnd: ',体验完整对话与上下文生长',
53
53
  activeContext: '上下文快照',
54
54
  snapInitial: '初始上下文',
55
+ initialUsageMissing: '初始用量未记录',
56
+ usageMissing: '用量未记录',
57
+ notRecorded: '未记录',
58
+ unknownCapacity: '上限未知',
55
59
  snapCurrent: '第 {step} / {total} 步',
56
60
  usedSuffix: '已用',
57
61
  freeSpaceTitle: '剩余窗口 (Free Space)',
58
- autoCompactTriggerTitle: '自动压缩触发线 (80%)',
59
- headroomTitle: '压缩预留空间 (Autocompact Headroom)',
60
- outputReserveTitle: '模型最大输出预留 (Max Output Reserve)',
61
62
  legendSys: '系统提示词',
62
63
  legendSchema: '工具定义',
63
64
  legendUser: '用户消息',
@@ -189,12 +190,13 @@ const DICTS = {
189
190
  emptyHintEnd: ' to replay the conversation and live context growth',
190
191
  activeContext: 'Context Snapshot',
191
192
  snapInitial: 'Initial Context',
193
+ initialUsageMissing: 'Initial usage not recorded',
194
+ usageMissing: 'Usage not recorded',
195
+ notRecorded: 'Not recorded',
196
+ unknownCapacity: 'Unknown limit',
192
197
  snapCurrent: 'Step {step} / {total}',
193
198
  usedSuffix: 'used',
194
199
  freeSpaceTitle: 'Free Context Space',
195
- autoCompactTriggerTitle: 'Auto-compaction Trigger (80%)',
196
- headroomTitle: 'Autocompact Headroom (12%)',
197
- outputReserveTitle: 'Max Output Reserve (8%)',
198
200
  legendSys: 'System Prompt',
199
201
  legendSchema: 'Tool Schemas',
200
202
  legendUser: 'User Messages',
@@ -501,6 +503,7 @@ function resolveWindowCapacity(tool = 'codex', model = '', contextWindow = 0) {
501
503
  return { tokens: contextWindow, label }
502
504
  }
503
505
  const t = String(tool || '').toLowerCase()
506
+ if (t.startsWith('antigravity')) return { tokens: null, label: null }
504
507
  const m = String(model || '').toLowerCase()
505
508
  if (
506
509
  t.startsWith('claude') ||
@@ -933,7 +936,7 @@ function assignFramesToGroups(rawGroups, frames = [], t) {
933
936
  }
934
937
 
935
938
  function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames = [], sessionStart = '', sessionMeta = {}, t) {
936
- const windowSpec = resolveWindowCapacity(sessionTool, sessionModel, sessionMeta.contextWindow)
939
+ let windowSpec = resolveWindowCapacity(sessionTool, sessionModel, sessionMeta.contextWindow)
937
940
  const initCtx = sessionMeta.initialContext || {}
938
941
  const rawGroups = []
939
942
  let work = []
@@ -964,14 +967,14 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
964
967
  id: rec.id,
965
968
  tag: rec.tag || '',
966
969
  title: rec.title,
967
- meta: rec.meta,
970
+ meta: observedOnly && rec.stepIndex >= 0 ? undefined : rec.meta,
968
971
  payload: rec.payload,
969
972
  ...(rec.images?.length ? { images: rec.images } : {}),
970
973
  }
971
974
  return entry
972
975
  }
973
976
 
974
- // Antigravity transcripts contain observed steps, with no initial prompt or tool inventory.
977
+ // Antigravity metadata may contain only part of the mounted context.
975
978
  const observedOnly = sessionTool.startsWith('antigravity')
976
979
  function initialRecords(key, defaults) {
977
980
  const records = initCtx[key] || []
@@ -989,7 +992,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
989
992
  const msgRecords = []
990
993
  const memRecords = initialRecords('mem', defaultInjectedContext)
991
994
 
992
- const sumTokEst = list => list.reduce((acc, r) => acc + (r.tokEst || 600), 0)
995
+ const sumTokEst = list => list.reduce((acc, r) => acc + (r.tokEst ?? (observedOnly ? 0 : 600)), 0)
993
996
  const sysTokens = sumTokEst(sysRecords)
994
997
  let schemaTokens = sumTokEst(schemaRecords)
995
998
  let userTokens = 0
@@ -1019,7 +1022,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1019
1022
  let dUser = userTokens
1020
1023
  let dMsg = msgTokens
1021
1024
  let dTool = toolTokens
1022
- if (lastRealTotal > 0) {
1025
+ if (lastRealTotal > 0 && !observedOnly) {
1023
1026
  const target = lastRealTotal + uncalibratedDelta
1024
1027
  const fixed = dSys + dSchema + dMem + dSkill
1025
1028
  const dyn = dUser + dMsg + dTool
@@ -1042,6 +1045,11 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1042
1045
  return { sys: dSys, schema: dSchema, user: dUser, mem: dMem, skill: dSkill, msg: dMsg, tool: dTool }
1043
1046
  }
1044
1047
 
1048
+ function reportedBuckets(disp, recorded) {
1049
+ if (!observedOnly) return disp
1050
+ return Object.fromEntries(Object.keys(disp).map(key => [key, recorded?.[key] ?? null]))
1051
+ }
1052
+
1045
1053
  const assembleCategoryList = (stepIdx, countsBefore, toksBefore, disp) => {
1046
1054
  const curTotal = disp.sys + disp.schema + disp.user + disp.mem + disp.msg + disp.tool + disp.skill
1047
1055
  const kindPct = value => Math.round((value / Math.max(1, curTotal)) * 100)
@@ -1066,10 +1074,10 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1066
1074
  color,
1067
1075
  itemCount: records.length,
1068
1076
  count: t('itemCount', { n: records.length }),
1069
- tok: `≈${(curTok / 1000).toFixed(1)}k`,
1070
- pct: `${kindPct(curTok)}%`,
1077
+ tok: curTok == null ? t('notRecorded') : `≈${(curTok / 1000).toFixed(1)}k`,
1078
+ pct: observedOnly || curTok == null ? '' : `${kindPct(curTok)}%`,
1071
1079
  delta: stepIdx >= 0 ? fmtCountDelta(records.length, prevCount) : '',
1072
- tokDelta: stepIdx >= 0 ? fmtTokDelta(curTok, prevTok) : '',
1080
+ tokDelta: stepIdx >= 0 && !observedOnly ? fmtTokDelta(curTok, prevTok) : '',
1073
1081
  itemIds,
1074
1082
  newIds,
1075
1083
  items: itemIds.map(rid => ({ ...contextRecords[rid], isNew: newSet.has(rid) })),
@@ -1088,9 +1096,15 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1088
1096
 
1089
1097
  let prevDisp = computeDisplayBuckets()
1090
1098
  const initTotal = prevDisp.sys + prevDisp.schema + prevDisp.user + prevDisp.mem + prevDisp.skill + prevDisp.msg + prevDisp.tool
1091
- const initCap = Math.max(windowSpec.tokens, Math.ceil(initTotal * 1.25))
1092
- const initCapPct = val => (val <= 0 ? 0 : Number((Math.max(0.4, (val / initCap) * 100)).toFixed(2)))
1099
+ let observedUsage = initCtx.estimatedTokens ?? null
1100
+ const openingTokens = observedOnly ? observedUsage : initTotal
1101
+ const initCap = observedOnly ? windowSpec.tokens : Math.max(windowSpec.tokens, Math.ceil(initTotal * 1.25))
1102
+ const initCapPct = val => (!initCap || val <= 0 ? 0 : Number((Math.max(0.4, (val / initCap) * 100)).toFixed(2)))
1093
1103
  const initKindPct = val => Math.round((val / Math.max(1, initTotal)) * 100)
1104
+ const openingByKind = Object.fromEntries(Object.entries(initCtx)
1105
+ .filter(([, records]) => Array.isArray(records) && records.some(record => record.tokEst != null))
1106
+ .map(([key, records]) => [key, sumTokEst(records)]))
1107
+ const initialBuckets = reportedBuckets(prevDisp, openingByKind)
1094
1108
  const zeroCounts = {
1095
1109
  sys: sysRecords.length,
1096
1110
  schema: schemaRecords.length,
@@ -1101,12 +1115,13 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1101
1115
  tool: 0,
1102
1116
  }
1103
1117
  const initialSnapshot = {
1104
- pct: Number(Math.min(99, (initTotal / initCap) * 100).toFixed(1)),
1118
+ pct: initCap && openingTokens != null ? Number(((openingTokens / initCap) * 100).toFixed(1)) : null,
1105
1119
  windowTokens: windowSpec.tokens,
1106
1120
  windowLabel: windowSpec.label,
1107
- totalTokens: initTotal,
1121
+ totalTokens: openingTokens,
1122
+ ...(observedOnly && openingTokens != null && { estimated: true }),
1108
1123
  deltaTokens: 0,
1109
- segments: {
1124
+ segments: observedOnly ? { used: initCap && openingTokens != null ? Math.min(openingTokens / initCap * 100, 100) : 0 } : {
1110
1125
  sys: initCapPct(prevDisp.sys),
1111
1126
  schema: initCapPct(prevDisp.schema),
1112
1127
  user: 0,
@@ -1115,7 +1130,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1115
1130
  msg: 0,
1116
1131
  tool: 0,
1117
1132
  },
1118
- pctByKind: {
1133
+ pctByKind: observedOnly ? {} : {
1119
1134
  sys: initKindPct(prevDisp.sys),
1120
1135
  schema: initKindPct(prevDisp.schema),
1121
1136
  user: 0,
@@ -1124,8 +1139,8 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1124
1139
  msg: 0,
1125
1140
  tool: 0,
1126
1141
  },
1127
- tokensByKind: { ...prevDisp },
1128
- categories: assembleCategoryList(-1, zeroCounts, prevDisp, prevDisp),
1142
+ tokensByKind: initialBuckets,
1143
+ categories: assembleCategoryList(-1, zeroCounts, prevDisp, initialBuckets),
1129
1144
  }
1130
1145
 
1131
1146
  const steps = rawGroups.map((group, index) => {
@@ -1181,7 +1196,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1181
1196
  payload: String(first.text || ''),
1182
1197
  ...(first.images?.length ? { images: first.images } : {}),
1183
1198
  }))
1184
- for (const skill of extractSkillNames(first, knownSkillNames)) {
1199
+ for (const skill of observedOnly ? [] : extractSkillNames(first, knownSkillNames)) {
1185
1200
  if (!allSkills.includes(skill)) {
1186
1201
  allSkills.push(skill)
1187
1202
  const skTok = 1800
@@ -1209,59 +1224,68 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1209
1224
  } else if (group.groupType === 'compact') {
1210
1225
  compactSeq++
1211
1226
  const cItem = first
1212
- const preTokens = cItem.preTokens || prevTotal
1213
- const archivedTools = toolRecords.length
1214
- const postTokens = cItem.postTokens || Math.min(preTokens, Math.max(24000, Math.round(preTokens * 0.28)))
1215
- const droppedTokens = cItem.droppedTokens || Math.max(0, preTokens - postTokens)
1216
- const summaryText = String(cItem.text || cItem.summary || 'Context Compaction Summary').trim()
1217
- const sumTok = Math.max(1200, Math.round(summaryText.length * 0.35))
1218
- const docId = `compact-doc-${index}`
1219
- const recId = `compact-summary-${compactSeq}`
1220
-
1221
- toolRecords = []
1222
- toolTokens = 0
1223
- userTokens = Math.round(userTokens * 0.35)
1224
- msgTokens = Math.round(msgTokens * 0.25)
1225
- memTokens += sumTok
1226
- lastRealTotal = postTokens
1227
- uncalibratedDelta = 0
1228
- const rawFixed = sysTokens + schemaTokens + memTokens + skillTokens
1229
- if (postTokens > 0 && rawFixed > postTokens * 0.85) {
1230
- mountScale = (postTokens * 0.72) / rawFixed
1231
- }
1232
-
1233
- memRecords.push(registerRecord({
1234
- id: recId,
1235
- stepIndex: index,
1236
- tokEst: sumTok,
1237
- tag: 'Compact',
1238
- title: `${t('compactTitle', { seq: cItem.seq || compactSeq })} (${(preTokens / 1000).toFixed(1)}k → ${(postTokens / 1000).toFixed(1)}k)`,
1239
- meta: `-${(droppedTokens / 1000).toFixed(1)}k tok · ${stepTime}s`,
1240
- payload: summaryText,
1241
- }))
1227
+ if (observedOnly) {
1228
+ compactInfo = { seq: compactSeq, title: t('compactTitle', { seq: compactSeq }) }
1229
+ if (cItem.text) {
1230
+ compactInfo.content = cItem.text
1231
+ compactInfo.docId = `compact-doc-${index}`
1232
+ memRecords.push(registerRecord({ id: `compact-summary-${compactSeq}`, tag: 'Checkpoint',
1233
+ title: compactInfo.title, payload: cItem.text, stepIndex: index }))
1234
+ }
1235
+ } else {
1236
+ const preTokens = cItem.preTokens || prevTotal
1237
+ const archivedTools = toolRecords.length
1238
+ const postTokens = cItem.postTokens || Math.min(preTokens, Math.max(24000, Math.round(preTokens * 0.28)))
1239
+ const droppedTokens = cItem.droppedTokens || Math.max(0, preTokens - postTokens)
1240
+ const summaryText = String(cItem.text || cItem.summary || 'Context Compaction Summary').trim()
1241
+ const sumTok = Math.max(1200, Math.round(summaryText.length * 0.35))
1242
+ const docId = `compact-doc-${index}`
1243
+ const recId = `compact-summary-${compactSeq}`
1244
+
1245
+ toolRecords = []
1246
+ toolTokens = 0
1247
+ userTokens = Math.round(userTokens * 0.35)
1248
+ msgTokens = Math.round(msgTokens * 0.25)
1249
+ memTokens += sumTok
1250
+ lastRealTotal = postTokens
1251
+ uncalibratedDelta = 0
1252
+ const rawFixed = sysTokens + schemaTokens + memTokens + skillTokens
1253
+ if (postTokens > 0 && rawFixed > postTokens * 0.85) {
1254
+ mountScale = (postTokens * 0.72) / rawFixed
1255
+ }
1242
1256
 
1243
- compactInfo = {
1244
- seq: cItem.seq || compactSeq,
1245
- trigger: cItem.trigger || 'auto',
1246
- preTokens,
1247
- postTokens,
1248
- droppedTokens,
1249
- archivedTools,
1250
- docId,
1251
- recId,
1252
- title: cItem.summary || t('compactTitle', { seq: cItem.seq || compactSeq }),
1253
- content: summaryText,
1254
- }
1257
+ memRecords.push(registerRecord({
1258
+ id: recId,
1259
+ stepIndex: index,
1260
+ tokEst: sumTok,
1261
+ tag: 'Compact',
1262
+ title: `${t('compactTitle', { seq: cItem.seq || compactSeq })} (${(preTokens / 1000).toFixed(1)}k → ${(postTokens / 1000).toFixed(1)}k)`,
1263
+ meta: `-${(droppedTokens / 1000).toFixed(1)}k tok · ${stepTime}s`,
1264
+ payload: summaryText,
1265
+ }))
1255
1266
 
1267
+ compactInfo = {
1268
+ seq: cItem.seq || compactSeq,
1269
+ trigger: cItem.trigger || 'auto',
1270
+ preTokens,
1271
+ postTokens,
1272
+ droppedTokens,
1273
+ archivedTools,
1274
+ docId,
1275
+ recId,
1276
+ title: cItem.summary || t('compactTitle', { seq: cItem.seq || compactSeq }),
1277
+ content: summaryText,
1278
+ }
1279
+ inBrief = `${(preTokens / 1000).toFixed(1)}k → ${(postTokens / 1000).toFixed(1)}k`
1280
+ responseBrief = t('archivedTools', { n: archivedTools, tokens: (droppedTokens / 1000).toFixed(1) })
1281
+ }
1256
1282
  kind = 'compact'
1257
1283
  primaryCat = 'mem'
1258
1284
  speedLabel = '0.8×'
1259
1285
  dwellMs = 2100
1260
1286
  spotlight = 'context-compact'
1261
1287
  detailTitle = t('compactTitle', { seq: compactInfo.seq })
1262
- detailSnippet = summaryText.slice(0, 260)
1263
- inBrief = `${(preTokens / 1000).toFixed(1)}k → ${(postTokens / 1000).toFixed(1)}k`
1264
- responseBrief = t('archivedTools', { n: archivedTools, tokens: (droppedTokens / 1000).toFixed(1) })
1288
+ detailSnippet = (compactInfo.content || '').slice(0, 260)
1265
1289
  } else if (group.groupType === 'assistant') {
1266
1290
  msgSeq++
1267
1291
  const cleanReply = (first.text || '').replace(/\s+/g, ' ').trim()
@@ -1302,7 +1326,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1302
1326
  allTools.push(...extracted.tools)
1303
1327
  allChanges.push(...extracted.changes)
1304
1328
 
1305
- for (const memName of extracted.memories) {
1329
+ for (const memName of observedOnly ? [] : extracted.memories) {
1306
1330
  if (!allMemories.includes(memName)) {
1307
1331
  allMemories.push(memName)
1308
1332
  const memTok = 1100
@@ -1339,14 +1363,14 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1339
1363
 
1340
1364
  const rawMontage = []
1341
1365
  for (const item of toolItems) {
1342
- const dynSchema = resolveDynamicSchema(item, index, schemaIdSet)
1366
+ const dynSchema = !observedOnly && resolveDynamicSchema(item, index, schemaIdSet)
1343
1367
  if (dynSchema) {
1344
1368
  schemaIdSet.add(dynSchema.id)
1345
1369
  schemaTokens += dynSchema.tokEst
1346
1370
  stepEstimatedDelta += dynSchema.tokEst
1347
1371
  schemaRecords.push(registerRecord(dynSchema))
1348
1372
  }
1349
- for (const skill of extractSkillNames(item, knownSkillNames)) {
1373
+ for (const skill of observedOnly ? [] : extractSkillNames(item, knownSkillNames)) {
1350
1374
  if (!allSkills.includes(skill)) {
1351
1375
  allSkills.push(skill)
1352
1376
  const skTok = 1800
@@ -1481,13 +1505,23 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1481
1505
 
1482
1506
  const disp = computeDisplayBuckets()
1483
1507
  prevDisp = disp
1484
- const totalTokens = disp.sys + disp.schema + disp.user + disp.mem + disp.msg + disp.tool + disp.skill
1485
- const deltaTokens = totalTokens - prevTotal
1486
- const capacity = Math.max(windowSpec.tokens, Math.ceil(totalTokens * 1.25))
1487
- const pct = Number(Math.min(99, (totalTokens / capacity) * 100).toFixed(1))
1488
- const capPct = value => (value <= 0 ? 0 : Number((Math.max(0.4, (value / capacity) * 100)).toFixed(2)))
1489
- const kindPct = value => Math.round((value / Math.max(1, totalTokens)) * 100)
1490
- const categories = assembleCategoryList(index, prevCounts, prevToks, disp)
1508
+ const bucketTotal = disp.sys + disp.schema + disp.user + disp.mem + disp.msg + disp.tool + disp.skill
1509
+ const previousUsage = observedOnly ? observedUsage : prevTotal
1510
+ const request = observedOnly && group.items.findLast(item => item.contextTokens != null || item.contextTokenEstimates || item.contextWindow != null)
1511
+ const sample = request?.contextTokens
1512
+ if (observedOnly) {
1513
+ const limit = group.items.findLast(item => item.contextWindow != null)?.contextWindow
1514
+ if (limit != null) windowSpec = resolveWindowCapacity(sessionTool, sessionModel, limit)
1515
+ observedUsage = sample ?? null
1516
+ }
1517
+ const totalTokens = observedOnly ? observedUsage : bucketTotal
1518
+ const deltaTokens = totalTokens == null || previousUsage == null ? null : totalTokens - previousUsage
1519
+ const capacity = observedOnly ? windowSpec.tokens : Math.max(windowSpec.tokens, Math.ceil(totalTokens * 1.25))
1520
+ const pct = capacity && totalTokens != null ? Number(((totalTokens / capacity) * 100).toFixed(1)) : null
1521
+ const capPct = value => (!capacity || value <= 0 ? 0 : Number((Math.max(0.4, (value / capacity) * 100)).toFixed(2)))
1522
+ const kindPct = value => Math.round((value / Math.max(1, bucketTotal)) * 100)
1523
+ const buckets = reportedBuckets(disp, request?.contextTokenEstimates)
1524
+ const categories = assembleCategoryList(index, prevCounts, prevToks, buckets)
1491
1525
 
1492
1526
  return {
1493
1527
  index,
@@ -1513,8 +1547,9 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1513
1547
  windowTokens: windowSpec.tokens,
1514
1548
  windowLabel: windowSpec.label,
1515
1549
  totalTokens,
1550
+ ...(observedOnly && totalTokens != null && { estimated: false }),
1516
1551
  deltaTokens,
1517
- segments: {
1552
+ segments: observedOnly ? { used: Math.min(pct ?? 0, 100) } : {
1518
1553
  sys: capPct(disp.sys),
1519
1554
  schema: capPct(disp.schema),
1520
1555
  user: capPct(disp.user),
@@ -1523,7 +1558,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1523
1558
  skill: capPct(disp.skill),
1524
1559
  mem: capPct(disp.mem),
1525
1560
  },
1526
- pctByKind: {
1561
+ pctByKind: observedOnly ? {} : {
1527
1562
  sys: kindPct(disp.sys),
1528
1563
  schema: kindPct(disp.schema),
1529
1564
  user: kindPct(disp.user),
@@ -1532,15 +1567,7 @@ function buildSteps(items, end, sessionTool = 'codex', sessionModel = '', frames
1532
1567
  skill: kindPct(disp.skill),
1533
1568
  mem: kindPct(disp.mem),
1534
1569
  },
1535
- tokensByKind: {
1536
- sys: disp.sys,
1537
- schema: disp.schema,
1538
- user: disp.user,
1539
- msg: disp.msg,
1540
- tool: disp.tool,
1541
- skill: disp.skill,
1542
- mem: disp.mem,
1543
- },
1570
+ tokensByKind: buckets,
1544
1571
  chips: {
1545
1572
  tools: uniqueRecent(allTools, 6),
1546
1573
  skills: uniqueRecent(allSkills, 4),
@@ -2074,9 +2101,19 @@ function renderBrowserCategories(categories = [], t) {
2074
2101
  }).join('')
2075
2102
  }
2076
2103
 
2104
+ function contextUsageLabel(snapshot, t, opening = false) {
2105
+ if (snapshot.totalTokens == null) return t(opening ? 'initialUsageMissing' : 'usageMissing')
2106
+ if (snapshot.estimated != null) return (snapshot.estimated ? '≈' : '') + snapshot.totalTokens.toLocaleString(t.lang)
2107
+ return (snapshot.totalTokens / 1000).toFixed(1) + 'k'
2108
+ }
2109
+
2110
+ function categoryUsageLabel(value, t) {
2111
+ return value == null ? t('notRecorded') : `≈${(value / 1000).toFixed(1)}k`
2112
+ }
2113
+
2077
2114
  function contextSidebar(line, t) {
2078
2115
  const initial = line.initialSnapshot
2079
- const tok = n => `≈${(Number(n || 0) / 1000).toFixed(1)}k`
2116
+ const tok = n => categoryUsageLabel(n, t)
2080
2117
  return `<aside class="session-context-aside" aria-label="${escape(t('activeContext'))}" data-session-aside>
2081
2118
  <section class="sp-aside-sec" aria-label="${escape(t('activeContext'))}">
2082
2119
  <div class="sp-sec-head">
@@ -2084,22 +2121,13 @@ function contextSidebar(line, t) {
2084
2121
  <span class="sp-sec-snap" data-context-snap>${escape(t('snapInitial'))}</span>
2085
2122
  </div>
2086
2123
  <div class="lc-overview-num">
2087
- <b data-context-tot>${escape((initial.totalTokens / 1000).toFixed(1))}k</b>
2088
- <span>/ <span data-context-win>${escape(initial.windowLabel || '1.0M')}</span> tokens</span>
2089
- <span class="lc-overview-pct"><b data-context-pct>${escape(String(initial.pct))}%</b>${escape(t('usedSuffix'))}</span>
2124
+ <b data-context-tot>${escape(contextUsageLabel(initial, t, true))}</b>
2125
+ <span>/ <span data-context-win>${escape(initial.windowLabel || t('unknownCapacity'))}</span><span data-capacity-unit${initial.windowLabel ? '' : ' hidden'}> tokens</span></span>
2126
+ <span class="lc-overview-pct"${initial.pct == null ? ' hidden' : ''}><b data-context-pct>${initial.pct == null ? '' : initial.pct + '%'}</b>${escape(t('usedSuffix'))}</span>
2090
2127
  </div>
2091
- <div class="lc-stacked" data-stacked-bar>
2092
- <div class="lc-stacked-seg is-sys" data-seg="sys" data-cat-key="sys" style="width:${initial.segments.sys}%"></div>
2093
- <div class="lc-stacked-seg is-schema" data-seg="schema" data-cat-key="schema" style="width:${initial.segments.schema}%"></div>
2094
- <div class="lc-stacked-seg is-user" data-seg="user" data-cat-key="user" style="width:${initial.segments.user}%"></div>
2095
- <div class="lc-stacked-seg is-mem" data-seg="mem" data-cat-key="mem" style="width:${initial.segments.mem}%"></div>
2096
- <div class="lc-stacked-seg is-skill" data-seg="skill" data-cat-key="skill" style="width:${initial.segments.skill}%"></div>
2097
- <div class="lc-stacked-seg is-msg" data-seg="msg" data-cat-key="msg" style="width:${initial.segments.msg}%"></div>
2098
- <div class="lc-stacked-seg is-tool" data-seg="tool" data-cat-key="tool" style="width:${initial.segments.tool}%"></div>
2128
+ <div class="lc-stacked" data-stacked-bar${initial.pct == null ? ' hidden' : ''}>
2129
+ ${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('')}
2099
2130
  <div class="lc-stacked-free" title="${escape(t('freeSpaceTitle'))}"></div>
2100
- <div class="lc-trigger" style="left:80%" title="${escape(t('autoCompactTriggerTitle'))}"></div>
2101
- <div class="lc-reserve lc-reserve-headroom" style="left:80%;width:12%" title="${escape(t('headroomTitle'))}"></div>
2102
- <div class="lc-reserve lc-reserve-output" style="left:92%;width:8%" title="${escape(t('outputReserveTitle'))}"></div>
2103
2131
  </div>
2104
2132
  <div class="lc-legend" data-lc-legend>
2105
2133
  <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>
@@ -2250,9 +2278,10 @@ function renderLog(session, line, { t, baseUrl = '' }) {
2250
2278
  const postK = ci.postTokens ? `${(ci.postTokens / 1000).toFixed(1)}k` : ''
2251
2279
  const dropK = ci.droppedTokens ? `${(ci.droppedTokens / 1000).toFixed(1)}k` : ''
2252
2280
  const tpl = ci.docId && ci.content ? `<template data-doc-html="${escape(ci.docId)}">${render(ci.content)}</template>` : ''
2253
- const badgeText = ci.trigger === 'manual' ? t('compactManual') : ci.trigger === 'handoff' ? t('compactHandoff') : t('compactAuto')
2281
+ const badgeText = !ci.trigger ? '' : ci.trigger === 'manual' ? t('compactManual') : ci.trigger === 'handoff' ? t('compactHandoff') : t('compactAuto')
2282
+ const eventTime = item.time ? `<time datetime="${escape(item.time)}">${escape(wallClock(item.time, 0, true))}</time>` : ''
2254
2283
  const freedText = dropK ? t('compactFreed', { tokens: dropK }) : ''
2255
- 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>`)
2284
+ 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>`)
2256
2285
  } else {
2257
2286
  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>`)
2258
2287
  }
@@ -2885,11 +2914,18 @@ function attachPlayerController(containerEl, playerData, { lang = 'zh', initialS
2885
2914
  }
2886
2915
  }
2887
2916
  const totEl = asidePane.querySelector('[data-context-tot]')
2888
- if (totEl) totEl.textContent = `${(snap.totalTokens / 1000).toFixed(1)}k`
2917
+ if (totEl) totEl.textContent = contextUsageLabel(snap, t, stepState.index < 0)
2889
2918
  const winEl = asidePane.querySelector('[data-context-win]')
2890
- if (winEl && snap.windowLabel) winEl.textContent = snap.windowLabel
2919
+ if (winEl) winEl.textContent = snap.windowLabel || t('unknownCapacity')
2920
+ const unit = asidePane.querySelector('[data-capacity-unit]')
2921
+ if (unit) unit.hidden = !snap.windowLabel
2891
2922
  const pctEl = asidePane.querySelector('[data-context-pct]')
2892
- if (pctEl) pctEl.textContent = `${snap.pct}%`
2923
+ if (pctEl) {
2924
+ pctEl.parentElement.hidden = snap.pct == null
2925
+ pctEl.textContent = snap.pct == null ? '' : snap.pct + '%'
2926
+ }
2927
+ const bar = asidePane.querySelector('[data-stacked-bar]')
2928
+ if (bar) bar.hidden = snap.pct == null
2893
2929
 
2894
2930
  for (const [key, val] of Object.entries(snap.segments || {})) {
2895
2931
  const seg = asidePane.querySelector(`[data-seg="${key}"]`)
@@ -2898,7 +2934,7 @@ function attachPlayerController(containerEl, playerData, { lang = 'zh', initialS
2898
2934
 
2899
2935
  for (const [key, val] of Object.entries(snap.tokensByKind || {})) {
2900
2936
  const tokEl = asidePane.querySelector(`[data-pro-tok="${key}"]`)
2901
- if (tokEl) tokEl.textContent = `≈${(val / 1000).toFixed(1)}k`
2937
+ if (tokEl) tokEl.textContent = categoryUsageLabel(val, t)
2902
2938
  }
2903
2939
 
2904
2940
  const browserBox = asidePane.querySelector('[data-context-browser]')
@@ -2997,7 +3033,7 @@ function attachPlayerController(containerEl, playerData, { lang = 'zh', initialS
2997
3033
  ? `<span class="session-tl-pop-thumb"><img src="${escapeHtml(frame.img)}" alt=""></span>`
2998
3034
  : ''
2999
3035
  const headTitle = ci
3000
- ? t('tlCompressTitle', { seq: ci.seq, dropped: ((ci.droppedTokens || 0) / 1000).toFixed(0) })
3036
+ ? (ci.droppedTokens == null ? t('compactTitle', { seq: ci.seq }) : t('tlCompressTitle', { seq: ci.seq, dropped: (ci.droppedTokens / 1000).toFixed(0) }))
3001
3037
  : frame
3002
3038
  ? `🖼 ${frame.label}`
3003
3039
  : doc
@@ -3005,9 +3041,9 @@ function attachPlayerController(containerEl, playerData, { lang = 'zh', initialS
3005
3041
  : s.kind === 'prompt'
3006
3042
  ? t('tlPromptTitle', { turn: s.turn, summary: shorten(s.summary || '', 20) })
3007
3043
  : shorten(s.summary || t('tlStepFallback'), 24)
3008
- const tokStr = `${((s.contextSnapshot?.totalTokens || 0) / 1000).toFixed(1)}k`
3044
+ const tokStr = contextUsageLabel(s.contextSnapshot, t)
3009
3045
  tlPop.style.left = `clamp(min(130px, 50%), ${pct.toFixed(1)}%, max(50%, 100% - 130px))`
3010
- 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>`
3046
+ 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>`
3011
3047
  tlPop.hidden = false
3012
3048
  }
3013
3049
 
@@ -51,12 +51,13 @@
51
51
  "contextWindow": {
52
52
  "type": "integer",
53
53
  "minimum": 1,
54
- "description": "Context window token capacity (e.g. 200000 or 1000000)."
54
+ "description": "Initial context window capacity in tokens. A request can override it when the limit changes."
55
55
  },
56
56
  "initialContext": {
57
57
  "type": "object",
58
58
  "description": "Initial mounted context records captured from the session preamble.",
59
59
  "properties": {
60
+ "estimatedTokens": { "type": "integer", "minimum": 0, "description": "Estimated tokens loaded before user input, from a recorded baseline breakdown." },
60
61
  "sys": {
61
62
  "type": "array",
62
63
  "items": { "$ref": "#/$defs/contextRecord" }
@@ -234,6 +235,13 @@
234
235
  "agent": { "type": "string" },
235
236
  "question": { "type": "boolean" },
236
237
  "answer": { "type": "boolean" },
238
+ "contextWindow": { "type": "integer", "minimum": 0, "description": "Window capacity for this request if it varies within the session. Zero marks an unknown capacity." },
239
+ "contextTokenEstimates": {
240
+ "type": "object",
241
+ "description": "Category estimates recorded for this model request.",
242
+ "propertyNames": { "enum": ["sys", "schema", "mem", "skill"] },
243
+ "additionalProperties": { "type": "integer", "minimum": 0 }
244
+ },
237
245
  "contextTokens": { "type": "integer", "minimum": 0 },
238
246
  "images": {
239
247
  "type": "array",