dsh-token-viz 0.0.0-stage → 1.1.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.
package/README.md CHANGED
@@ -1,3 +1,99 @@
1
- # Temporary Holding Version
1
+ # dsh-token-viz
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ DSH Desktop 会话逐轮 Token 可视化插件。在“对话、轨迹、上下文”旁选择“Token 消耗”会话视图;图表只占用当前会话内容区域,顶部工具栏控制轮次窗口,右上角显示会话累计消耗。上排展示每轮用量和所选轮次的分类明细,下排通栏展示会话累计用量。
4
+
5
+ ## 安装到 Desktop
6
+
7
+ 已按 DSH 0.2.2-rc.5 的 Desktop 插件契约实现,Node 要求至少 24.9.0。在插件目录的上级目录运行以下命令,将路径替换为实际绝对路径。
8
+
9
+ ```bash
10
+ dsh plugin --profile desktop add "C:/Users/28483/Documents/deepseek-harness/default-workspace/dsh-token-viz"
11
+ ```
12
+
13
+ 也可在 Desktop 会话中让插件管理工具安装此目录。安装目标必须是正在使用的 desktop profile。在 Settings → Plugins 中确认“Token 消耗”已启用,刷新会话页面后查看与“对话”并列的标签。
14
+
15
+ package.json 中的 `dsh.client.platform` 使用 `web`,这是当前 DSH 为 Electron 渲染进程使用的 Client 加载标识。安装与运行目标为 `desktop` profile。Host 入口为 `lib/index.js`,Client 入口为 `lib/client.js`,通过 `window.__ModuleLoader__` 注册。
16
+
17
+ ## 数据与折叠语义
18
+
19
+ Host 向 `sessionProjections` 注册逐轮用量投影。DSH 从 `$DSH_HOME/sessions/**/session.vN.jsonl.zstd` 恢复历史事件,并向投影提供活跃会话的新增事件。
20
+
21
+ 与当前 DSH `tokenUsage` 投影保持相同的事件顺序折叠规则。
22
+
23
+ - `assistant/message` 优先取 `data.usage`,否则取 stream 中最后一个 usage chunk。
24
+ - `assistant/attempt` 取 stream 中最后一个 usage chunk。
25
+ - 同一连续 `(turn, step)` 调用中的后续有效 usage 替换前值,流式估计被最终结算覆盖。
26
+ - 匹配当前 `(turn, step)` 的 `llm/retry-started` 开启下一次调用,之前调用的消耗保留,新调用累加。
27
+ - 缺少 usage 的后续事件保留已有的有效结算。
28
+ - 每轮以 `turn/start` 对齐,一个用户轮次中多个工具步骤和重试调用归入同一轮。界面轮号按日志出现顺序从 1 开始。
29
+ - 提示词通过独立的会话投影 `dshTokenVizPrompts` 读取,按原始轮次与图表关联,不要求先滚动加载旧聊天,也不会写入工作区会话摘要。
30
+
31
+ 总 Token = `inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens`。DSH 的 input 已排除 cache,reasoning 已包含在 output 中。遵循该投影口径,忽略额外的 `totalTokens` 字段。
32
+
33
+ 完全缺失 usage 的轮次保留横轴位置,显示空心折线点和中性标记柱,tooltip 注明“usage 缺失”,点击后显示饼图空状态。有部分步骤缺失的轮次展示已知用量并提示数据不完整。累计曲线在有缺失时表达已记录用量的累计值,实际用量可能更高。有效的全零 usage 会保留为已记录的零用量。
34
+
35
+ ### 为什么某些轮次没有用量?
36
+
37
+ 调用开始不等于提供方返回了用量。若该轮结束状态是 `aborted` 或 `error`,且既没有最终结算也没有流式 usage,视图会说明中止或出错,并保留该轮。未记录结束原因时只报告 usage 缺失,不推断发生了什么。仅凭消息文本或请求上下文无法还原准确的缓存、输出和推理用量;要补回数字,需要能与该次调用匹配的提供方结算记录。
38
+
39
+ ## 增量缓存
40
+
41
+ 1.1 改用 DSH 原生会话投影 `dshTokenVizUsage`。DSH 按会话管理投影的检查点和增量事件;历史会话可从日志恢复,活跃会话随事件更新。Client 订阅当前会话的投影,不再轮询自建 HTTP 地址,也不再维护另一份基于文件时间戳的运行时缓存。
42
+
43
+ ## 饼图拆分粒度
44
+
45
+ “轮次内分类用量”按 usage 原生字段拆分。使用 input、output、cacheRead、cacheWrite、reasoning 五类。
46
+
47
+ 为防止 reasoning 重复计算,饼图中的 output 表示 `outputTokens - reasoningTokens`,reasoning 从 output 中独立显示。若提供方报告的 reasoning 超过 output,可视化按 output 上限截取,tooltip 仍展示原始字段。每个分类显示 token 数及占比,并按消耗降序排列。
48
+
49
+ 日志中的文本来源无法提供可靠的精确 Token 归因,因此工具调用、系统提示词等内容来源未单独计量。Token 数来自提供方 usage,未进行本地 tokenizer 估算。
50
+
51
+ ## 图表与交互
52
+
53
+ 采用手写 SVG 折线图、堆叠柱状图和饼图。当前 Desktop Client 入口直接由 ModuleLoader 加载,宿主未公开 ECharts 依赖,此插件采用需求允许的 SVG 降级方案,保持免构建和无额外依赖。tooltip 使用浮动 div。
54
+
55
+ - 横轴为轮次,纵轴为 Token 数。每根有记录的柱标本轮总量,每个点标截至该轮的已知累计量;图表在容器内压缩轮距并显示全部所选轮次,不出现图内滚动条。工具栏中的“在图上显示用量”默认开启,关闭只隐藏数值标签,不影响悬浮明细。
56
+ - 悬浮堆叠柱时高亮整柱。鼠标在折线绘图区内按横向位置命中最近轮次,无须瞄准圆点;高亮点向两轴各绘一条虚线。悬浮只预览明细和该轮的用户提示词,不改变分类图所选轮次。要看已选轮次的原文,可悬浮或用 Tab 聚焦分类图标题旁的「第 X 轮」。usage 缺失不影响原文显示;无可用文字时不会借用相邻轮次的内容。
57
+ - 全局工具栏的窗口只控制横轴,不改变右上角的会话总量。有缺失时右上角标示已知累计消耗。
58
+ - 点击折线点或柱,右侧切换至该轮。默认选中最新轮次。
59
+ - 支持最近 3 次(默认)、7 次、15 次、30 次、自定义最近 N 次及全部,共同控制两张图的横轴窗口。饼图保留当前选中轮次。
60
+ - 切换会话时清空旧数据并获取新会话用量。视图收到会话投影更新时刷新。
61
+ - 点击“对话”“轨迹”“上下文”等标签即可切换视图,无需关闭按钮或 Escape。成功确认没有轮次时显示“当前会话暂无对话历史,说句话试试吧~”;已有轮次但缺失 usage 不会被判定为没有历史。
62
+ - 面板和图表使用 DSH 官方语义 CSS token,随明暗主题变化。
63
+
64
+ ## 配置
65
+
66
+ 在 Settings → Plugins 中定位插件配置,或通过 DSH 的 profile 配置编辑入口修改对应配置。
67
+
68
+ | 配置项 | 默认值 | 含义 |
69
+ | --- | --- | --- |
70
+ | `defaultWindow` | `3` | 初始显示最近 N 轮 |
71
+
72
+ 旧版 `refreshMs` 和 `maxSessions` 不再生效:渲染进程订阅会话更新,不再定时发出 HTTP 请求。
73
+
74
+ 配置初值也声明在 `cordis.patch.yml` 中。
75
+
76
+ ## 开发与调试
77
+
78
+ ```bash
79
+ cd dsh-token-viz
80
+ npm test
81
+ npm run check
82
+ ```
83
+
84
+ 修改 Host 代码后需要重启 Desktop 应用。修改 Client 代码后刷新页面即可。确认修改的是 Desktop 当前安装目录实际加载的文件,本地安装方式若产生副本,需要重新安装后再执行对应重启或刷新步骤。
85
+
86
+ ## 最少验收步骤
87
+
88
+ 1. 在 Settings → Plugins 确认“Token 消耗”已启用,打开已有至少 10 个用户轮次的会话,确认“上下文”旁出现“Token 消耗”,侧栏和底栏仍可操作。
89
+ 2. 点击按钮,检查折线图与柱状图同时可见,横轴轮数与 `turn/start` 数一致。包含工具调用的用户轮次汇总该轮全部调用。
90
+ 3. 点击第 A 轮的柱,再悬浮第 B 轮的折线点:图表提示应显示 B 的用户文本、Token 明细和累计值;悬浮或用 Tab 聚焦分类图的「第 A 轮」,应显示 A 的原文。把窗口切到「全部」后对早期轮次重复检查。
91
+ 4. 切换“7 次”,确认两张图仅显示最近 7 轮,再选“全部”恢复全部轮次。自定义输入正整数后确认窗口变化。
92
+ 5. 点击中间一根柱,再点击另一个折线点,确认饼图标题为“第 N 轮”,分类按 token 降序,分区之和等于该轮总量。
93
+ 6. 使用存在缺失 usage 的真实会话检查空心点、中性柱和 tooltip,点击该轮应出现“usage 缺失”空状态。可先运行单元测试验证缺失、流式覆盖及重试语义。
94
+ 7. 保持面板打开并切换到另一个会话,检查轮数和总量刷新,旧会话数据清空。
95
+ 8. 分别切换明暗主题,检查文字、图表与浮动 tooltip 的可读性,再点击“对话”标签返回原会话内容。另建空会话,检查无历史提示。
96
+
97
+ ## 验证记录
98
+
99
+ Host 测试覆盖逐轮折叠、重试、缺失与零值,以及原生投影检查点恢复和视图数据。升级 1.0 后请完全退出并重新启动 Desktop,以同时载入新的 Host 投影和 Client 标签。自动测试不能代替渲染进程中的实际交互验收。
@@ -0,0 +1,5 @@
1
+ - insert:
2
+ - id: dsh-token-viz
3
+ name: dsh-token-viz
4
+ config:
5
+ defaultWindow: 3
package/icon.svg ADDED
@@ -0,0 +1,12 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36">
2
+ <g fill="none" stroke="#5578c9" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
3
+ <path d="M5 6v24h26"/>
4
+ <path d="m8 22 7-7 6 3 9-11"/>
5
+ </g>
6
+ <g fill="#5578c9">
7
+ <circle cx="8" cy="22" r="2"/>
8
+ <circle cx="15" cy="15" r="2"/>
9
+ <circle cx="21" cy="18" r="2"/>
10
+ <circle cx="30" cy="7" r="2"/>
11
+ </g>
12
+ </svg>
package/lib/cache.js ADDED
@@ -0,0 +1,95 @@
1
+ import { stat as fsStat } from 'node:fs/promises';
2
+ import { createHash } from 'node:crypto';
3
+ const digest = event => createHash('sha256').update(JSON.stringify(event)).digest('hex');
4
+ import { createUsageState, applyUsageEvent, usageView } from './usage.js';
5
+
6
+ async function fileInfo(snapshot, statFile) {
7
+ if (!snapshot.location?.path) return null;
8
+ try {
9
+ const file = await statFile(snapshot.location.path);
10
+ return { mtimeMs: file.mtimeMs, size: file.size };
11
+ } catch (error) {
12
+ if (error.code === 'ENOENT') return null;
13
+ throw error;
14
+ }
15
+ }
16
+
17
+ export function createSessionCache(persistence, { maxSessions = 32, statFile = fsStat } = {}) {
18
+ const entries = new Map();
19
+ const pending = new Map();
20
+ let generation = 0;
21
+
22
+ async function load(sessionId) {
23
+ const epoch = generation;
24
+ const serviceIdentity = persistence.identity;
25
+ const snapshot = await persistence.stat(sessionId);
26
+ if (!snapshot) throw new Error('session not found');
27
+ const file = await fileInfo(snapshot, statFile);
28
+ const signature = JSON.stringify([snapshot.revision, snapshot.sizeBytes, snapshot.location?.path, file]);
29
+ const old = entries.get(sessionId);
30
+ const sameService = old?.serviceIdentity === serviceIdentity;
31
+ if (sameService && old.signature === signature) {
32
+ entries.delete(sessionId);
33
+ entries.set(sessionId, old);
34
+ return old.view;
35
+ }
36
+ const appendable = sameService && old.lastSeq !== null
37
+ && !(file && old.file && file.size < old.file.size)
38
+ && !(snapshot.eventCount !== undefined && snapshot.eventCount <= old.lastSeq);
39
+ const handle = await persistence.open(sessionId, 'read');
40
+ let state;
41
+ let events;
42
+ let extended = false;
43
+ try {
44
+ if (appendable) {
45
+ const result = await handle.read(old.lastSeq);
46
+ const anchor = result.events[0];
47
+ if (anchor?.seq === old.lastSeq && digest(anchor) === old.anchor) {
48
+ state = structuredClone(old.state);
49
+ events = result.events.slice(1);
50
+ extended = true;
51
+ }
52
+ }
53
+ if (!state) {
54
+ state = createUsageState();
55
+ state.sessionId = sessionId;
56
+ events = (await handle.read(0)).events;
57
+ }
58
+ for (const event of events) applyUsageEvent(state, event);
59
+ } finally {
60
+ await handle.close();
61
+ }
62
+ const last = events.at(-1);
63
+ const entry = {
64
+ state, view: usageView(state), signature, serviceIdentity, file,
65
+ lastSeq: last?.seq ?? (extended ? old.lastSeq : null),
66
+ anchor: last ? digest(last) : (extended ? old.anchor : null),
67
+ };
68
+ if (epoch === generation) {
69
+ entries.delete(sessionId);
70
+ entries.set(sessionId, entry);
71
+ while (entries.size > maxSessions) entries.delete(entries.keys().next().value);
72
+ }
73
+ return entry.view;
74
+ }
75
+
76
+ async function get(sessionId) {
77
+ if (pending.has(sessionId)) return pending.get(sessionId);
78
+ const task = load(sessionId);
79
+ pending.set(sessionId, task);
80
+ try {
81
+ return await task;
82
+ } finally {
83
+ if (pending.get(sessionId) === task) pending.delete(sessionId);
84
+ }
85
+ }
86
+
87
+ return {
88
+ get,
89
+ clear() {
90
+ generation += 1;
91
+ entries.clear();
92
+ pending.clear();
93
+ },
94
+ };
95
+ }
package/lib/client.js ADDED
@@ -0,0 +1,151 @@
1
+ (() => {
2
+ const fields = ['input', 'output', 'cacheRead', 'cacheWrite', 'reasoning'];
3
+ const labels = { input: '输入', output: '输出(不含推理)', cacheRead: '缓存读取', cacheWrite: '缓存写入', reasoning: '推理' };
4
+ const raw = { input: 'inputTokens', output: 'outputTokens', cacheRead: 'cacheReadTokens', cacheWrite: 'cacheWriteTokens', reasoning: 'reasoningTokens' };
5
+ const colors = { input: 'var(--dsw-alias-brand-primary)', output: 'var(--dsw-alias-state-success-primary)', cacheRead: 'var(--dsw-alias-state-warn-primary)', cacheWrite: 'var(--dsw-alias-state-idle-primary)', reasoning: 'var(--dsw-alias-state-error-primary)' };
6
+ const formatter = new Intl.NumberFormat('zh-CN');
7
+ const fmt = v => Number.isFinite(v) ? formatter.format(v) : '未知';
8
+ const roundNumber = r => r.number ?? r.turn;
9
+ const roundKey = r => String(r.turn ?? r.number);
10
+ const roundName = r => `第 ${roundNumber(r)} 轮`;
11
+ const rawLabel = key => key === 'output' ? '输出(含推理)' : labels[key];
12
+ const markValue = (r, kind) => kind === 'line' ? r.cumulative : r.missing ? null : r.total;
13
+ const markLabel = (r, kind) => (kind === 'bar' && r.partial && Number.isFinite(r.total) ? '≥' : '') + fmt(markValue(r, kind));
14
+ const chooseRound = (rows, key) => rows.find(r => roundKey(r) === key) ?? rows.at(-1);
15
+ const interaction = (state, action) => action.type === 'select' ? { ...state, selected: action.key } : { ...state, preview: action.key };
16
+ function usageNote(r) {
17
+ if (!r.missing && !r.partial) return '';
18
+ const reason = r.endReason === 'aborted' ? '本轮已中断;' : r.endReason === 'error' ? '本轮因错误结束;' : '';
19
+ return reason + (r.missing ? '未记录用量,实际消耗未知。' : '仅记录了部分用量,所示数值为已知部分。');
20
+ }
21
+ function layout(rows, kind, viewport = 0) {
22
+ let max = 1;
23
+ for (const row of rows) {
24
+ max = Math.max(max, markValue(row, kind) || 0);
25
+ }
26
+ const base = Math.pow(10, Math.floor(Math.log10(Math.max(1,max/4))));
27
+ const unit = [1,2,5,10].find(v => v*base >= max/4) * base;
28
+ const topValue = Math.ceil(max/unit) * unit;
29
+ const ticks = Array.from({length: Math.round(topValue/unit)+1}, (_,i) => i*unit);
30
+ const left = Math.max(46, fmt(topValue).length * 8 + 14), top = 33, bottom = 221;
31
+ const width = (viewport || 320), right = width - 12;
32
+ const step = (right-left) / Math.max(1,rows.length);
33
+ return {width,left,right,top,bottom,step,ticks,count:rows.length,x:i=>left+(i+.5)*step,y:v=>bottom-(v || 0)/topValue*(bottom-top)};
34
+ }
35
+ function nearest(g,x,y) {
36
+ if (!g.count || !Number.isFinite(x) || !Number.isFinite(y) || x<g.left || x>g.right || y<g.top || y>g.bottom) return -1;
37
+ return Math.min(g.count-1, Math.floor((x-g.left)/g.step));
38
+ }
39
+ // The same plain-script helpers can run under Node without browser or React dependencies.
40
+ if (typeof module !== 'undefined' && module.exports) module.exports = { layout, nearest, markLabel, usageNote, chooseRound, rawLabel, interaction };
41
+ window.__ModuleLoader__.load({ id:'dsh-token-viz', factory(require) {
42
+ const React = require('react'), h = React.createElement;
43
+ const brand = colors.input, axis = 'var(--dsw-alias-label-secondary)', surface = 'var(--dsw-alias-bg-layer-1)';
44
+ const css = `
45
+ .dtv-view{height:100%;min-height:0;overflow:auto;padding:16px;color:var(--dsw-alias-label-primary);font-family:inherit;font-size:14px;line-height:1.5;font-variant-numeric:tabular-nums}.dtv-view,.dtv-view *{box-sizing:border-box}.dtv-view :is(h3,p,dl,dd){margin:0}.dtv-view h3{font-size:16px}.dtv-muted,.dtv-view small{color:var(--dsw-alias-label-secondary)}.dtv-warning{color:var(--dsw-alias-state-warn-primary)}
46
+ .dtv-toolbar,.dtv-controls,.dtv-legend,.dtv-title{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.dtv-toolbar,.dtv-title{justify-content:space-between}.dtv-toolbar{margin-bottom:14px}.dtv-controls button,.dtv-controls input{font:inherit;border:1px solid var(--dsw-alias-border-l1);border-radius:6px;background:var(--dsw-alias-bg-layer-2);color:inherit;padding:4px 8px}.dtv-controls button{cursor:pointer}.dtv-controls input{width:5em}.dtv-controls button:hover,.dtv-controls button[aria-pressed=true]{color:var(--dsw-alias-brand-primary);border-color:currentColor}.dtv-view :focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:2px}
47
+ .dtv-upper{display:grid;grid-template-columns:minmax(0,1.8fr) minmax(240px,1fr);gap:14px;margin-bottom:14px}.dtv-card{min-width:0;padding:14px;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1)}.dtv-view{container-type:inline-size}@container(max-width:700px){.dtv-upper{grid-template-columns:minmax(0,1fr)}}
48
+ .dtv-plot{position:relative;margin-top:6px}.dtv-scroll{width:100%;min-width:0}.dtv-scroll svg{display:block;width:100%;overflow:hidden}.dtv-scroll g[role=button]:focus:not(:focus-visible){outline:none}.dtv-scroll text{font-family:inherit;font-size:12px;fill:var(--dsw-alias-label-secondary);pointer-events:none}.dtv-scroll text.dtv-value{fill:var(--dsw-alias-label-primary);font-weight:600}.dtv-tip{position:absolute;z-index:1;top:4px;max-width:100%;width:max-content;pointer-events:none;padding:8px 10px;background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l2);border-radius:6px;font-size:12px}.dtv-tip dl,.dtv-breakdown li{display:grid;align-items:center;column-gap:8px}.dtv-tip dl{grid-template-columns:minmax(0,1fr) auto}.dtv-tip dd{text-align:right}.dtv-legend{gap:6px 14px;font-size:12px}.dtv-swatch{display:inline-block;width:10px;height:10px;border-radius:2px;margin-right:5px}.dtv-breakdown{list-style:none;padding:0;margin:4px 0 0}.dtv-breakdown li{grid-template-columns:1fr auto 4em;font-size:13px}.dtv-breakdown li span:last-child{text-align:right}.dtv-empty{padding:40px 12px;text-align:center;color:var(--dsw-alias-label-secondary)}
49
+ .dtv-tip{max-width:min(100%,28rem)}.dtv-prompt-preview,.dtv-prompt-full{white-space:pre-wrap;overflow-wrap:anywhere}.dtv-prompt-preview{display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}.dtv-title{position:relative}.dtv-prompt-trigger{cursor:help;border-radius:3px;text-decoration:underline dotted;text-underline-offset:3px}.dtv-prompt-full{display:none;position:absolute;z-index:2;inset-inline-end:0;top:100%;width:min(100%,28rem);max-height:min(14rem,44vh);overflow:auto;padding:8px 10px;border:1px solid var(--dsw-alias-border-l2);border-radius:6px;background:var(--dsw-alias-bg-layer-2);font-size:13px}.dtv-round-prompt:hover .dtv-prompt-full,.dtv-round-prompt:focus-within .dtv-prompt-full{display:block}
50
+ `;
51
+ const swatch = key => h('i',{className:'dtv-swatch',style:{background:colors[key]},'aria-hidden':true});
52
+ function TokenView({sessionId,useProjection}) {
53
+ const snapshot = useProjection('dshTokenVizUsage');
54
+ const prompts = useProjection('dshTokenVizPrompts');
55
+ const data = React.useMemo(() => {
56
+ if (!snapshot || snapshot.sessionId !== sessionId || !Array.isArray(snapshot.rounds)) return null;
57
+ const byTurn = new Map((prompts?.sessionId === sessionId ? prompts.prompts : []).map(([turn,text,source])=>[turn,{userPrompt:text,promptSource:source||'user'}]));
58
+ const confirmations = new Map();
59
+ for (const call of prompts?.sessionId===sessionId ? prompts.confirmations??[] : []) {
60
+ const lines=call.items.length ? call.items.map(q=>`Agent 提问:${q.question}\n用户答复:${q.reply ?? '尚无可读取的答复记录'}`) : ['日志记录了确认调用,但没有可读取的问题或答复。'];
61
+ confirmations.set(call.turn,[...(confirmations.get(call.turn)??[]),...lines]);
62
+ }
63
+ return { ...snapshot, rounds: snapshot.rounds.map(round => ({ ...round, ...(byTurn.get(round.turn) ?? {userPrompt:null}), confirmations:confirmations.get(round.turn) })) };
64
+ }, [sessionId, snapshot, prompts]);
65
+ if (!data) return h('p',{role:'status'},'正在同步本会话的 Token 用量… 若升级后一直没有数据,请完全退出并重新启动 Desktop。');
66
+ return h(SessionCharts,{key:sessionId,data});
67
+ }
68
+ const promptLabel = r => !r.userPrompt && r.confirmations?.length ? '本轮确认记录' : r.promptSource === 'agent-message' ? '代理消息(自动触发)' : r.promptSource === 'subagent-settled' ? '子代理完成通知(自动触发)' : '用户提示词';
69
+ const promptText = r => [r.userPrompt,...(r.confirmations??[])].filter(Boolean).join('\n\n') || '本轮没有可显示的用户文本';
70
+ function RoundPrompt({round:r}) {
71
+ const id = React.useId();
72
+ return h('div',{className:'dtv-round-prompt'},
73
+ h('span',{className:'dtv-prompt-trigger dtv-muted',tabIndex:0,'aria-describedby':id},h('span',{'aria-live':'polite'},roundName(r))),
74
+ h('div',{className:'dtv-prompt-full',id,role:'tooltip',tabIndex:0},h('b',null,promptLabel(r)+':'),promptText(r)));
75
+ }
76
+ function Tooltip({round:r, known, id, side}) {
77
+ const entry = (key,label,value) => h(React.Fragment,{key},h('dt',null,label),h('dd',null,value));
78
+ return h('div',{className:'dtv-tip',role:'tooltip',id,style:{[side]:4}},h('strong',null,roundName(r)),
79
+ h('p',{className:'dtv-prompt-preview'},h('b',null,promptLabel(r)+':'),promptText(r)),
80
+ usageNote(r) && h('p',{className:'dtv-warning'},usageNote(r)),h('dl',null,
81
+ entry('total','本轮用量',markLabel(r,'bar')), entry('sum',known?'已知累计用量':'累计用量',fmt(r.cumulative)),
82
+ ...fields.map(k=>entry(k,`${rawLabel(k)} · ${raw[k]}`,fmt(r.usage?.[raw[k]])))));
83
+ }
84
+ function Plot({rows,kind,selection,preview,dispatch,known,showAmounts}) {
85
+ const scroll = React.useRef(null), [viewport,setViewport] = React.useState(0);
86
+ React.useLayoutEffect(()=>{ const el = scroll.current; if (!el) return; const sync=()=>setViewport(el.clientWidth); sync(); const observer=new ResizeObserver(sync); observer.observe(el); return ()=>observer.disconnect(); },[]);
87
+ const g = React.useMemo(()=>layout(rows,kind,viewport),[rows,kind,viewport]), line = kind==='line';
88
+ const tipId = React.useId(), hoverIndex = preview?.kind === kind ? rows.findIndex(r=>roundKey(r)===preview.round) : -1;
89
+ const hover = rows[hoverIndex];
90
+ const setPreview = (row,side) => dispatch({type:'preview',key:row ? {kind,round:roundKey(row),side} : null});
91
+ const select = r => dispatch({type:'select',key:roundKey(r)});
92
+ function pointer(event,commit) {
93
+ const rect = event.currentTarget.getBoundingClientRect();
94
+ const index = nearest(g,(event.clientX-rect.left)*g.width/rect.width,(event.clientY-rect.top)*258/rect.height);
95
+ if (commit) { if (index>=0) select(rows[index]); return; }
96
+ const box = scroll.current.getBoundingClientRect();
97
+ setPreview(rows[index], event.clientX-box.left < box.width/2 ? 'right':'left');
98
+ }
99
+ const segment = (key,x1,y1,x2,y2,props={}) => h('line',{key,x1,y1,x2,y2,stroke:axis,...props});
100
+ const text = (x,y,value,props={}) => h('text',{x,y,textAnchor:'middle',...props},value);
101
+ const marks = rows.map((r,i)=>{
102
+ const x=g.x(i), y=g.y(markValue(r,kind)), active=i===hoverIndex, chosen=r===selection;
103
+ const width=g.step<12?g.step:Math.min(40,g.step*.72), left=x-width/2, height=Math.max(4,g.bottom-y);
104
+ let base=g.bottom;
105
+ return h('g',{key:roundKey(r),tabIndex:0,role:'button','aria-pressed':chosen,'aria-label':`${roundName(r)},${line ? '累计':'本轮'}用量 ${markLabel(r,kind)}。${usageNote(r)}`, 'aria-describedby':active?tipId:undefined,
106
+ style:{cursor:'pointer'},onMouseDown:e=>e.preventDefault(),onFocus:()=>setPreview(r,g.x(i)-scroll.current.scrollLeft<viewport/2?'right':'left'),onBlur:()=>setPreview(null),
107
+ onKeyDown:e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();select(r);}if(e.key==='Escape')setPreview(null);},
108
+ onClick:e=>{e.stopPropagation();select(r);}},
109
+ h('rect',{x:x-g.step/2,y:g.top,width:g.step,height:g.bottom-g.top,fill:brand,fillOpacity:active?.075:0}),
110
+ line ? h('circle',{cx:x,cy:y,r:active?8:6,fill:r.missing?surface:brand,stroke:active?'var(--dsw-alias-label-primary)':surface,strokeWidth:active?3:2}) : h(React.Fragment,null,
111
+ ...(r.categories||[]).map(({key,tokens})=>{const part=g.bottom-g.y(tokens);base-=part;return h('rect',{key,x:left,y:base,width,height:part,fill:colors[key]});}),
112
+ h('rect',{x:left,y:g.bottom-height,width,height,fill:r.missing?axis:'none',fillOpacity:.2,stroke:active||r.missing||r.total===0?axis:'none',strokeWidth:active?2.5:1,strokeDasharray:r.missing?'3 2':undefined})),
113
+ showAmounts && text(x,y-12,markLabel(r,kind),{className:'dtv-value'}),segment('tick',x,g.bottom,x,g.bottom+4),i%Math.max(1,Math.ceil(54/g.step))===0 && text(x,g.bottom+20,roundName(r)));
114
+ });
115
+ return h('div',{className:'dtv-plot'},h('div',{ref:scroll,className:'dtv-scroll',onScroll:()=>setPreview(null)},
116
+ h('svg',{width:g.width,height:258,viewBox:`0 0 ${g.width} 258`,role:'group','aria-label':line?'各轮累计 Token 用量':'各轮 Token 分类堆叠用量',
117
+ onPointerMove:e=>pointer(e,false),onPointerLeave:()=>setPreview(null),onClick:e=>pointer(e,true)},
118
+ text(g.left-8,16,'Token',{textAnchor:'end'}),...g.ticks.map(t=>h('g',{key:t},segment('grid',g.left,g.y(t),g.right,g.y(t),{opacity:.16}),segment('tick',g.left-4,g.y(t),g.left,g.y(t)),text(g.left-8,g.y(t)+4,fmt(t),{textAnchor:'end'}))),
119
+ segment('y',g.left,g.top,g.left,g.bottom),segment('x',g.left,g.bottom,g.right,g.bottom),
120
+ line && h('polyline',{points:rows.map((r,i)=>`${g.x(i)},${g.y(r.cumulative)}`).join(' '),fill:'none',stroke:brand,strokeWidth:2}),
121
+ line && hover && h('path',{d:`M ${g.left} ${g.y(hover.cumulative)} H ${g.x(hoverIndex)} V ${g.bottom}`,fill:'none',stroke:axis,strokeDasharray:'4 4',pointerEvents:'none'}),...marks)),
122
+ hover && h(Tooltip,{id:tipId,round:hover,known,side:preview.side}));
123
+ }
124
+ function Pie({round:r}) {
125
+ if (!r || r.missing || !r.usage) return h('p',{className:'dtv-empty'},r ? usageNote(r)||'未记录用量,无法绘制占比。':'暂无可选择的轮次');
126
+ const parts = fields.map(key=>({key,tokens:r.categories?.find(p=>p.key===key)?.tokens||0})).sort((a,b)=>b.tokens-a.tokens);
127
+ const total=parts.reduce((sum,p)=>sum+p.tokens,0); let offset=0;
128
+ return h(React.Fragment,null,r.partial && h('p',{className:'dtv-warning'},usageNote(r)),!total ? h('p',{className:'dtv-empty'},r.partial?'已知用量为 0,无法绘制占比。':'此轮用量为 0,暂无占比。') : h(React.Fragment,null,
129
+ h('svg',{viewBox:'0 0 240 134',role:'img','aria-label':`${roundName(r)}已记录用量占比`,style:{display:'block',width:'100%',height:134}},...parts.filter(p=>p.tokens>0).map(p=>{
130
+ const size=100*p.tokens/total; const slice=h('circle',{key:p.key,cx:120,cy:67,r:48,fill:'none',stroke:colors[p.key],strokeWidth:17,pathLength:100,strokeDasharray:`${size} ${100-size}`,strokeDashoffset:-offset,transform:'rotate(-90 120 67)'},h('title',null,`${labels[p.key]} ${fmt(p.tokens)}`));offset+=size;return slice;}),h('text',{x:120,y:72,textAnchor:'middle',fill:'var(--dsw-alias-label-primary)',fontSize:14},markLabel(r,'bar'))),
131
+ h('ul',{className:'dtv-breakdown'},...parts.map(p=>h('li',{key:p.key},h('span',null,swatch(p.key),labels[p.key]),h('span',null,fmt(p.tokens)),h('span',{className:'dtv-muted'},`${(100*p.tokens/total).toFixed(1)}%`))))));
132
+ }
133
+ function SessionCharts({data}) {
134
+ const [windowSize,setWindow]=React.useState(data.defaultWindow||3),[custom,setCustom]=React.useState(''),[error,setError]=React.useState('');
135
+ const [showAmounts,setShowAmounts]=React.useState(true);
136
+ const [state,dispatch]=React.useReducer(interaction,{selected:null,preview:null});
137
+ const rows=React.useMemo(()=>windowSize==='all'?data.rounds:data.rounds.slice(-windowSize),[data.rounds,windowSize]);
138
+ const selection=chooseRound(data.rounds,state.selected), plot=kind=>h(Plot,{rows,kind,selection,preview:state.preview,dispatch,showAmounts,known:data.hasMissing});
139
+ const changeWindow=v=>{setWindow(v);setError('');dispatch({type:'preview',key:null});};
140
+ return h('section',{className:'dtv-view',role:'region','aria-label':'Token 消耗'},h('style',null,css),!rows.length ? h('p',{className:'dtv-empty'},'当前会话暂无对话历史,说句话试试吧~') : h(React.Fragment,null,
141
+ h('div',{className:'dtv-toolbar'},h('div',{className:'dtv-controls'},...[3,7,15,30,'all'].map(v=>h('button',{type:'button',key:v,'aria-pressed':v===windowSize,onClick:()=>changeWindow(v)},v==='all'?'全部':`最近 ${v} 轮`)),
142
+ h('form',{className:'dtv-controls',onSubmit:e=>{e.preventDefault();const v=Number(custom);if(!Number.isSafeInteger(v)||v<1){setError('请输入正整数轮数');return;}changeWindow(v);}},h('label',null,'自定义 ',h('input',{type:'number',min:1,step:1,value:custom,onChange:e=>setCustom(e.target.value)})),h('button',{type:'submit'},'应用'))),
143
+ h('div',{className:'dtv-controls'},h('button',{type:'button','aria-pressed':showAmounts,onClick:()=>setShowAmounts(value=>!value)},'在图上显示用量')),
144
+ h('strong',null,`${data.hasMissing?'已知累计消耗':'累计消耗'} ${fmt(data.total)} Token`)),error && h('p',{role:'alert',className:'dtv-warning'},error),
145
+ h('div',{className:'dtv-upper'},h('section',{className:'dtv-card'},h('h3',null,'每轮用量'),plot('bar'),h('div',{className:'dtv-legend'},...fields.map(k=>h('span',{key:k},swatch(k),labels[k])))),
146
+ h('section',{className:'dtv-card'},h('div',{className:'dtv-title'},h('h3',null,'轮次内分类用量'),h(RoundPrompt,{round:selection})),h(Pie,{round:selection}))),
147
+ h('section',{className:'dtv-card'},h('h3',null,'会话累计用量'),data.hasMissing && h('small',null,'部分用量未记录,累计曲线仅表示已知消耗。'),plot('line'))));
148
+ }
149
+ return {inject:['slots'],apply(ctx){ctx.slots.inject('conversation.view',()=>ctx.slots.register({name:'conversation.view',id:'dsh-token-viz-view',order:40,label:'Token 消耗'},TokenView));}};
150
+ }});
151
+ })();
package/lib/index.js ADDED
@@ -0,0 +1,108 @@
1
+ import { z } from 'zod';
2
+ import { applyUsageEvent, usageView } from './usage.js';
3
+
4
+ const count = z.number().int().nonnegative();
5
+ const usage = z.strictObject({ inputTokens: count, outputTokens: count, cacheReadTokens: count, cacheWriteTokens: count, reasoningTokens: count });
6
+ const call = z.strictObject({ known: z.boolean(), missingAttempts: count });
7
+ const endReason = z.enum(['aborted', 'error']).nullable();
8
+ const round = z.strictObject({ turn: count, endReason, usage, samples: count, calls: z.array(z.tuple([count, call])) });
9
+ const stateSchema = z.strictObject({ sessionId: z.string(), rounds: z.array(round), last: z.strictObject({ turn: count, step: count, usage }).nullable() });
10
+ const categories = z.array(z.strictObject({ key: z.enum(['input', 'output', 'cacheRead', 'cacheWrite', 'reasoning']), tokens: count }));
11
+ const viewSchema = z.strictObject({ sessionId: z.string(), defaultWindow: count, total: count, hasMissing: z.boolean(), rounds: z.array(z.strictObject({ turn: count, endReason, number: count, total: count.nullable(), cumulative: count, usage: usage.nullable(), categories, missing: z.boolean(), partial: z.boolean() })) });
12
+ const relevant = new Set(['turn/start', 'turn/end', 'step/start', 'llm/retry-started', 'assistant/message', 'assistant/attempt']);
13
+ const hydrate = saved => ({ ...saved, usage: { ...saved.usage }, calls: new Map(saved.calls.map(([step, entry]) => [step, { ...entry }])) });
14
+
15
+ // The durable native checkpoint is plain JSON. Only materialize the touched
16
+ // round for a transition; never keep an event, stream, or message in state.
17
+ function fold(state, event) {
18
+ if (!relevant.has(event.type)) return state;
19
+ const turn = event.data.turn;
20
+ const tail = state.rounds.length - 1;
21
+ const at = state.rounds[tail]?.turn === turn ? tail : state.rounds.findIndex(item => item.turn === turn);
22
+ if (at >= 0 && event.type === 'turn/start') return state;
23
+ const working = { last: state.last, rounds: new Map(at < 0 ? [] : [[turn, hydrate(state.rounds[at])]]) };
24
+ applyUsageEvent(working, event);
25
+ const result = working.rounds.get(turn);
26
+ if (!result || (event.type === 'turn/end' && result.endReason === state.rounds[at].endReason)) return state;
27
+ const next = { ...result, calls: [...result.calls] };
28
+ const rounds = state.rounds.slice();
29
+ if (at < 0) rounds.push(next);
30
+ else rounds[at] = next;
31
+ return { ...state, rounds, last: working.last };
32
+ }
33
+
34
+ // Unlike usage accounting, opening text lives in its own session-only checkpoint.
35
+ // Keep the wire view stable when only the opening-input cursor changes.
36
+ const confirmation = z.strictObject({ turn: count, callId: z.string(), items: z.array(z.strictObject({ id:z.string(), question:z.string(), reply:z.string().nullable() })) });
37
+ const promptViewSchema = z.strictObject({ confirmations:z.array(confirmation).optional(), sessionId: z.string(), prompts: z.array(z.union([z.tuple([count, z.string()]), z.tuple([count, z.string(), z.enum(['agent-message', 'subagent-settled'])])])) });
38
+ const promptUnit = {
39
+ key: 'dshTokenVizPrompts', stateVersion: 3,
40
+ stateSchema: z.strictObject({ turn: count.nullable(), awaiting: z.boolean(), view: promptViewSchema }),
41
+ init: header => ({ turn: null, awaiting: false, view: { sessionId: header.id, prompts: [] } }),
42
+ apply: foldPrompt,
43
+ wire: { summary: false, viewSchema: promptViewSchema, view: state => state.view },
44
+ };
45
+
46
+ function jsonValue(value) {
47
+ if (typeof value !== 'string') return value;
48
+ try { return JSON.parse(value); } catch { return null; }
49
+ }
50
+ function foldConfirmation(state, event) {
51
+ const d = event.data, calls = state.view.confirmations ?? [];
52
+ const save = confirmations => ({...state, view:{...state.view, confirmations}});
53
+ if (event.type === 'tool/call') {
54
+ if (d.name !== 'ask_user_question' || calls.some(c=>c.callId===d.callId && c.turn===d.turn)) return state;
55
+ const qs=jsonValue(d.arguments)?.questions;
56
+ const items=Array.isArray(qs) ? qs.filter(q=>typeof q?.id==='string' && typeof q.question==='string').map(q=>({id:q.id,question:q.question,reply:null})) : [];
57
+ return save([...calls,{turn:d.turn,callId:d.callId,items}]);
58
+ }
59
+ const m=d.message, at=calls.findIndex(c=>c.turn===d.turn && c.callId===m?.toolCallId);
60
+ if (at<0 || m.isError) return state;
61
+ const answers=(m.content??[]).filter(b=>b.type==='text').flatMap(b=>{const a=jsonValue(b.text)?.answers;return Array.isArray(a)?a:[];});
62
+ const items=calls[at].items.map(q=>{
63
+ const a=answers.find(a=>a?.id===q.id);
64
+ if (!a || !Array.isArray(a.selected) || !a.selected.every(s=>typeof s==='string') || (a.custom!=null && typeof a.custom!=='string')) return q;
65
+ const reply=[...a.selected,a.custom].filter(s=>s?.trim()).join('\n');
66
+ return {...q,reply:reply||'已跳过,未提供答复'};
67
+ });
68
+ return save(calls.map((c,i)=>i===at?{...c,items}:c));
69
+ }
70
+ function foldPrompt(state, event) {
71
+ if (event.type==='tool/call' || event.type==='tool/result') return foldConfirmation(state,event);
72
+ if (event.type === 'turn/start') {
73
+ const turn = event.data.turn;
74
+ return state.turn !== null && turn <= state.turn ? state : { ...state, turn, awaiting: true };
75
+ }
76
+ if (!state.awaiting) return state;
77
+ // Only Step 1 can open the exchange. Notices may precede the first human
78
+ // input, but a later steering message must never become the turn's prompt.
79
+ if (['turn/end', 'step/end', 'assistant/message', 'assistant/attempt'].includes(event.type) ||
80
+ (event.type === 'step/start' && event.data.step !== 1)) {
81
+ return event.data.turn === state.turn ? { ...state, awaiting: false } : state;
82
+ }
83
+ if (event.type !== 'user/message' || event.surfaceOp !== 'append') return state;
84
+ const source = event.data.source?.kind;
85
+ if (!['user', 'agent-message', 'subagent-settled'].includes(source)) return state;
86
+ const text = event.data.content.filter(block => block.type === 'text').map(block => block.text).join('\n');
87
+ const view = text.trim() ? { ...state.view, prompts: [...state.view.prompts, source === 'user' ? [state.turn, text] : [state.turn, text, source]] } : state.view;
88
+ return { ...state, awaiting: false, view };
89
+ }
90
+
91
+ export const inject = ['sessionProjections'];
92
+ export async function apply(ctx, config = {}) {
93
+ const window = config.defaultWindow;
94
+ const defaultWindow = Number.isInteger(window) && window >= 1 && window <= 1000 ? window : 3;
95
+ await ctx.sessionProjections.register(promptUnit);
96
+ await ctx.sessionProjections.register({
97
+ key: 'dshTokenVizUsage', stateVersion: 2, stateSchema,
98
+ init: header => ({ sessionId: header.id, rounds: [], last: null }),
99
+ apply: fold,
100
+ wire: {
101
+ summary: false, viewSchema,
102
+ view(state) {
103
+ const rounds = new Map(state.rounds.map(item => [item.turn, { ...item, calls: new Map(item.calls) }]));
104
+ return { ...usageView({ sessionId: state.sessionId, rounds }), defaultWindow };
105
+ },
106
+ },
107
+ });
108
+ }
package/lib/usage.js ADDED
@@ -0,0 +1,95 @@
1
+ const FIELDS = ['inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens', 'reasoningTokens'];
2
+ const zeroUsage = () => Object.fromEntries(FIELDS.map(field => [field, 0]));
3
+
4
+ function normalizeUsage(value) {
5
+ if (!value || typeof value !== 'object') return null;
6
+ return Object.fromEntries(FIELDS.map(field => [field, Number.isFinite(value[field]) ? value[field] : 0]));
7
+ }
8
+
9
+ function eventUsage(event) {
10
+ const data = event.data;
11
+ if (event.type === 'assistant/message' && data.usage !== undefined) return normalizeUsage(data.usage);
12
+ const stream = data.stream || [];
13
+ for (let index = stream.length - 1; index >= 0; index -= 1) {
14
+ const record = stream[index];
15
+ if (record.type === 'chunk' && record.chunk.type === 'usage') return normalizeUsage(record.chunk.usage);
16
+ }
17
+ return null;
18
+ }
19
+
20
+ export function nativeTotal(usage) {
21
+ return usage.inputTokens + usage.outputTokens + usage.cacheReadTokens + usage.cacheWriteTokens;
22
+ }
23
+
24
+ export function createUsageState() {
25
+ return { rounds: new Map(), last: null, sessionId: undefined };
26
+ }
27
+
28
+ function ensureRound(state, turn) {
29
+ if (!state.rounds.has(turn)) state.rounds.set(turn, { turn, endReason: null, usage: zeroUsage(), samples: 0, calls: new Map() });
30
+ return state.rounds.get(turn);
31
+ }
32
+
33
+ function ensureCall(round, step) {
34
+ if (!round.calls.has(step)) round.calls.set(step, { known: false, missingAttempts: 0 });
35
+ return round.calls.get(step);
36
+ }
37
+
38
+ export function applyUsageEvent(state, event) {
39
+ const data = event?.data;
40
+ if (!data || data.turn === undefined) return state;
41
+ if (event.type === 'turn/start') {
42
+ ensureRound(state, data.turn);
43
+ return state;
44
+ }
45
+ if (event.type === 'turn/end') {
46
+ const round = state.rounds.get(data.turn);
47
+ const kind = data.reason?.kind;
48
+ if (round) round.endReason = kind === 'aborted' || kind === 'error' ? kind : null;
49
+ return state;
50
+ }
51
+ if (event.type === 'step/start') {
52
+ ensureCall(ensureRound(state, data.turn), data.step);
53
+ return state;
54
+ }
55
+ if (event.type === 'llm/retry-started') {
56
+ const call = ensureCall(ensureRound(state, data.turn), data.step);
57
+ if (!call.known) call.missingAttempts += 1;
58
+ call.known = false;
59
+ if (state.last?.turn === data.turn && state.last.step === data.step) state.last = null;
60
+ return state;
61
+ }
62
+ if (event.type !== 'assistant/message' && event.type !== 'assistant/attempt') return state;
63
+ const round = ensureRound(state, data.turn);
64
+ const call = ensureCall(round, data.step);
65
+ const usage = eventUsage(event);
66
+ if (!usage) return state;
67
+ const previous = state.last?.turn === data.turn && state.last.step === data.step ? state.last.usage : null;
68
+ for (const field of FIELDS) round.usage[field] += usage[field] - (previous?.[field] || 0);
69
+ if (!previous) round.samples += 1;
70
+ call.known = true;
71
+ state.last = { turn: data.turn, step: data.step, usage };
72
+ return state;
73
+ }
74
+
75
+ export function usageView(state) {
76
+ let cumulative = 0;
77
+ const rounds = [];
78
+ for (const round of state.rounds.values()) {
79
+ const missing = round.samples === 0;
80
+ const usage = missing ? null : { ...round.usage };
81
+ const total = missing ? null : nativeTotal(usage);
82
+ cumulative += total || 0;
83
+ const partial = !missing && [...round.calls.values()].some(call => !call.known || call.missingAttempts > 0);
84
+ const reasoning = usage ? Math.max(0, Math.min(usage.outputTokens, usage.reasoningTokens)) : 0;
85
+ const categories = usage ? [
86
+ { key: 'input', tokens: usage.inputTokens },
87
+ { key: 'output', tokens: usage.outputTokens - reasoning },
88
+ { key: 'cacheRead', tokens: usage.cacheReadTokens },
89
+ { key: 'cacheWrite', tokens: usage.cacheWriteTokens },
90
+ { key: 'reasoning', tokens: reasoning },
91
+ ].filter(item => item.tokens > 0) : [];
92
+ rounds.push({ turn: round.turn, endReason: round.endReason ?? null, number: rounds.length + 1, total, cumulative, usage, categories, missing, partial });
93
+ }
94
+ return { sessionId: state.sessionId, rounds, total: cumulative, hasMissing: rounds.some(round => round.missing || round.partial) };
95
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Token Usage",
4
+ "description": "Per-turn cumulative tokens, request usage and native usage breakdowns for Desktop sessions."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Token 消耗",
4
+ "description": "逐轮查看会话累计 Token、请求用量及原生 usage 字段分布。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,28 @@
1
1
  {
2
2
  "name": "dsh-token-viz",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "dependencies": { "zod": "4.6.6" },
5
+ "description": "Per-turn token usage charts for DSH Desktop sessions",
6
+ "type": "module",
7
+ "main": "./lib/index.js",
8
+ "exports": {
9
+ ".": "./lib/index.js",
10
+ "./client": "./lib/client.js",
11
+ "./locale/*.json": "./locale/*.json",
12
+ "./icon": "./icon.svg"
13
+ },
14
+ "files": ["lib", "locale", "icon.svg", "cordis.patch.yml", "README.md"],
15
+ "scripts": {
16
+ "test": "node --test --test-isolation=none",
17
+ "check": "node --check lib/index.js && node --check lib/usage.js && node --check lib/cache.js && node --check lib/client.js"
18
+ },
19
+ "engines": { "dsh": ">=0.2.2-rc.5", "node": ">=24.9.0" },
20
+ "dsh": {
21
+ "bundle": { "patch": "./cordis.patch.yml" },
22
+ "client": {
23
+ "platform": "web",
24
+ "immediately": true,
25
+ "inject": ["@deepseek-ai/dsh-client-ui-conversation"]
26
+ }
27
+ }
28
+ }