dsh-island 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,62 @@
1
+ <!doctype html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
5
+ <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'none'; object-src 'none'; base-uri 'none'">
6
+ <title>用量统计 · DeepSeek 灵动岛</title><link rel="stylesheet" href="stats.css">
7
+ </head>
8
+ <body>
9
+ <header class="top">
10
+ <div class="brand">
11
+ <span class="mark" aria-hidden="true"></span>
12
+ <div><h1>用量统计</h1><p id="source" class="sub">正在读取 Harness 会话记录…</p></div>
13
+ </div>
14
+ <div class="tabs" role="tablist" aria-label="时间范围">
15
+ <button role="tab" data-range="today" aria-selected="true">今天</button>
16
+ <button role="tab" data-range="7d" aria-selected="false">7 天</button>
17
+ <button role="tab" data-range="30d" aria-selected="false">30 天</button>
18
+ </div>
19
+ </header>
20
+
21
+ <main id="main" aria-busy="true">
22
+ <section class="kpis" aria-label="概览">
23
+ <div class="kpi"><span class="k">Tokens</span><strong id="k-tokens" class="num">—</strong><span id="k-tokens-sub" class="s"></span></div>
24
+ <div class="kpi"><span class="k">估算费用</span><strong id="k-cost" class="num">—</strong><span id="k-cost-sub" class="s"></span></div>
25
+ <div class="kpi"><span class="k">缓存命中</span><strong id="k-cache" class="num">—</strong><span class="s">命中部分按缓存价计费</span></div>
26
+ <div class="kpi"><span class="k">轮次</span><strong id="k-turns" class="num">—</strong><span id="k-turns-sub" class="s"></span></div>
27
+ <div class="kpi"><span class="k">工作时长</span><strong id="k-time" class="num">—</strong><span class="s">各轮耗时之和</span></div>
28
+ </section>
29
+
30
+ <section class="card chart-card">
31
+ <div class="card-head">
32
+ <h2 id="chart-title">按小时</h2>
33
+ <div class="legend" aria-label="图例">
34
+ <span><i style="--c:var(--s-cache)"></i>缓存命中</span>
35
+ <span><i style="--c:var(--s-input)"></i>未命中输入</span>
36
+ <span><i style="--c:var(--s-output)"></i>输出</span>
37
+ </div>
38
+ </div>
39
+ <div id="chart" class="chart"></div>
40
+ <div id="tip" class="tip" role="status" hidden></div>
41
+ </section>
42
+
43
+ <div class="cols">
44
+ <section class="card">
45
+ <div class="card-head"><h2>按模型</h2></div>
46
+ <table class="models"><thead><tr><th>模型</th><th class="r">Tokens</th><th class="r">≈ 费用</th><th class="r">轮次</th></tr></thead><tbody id="models"></tbody></table>
47
+ </section>
48
+ <section class="card">
49
+ <div class="card-head"><h2>按会话</h2><span class="hint">点开查看每一轮</span></div>
50
+ <div id="sessions" class="sessions"></div>
51
+ </section>
52
+ </div>
53
+
54
+ <p id="empty" class="empty" hidden>这段时间还没有完成的轮次。</p>
55
+ <footer class="note">
56
+ 费用为估算:按 <a id="price-link" href="https://api-docs.deepseek.com/zh-cn/quick_start/pricing" target="_blank" rel="noreferrer">DeepSeek 官方价格</a>(2026-10-27 查询,人民币)和每次调用的时间计算,
57
+ 高峰时段(北京时间工作日 9–12 点、14–18 点)按高峰价;法定节假日无法识别,按工作日计。未命中缓存的输入(含写入缓存)按未命中价,输出含思考内容。
58
+ 没有官方价格的模型不计入费用。实际扣费以 DeepSeek 账单为准。
59
+ </footer>
60
+ </main>
61
+ <script src="stats.js"></script>
62
+ </body></html>
@@ -0,0 +1,147 @@
1
+ // 用量统计窗口:今天按小时、7/30 天按天;按模型、按会话(可展开到每一轮)。数据来自 Harness 会话记录。
2
+ const api = window.usageStats;
3
+ const $ = id => document.getElementById(id);
4
+ const NS = 'http://www.w3.org/2000/svg';
5
+ const SERIES = [['cacheRead', '缓存命中', 'var(--s-cache)'], ['input', '未命中输入', 'var(--s-input)'], ['output', '输出', 'var(--s-output)']];
6
+ let range = 'today', data = null;
7
+
8
+ const tokens = n => !n ? '0' : n < 1000 ? String(Math.round(n)) : n < 1e6 ? `${(n / 1000).toFixed(n < 1e4 ? 1 : 0)}K` : n < 1e9 ? `${(n / 1e6).toFixed(n < 1e7 ? 2 : 1)}M` : `${(n / 1e9).toFixed(2)}B`;
9
+ const money = n => n == null ? '—' : n === 0 ? '¥0' : n < 0.01 ? '<¥0.01' : `¥${n.toFixed(n < 100 ? 2 : 0)}`;
10
+ const duration = ms => { const m = Math.round(ms / 60000); return m < 1 ? '不到 1 分钟' : m < 60 ? `${m} 分钟` : `${Math.floor(m / 60)} 小时 ${m % 60} 分`; };
11
+ const clock = t => { const d = new Date(t), hm = `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`; return d.toDateString() === new Date().toDateString() ? hm : `${d.getMonth() + 1}/${d.getDate()} ${hm}`; };
12
+ const shortModel = m => m ? m.replace(/^deepseek-/i, '') : '—';
13
+ const el = (tag, attrs = {}, ...children) => {
14
+ const node = tag.startsWith('svg:') ? document.createElementNS(NS, tag.slice(4)) : document.createElement(tag);
15
+ for (const [k, v] of Object.entries(attrs)) if (v != null && v !== false) k === 'text' ? node.textContent = v : node.setAttribute(k, v);
16
+ node.append(...children.filter(c => c != null));
17
+ return node;
18
+ };
19
+
20
+ function load(next) {
21
+ range = next;
22
+ for (const b of document.querySelectorAll('.tabs button')) b.setAttribute('aria-selected', String(b.dataset.range === range));
23
+ $('main').setAttribute('aria-busy', 'true');
24
+ api.request(range);
25
+ }
26
+ for (const b of document.querySelectorAll('.tabs button')) b.addEventListener('click', () => load(b.dataset.range));
27
+ document.querySelector('.tabs').addEventListener('keydown', e => {
28
+ const order = ['today', '7d', '30d'], i = order.indexOf(range);
29
+ if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') { const n = order[(i + (e.key === 'ArrowRight' ? 1 : 2)) % 3]; load(n); document.querySelector(`[data-range="${n}"]`).focus(); }
30
+ });
31
+
32
+ /** A bar segment with only its top corners rounded. */
33
+ function topRounded(x, y, w, h, r) {
34
+ r = Math.min(r, w / 2, h);
35
+ return `M${x},${y + h}V${y + r}Q${x},${y} ${x + r},${y}H${x + w - r}Q${x + w},${y} ${x + w},${y + r}V${y + h}Z`;
36
+ }
37
+ function niceMax(v) { if (v <= 0) return 1; const p = 10 ** Math.floor(Math.log10(v)), f = v / p; return (f <= 1 ? 1 : f <= 2 ? 2 : f <= 2.5 ? 2.5 : f <= 5 ? 5 : 10) * p; }
38
+
39
+ function renderChart(d) {
40
+ const box = $('chart'), W = Math.max(320, box.clientWidth - 8), H = box.clientHeight - 6;
41
+ const left = 46, bottom = 22, top = 8, plotW = W - left - 6, plotH = H - top - bottom;
42
+ const totals = d.buckets.map(b => b.cacheRead + b.input + b.output), max = niceMax(Math.max(...totals, 1000));
43
+ const svg = el('svg:svg', { viewBox: `0 0 ${W} ${H}`, role: 'img', 'aria-label': `${$('chart-title').textContent}的 tokens 用量` });
44
+ for (let i = 0; i <= 4; i++) {
45
+ const y = top + plotH - plotH * i / 4;
46
+ svg.append(el('svg:line', { class: 'grid', x1: left, x2: W - 6, y1: y, y2: y }));
47
+ svg.append(el('svg:text', { class: 'axis', x: left - 8, y: y + 3.5, 'text-anchor': 'end', text: tokens(max * i / 4) }));
48
+ }
49
+ const n = d.buckets.length, slot = plotW / n, bw = Math.max(3, Math.min(26, slot * 0.62));
50
+ const every = d.byHour ? 3 : n > 10 ? 5 : 1;
51
+ d.buckets.forEach((b, i) => {
52
+ const x = left + slot * i + (slot - bw) / 2, g = el('svg:g', { class: 'col', 'data-i': i });
53
+ let y = top + plotH;
54
+ const parts = SERIES.map(([k, , c]) => [b[k], c]).filter(([v]) => v > 0);
55
+ parts.forEach(([v, c], j) => {
56
+ const h = Math.max(1.5, v / max * plotH), gap = j > 0 ? 2 : 0, last = j === parts.length - 1;
57
+ y -= h;
58
+ const segH = Math.max(0.5, h - gap);
59
+ g.append(last ? el('svg:path', { class: 'seg', d: topRounded(x, y, bw, segH, 4), fill: c, style: `animation-delay:${i * 14}ms` })
60
+ : el('svg:rect', { class: 'seg', x, y, width: bw, height: segH, fill: c, style: `animation-delay:${i * 14}ms` }));
61
+ });
62
+ g.append(el('svg:rect', { class: 'hit', x: left + slot * i, y: top, width: slot, height: plotH, tabindex: '0', 'aria-label': `${b.label}:${tokens(totals[i])} tokens` }));
63
+ svg.append(g);
64
+ if (i % every === 0 || (!d.byHour && i === n - 1)) svg.append(el('svg:text', { class: 'axis', x: left + slot * i + slot / 2, y: H - 6, 'text-anchor': 'middle', text: b.label }));
65
+ });
66
+ const show = (i, anchor) => {
67
+ const b = d.buckets[i]; if (!b) return;
68
+ for (const g of svg.querySelectorAll('.col')) g.classList.toggle('dim', g.dataset.i !== String(i));
69
+ const tip = $('tip');
70
+ tip.replaceChildren(el('b', { text: d.byHour ? `${b.label} – ${Number(b.label.split(':')[0]) + 1}:00` : b.label }),
71
+ ...SERIES.map(([k, label, c]) => el('div', { class: 'r' }, el('span', {}, el('i', { style: `--c:${c}` }), label), el('span', { text: tokens(b[k]) }))),
72
+ el('div', { class: 'r' }, el('span', { text: '≈ 费用' }), el('span', { text: money(b.cost) })),
73
+ el('div', { class: 'r' }, el('span', { text: '轮次' }), el('span', { text: String(b.turns) })));
74
+ tip.hidden = false;
75
+ const card = box.parentElement.getBoundingClientRect(), r = anchor.getBoundingClientRect();
76
+ let x = r.left - card.left + r.width / 2 + 12;
77
+ if (x + tip.offsetWidth > card.width - 8) x = r.left - card.left + r.width / 2 - tip.offsetWidth - 12;
78
+ tip.style.left = `${Math.max(8, x)}px`; tip.style.top = `${box.offsetTop + 10}px`;
79
+ };
80
+ const hide = () => { $('tip').hidden = true; for (const g of svg.querySelectorAll('.col')) g.classList.remove('dim'); };
81
+ svg.addEventListener('pointerover', e => { const g = e.target.closest('.col'); if (g) show(Number(g.dataset.i), g.querySelector('.hit')); });
82
+ svg.addEventListener('pointerleave', hide);
83
+ svg.addEventListener('focusin', e => { const g = e.target.closest('.col'); if (g) show(Number(g.dataset.i), e.target); });
84
+ svg.addEventListener('focusout', hide);
85
+ box.replaceChildren(svg);
86
+ }
87
+
88
+ function renderModels(d) {
89
+ const max = Math.max(...d.models.map(m => m.tokens), 1);
90
+ $('models').replaceChildren(...d.models.map(m => el('tr', {},
91
+ el('td', {}, el('div', { class: 'name' }, el('span', { text: m.model }), el('div', { class: 'share' }, el('i', { style: `width:${Math.max(2, m.tokens / max * 100)}%` })))),
92
+ el('td', { class: 'r', text: tokens(m.tokens) }),
93
+ el('td', { class: 'r' }, m.priced ? money(m.cost) : el('span', { class: 'unpriced', text: '无官方价格' })),
94
+ el('td', { class: 'r', text: String(m.turns) }))));
95
+ }
96
+
97
+ const STATE = { completed: '完成', paused: '已停止', error: '出错' };
98
+ function renderSessions(d) {
99
+ const open = new Set([...document.querySelectorAll('.sessions details[open]')].map(x => x.dataset.id));
100
+ $('sessions').replaceChildren(...d.sessions.map(s => {
101
+ const rows = s.items.map(t => el('tr', {},
102
+ el('td', {}, el('span', { class: `state ${t.state}`, title: STATE[t.state] ?? t.state }), clock(t.end)),
103
+ el('td', { text: shortModel(t.model), title: t.model || '' }),
104
+ el('td', { class: 'r', text: `${t.calls} · ${t.tools}`, title: `模型调用 ${t.calls} 次,工具 ${t.tools} 次` }),
105
+ el('td', { class: 'r', text: tokens(t.cacheRead) }),
106
+ el('td', { class: 'r', text: tokens(t.input) }),
107
+ el('td', { class: 'r', text: tokens(t.output) }),
108
+ el('td', { class: 'r', text: t.priced ? money(t.cost) : '—' })));
109
+ const table = el('table', { class: 'turns' },
110
+ el('thead', {}, el('tr', {}, ...['结束', '模型', '调用·工具', '命中', '未命中', '输出', '≈ 费用'].map((h, i) => el('th', { class: i > 1 ? 'r' : null, text: h })))),
111
+ el('tbody', {}, ...rows));
112
+ const node = el('details', { 'data-id': s.id },
113
+ el('summary', {}, el('span', { class: 't', text: s.title || '未命名会话', title: s.title || '' }), el('span', { class: 'm', text: `${s.turns} 轮 · ${tokens(s.tokens)}` }), el('span', { class: 'm', text: money(s.cost) })),
114
+ table);
115
+ if (open.has(s.id)) node.open = true;
116
+ return node;
117
+ }));
118
+ }
119
+
120
+ function render(d) {
121
+ $('main').setAttribute('aria-busy', 'false');
122
+ if (!d) { $('source').textContent = '暂时无法读取统计,请确认 Harness 正在运行。'; return; }
123
+ if (d.range !== range) return;
124
+ $('chart').classList.toggle('still', data?.range === d.range);
125
+ data = d;
126
+ const t = d.totals;
127
+ $('source').replaceChildren(document.createTextNode(`来自 Harness 会话记录 · 已读取 ${d.scanned} 个会话`));
128
+ if (d.preview) $('source').append(el('span', { class: 'tag', text: '预览 · 示例数据' }));
129
+ $('chart-title').textContent = d.byHour ? '今天 · 按小时' : `最近 ${d.buckets.length} 天 · 按天`;
130
+ $('k-tokens').textContent = tokens(t.tokens);
131
+ $('k-tokens-sub').textContent = `输入 ${tokens(t.input + t.cacheRead)} · 输出 ${tokens(t.output)}`;
132
+ $('k-cost').textContent = t.cost > 0 || !t.unpricedTokens ? `≈${money(t.cost)}` : '—';
133
+ $('k-cost-sub').textContent = t.unpricedTokens ? `另有 ${tokens(t.unpricedTokens)} 无官方价格` : '按官方价格估算';
134
+ $('k-cache').textContent = t.cacheRate == null ? '—' : `${t.cacheRate}%`;
135
+ $('k-turns').textContent = String(t.turns);
136
+ $('k-turns-sub').textContent = t.turns ? `完成 ${t.completed} · 其他 ${t.turns - t.completed}` : '';
137
+ $('k-time').textContent = duration(t.ms);
138
+ $('empty').hidden = t.turns > 0;
139
+ renderChart(d); renderModels(d); renderSessions(d);
140
+ }
141
+
142
+ api.subscribe(render);
143
+ let resizeFrame;
144
+ addEventListener('resize', () => { cancelAnimationFrame(resizeFrame); resizeFrame = requestAnimationFrame(() => { if (!data) return; $('chart').classList.add('still'); renderChart(data); }); });
145
+ load('today');
146
+ // 打开期间每分钟刷新一次。
147
+ setInterval(() => { if (document.visibilityState === 'visible') api.request(range); }, 60000);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-island",
3
- "version": "0.4.0",
4
- "description": "DeepSeek Harness 桌面灵动岛插件:实时任务状态、任务控制台、在灵动岛回答 Agent 提问(社区插件)",
3
+ "version": "0.5.0",
4
+ "description": "DeepSeek Harness 桌面灵动岛插件:实时任务状态、上下文占用、在灵动岛批准权限与回答提问、用量与费用统计(社区插件)",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "main": "src/host.js",
@@ -0,0 +1,89 @@
1
+ // 在灵动岛里批准或拒绝权限请求(ctx.approval → `approval/request` waterfall)。
2
+ //
3
+ // 灵动岛在 waterfall 最前面挂一个监听,与 Harness 窗口里的审批卡“赛跑”,先答者生效。
4
+ // 往下游传的 signal 换成“原信号 或 灵动岛已作答”的组合:灵动岛先答时中止它,Harness 的审批卡随之撤下,
5
+ // 不会一直占着输入框。只给顶层任务用;只提供“允许一次”和“拒绝”,持久授权仍在 Harness 中设置。
6
+ import { randomUUID } from 'node:crypto';
7
+
8
+ const clip = (value, max) => typeof value === 'string' ? value.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g, ' ').trim().slice(0, max) : '';
9
+ const OUTCOMES = new Set(['allowed-once', 'rejected']);
10
+
11
+ /** What a tool call wants to do, for display: a command, a file, a URL or a short argument digest. */
12
+ export function summarizeCall(name, argumentsText) {
13
+ let args;
14
+ try { args = typeof argumentsText === 'string' ? JSON.parse(argumentsText) : argumentsText; } catch { return argumentsText ? { label: '参数', text: clip(String(argumentsText), 600) } : null; }
15
+ if (!args || typeof args !== 'object') return null;
16
+ const pick = (...keys) => { for (const k of keys) if (typeof args[k] === 'string' && args[k].trim()) return args[k]; return ''; };
17
+ const command = pick('command', 'cmd', 'script', 'code');
18
+ const path = pick('path', 'file_path', 'filePath', 'file', 'target');
19
+ const url = pick('url', 'uri');
20
+ if (/^(bash|pwsh|powershell|terminal_send|terminal_open|shell)$/i.test(name) && command) return { label: '命令', text: clip(command, 600), mono: true };
21
+ if (path) return { label: /write|edit|replace|create|delete|remove/i.test(name + ' ' + (args.command ?? '')) ? '修改文件' : '文件', text: clip(path, 300), mono: true, extra: command && command !== path ? clip(command, 40) : '' };
22
+ if (url) return { label: '网址', text: clip(url, 300), mono: true };
23
+ if (command) return { label: '命令', text: clip(command, 600), mono: true };
24
+ const first = Object.entries(args).find(([, v]) => typeof v === 'string' && v.trim());
25
+ return first ? { label: first[0], text: clip(first[1], 400), mono: false } : null;
26
+ }
27
+
28
+ /** Find the tool call an approval is about, scanning back from the end of the session log. */
29
+ export function callDetail(session, callId) {
30
+ if (!callId || typeof session?.eventAt !== 'function' || !Number.isInteger(session.seq)) return null;
31
+ for (let seq = session.seq - 1, n = 0; seq >= 0 && n < 500; seq -= 1, n += 1) {
32
+ let event; try { event = session.eventAt(seq); } catch { return null; }
33
+ if (event?.type === 'tool/call' && event.data?.callId === callId) return summarizeCall(event.data.name, event.data.arguments);
34
+ }
35
+ return null;
36
+ }
37
+
38
+ export class ApprovalDesk {
39
+ constructor(ctx, onChange = () => {}) { this.ctx = ctx; this.onChange = onChange; this.pending = new Map(); this.enabled = true; }
40
+ attach() {
41
+ const desk = this;
42
+ return this.ctx.on('approval/request', function (request, next) { return desk.intercept(request, next); }, { global: true, prepend: true });
43
+ }
44
+ isRoot(agent) {
45
+ try { const agents = this.ctx.get?.('agents'); return !!agents && (agents.roots?.() ?? []).includes(agent); } catch { return false; }
46
+ }
47
+ intercept(request, next) {
48
+ if (!this.enabled || !request?.agent?.session || request.signal?.aborted || !this.isRoot(request.agent)) return next();
49
+ const original = request.signal, retire = new AbortController();
50
+ const combined = original ? AbortSignal.any([original, retire.signal]) : retire.signal;
51
+ try { request.signal = combined; } catch { return next(); }
52
+ if (request.signal !== combined) return next();
53
+ const id = randomUUID();
54
+ return new Promise(resolve => {
55
+ let done = false;
56
+ const finish = (outcome, fromIsland) => {
57
+ if (done) return;
58
+ done = true; this.pending.delete(id); original?.removeEventListener?.('abort', onAbort); this.onChange(); resolve(outcome);
59
+ // The island answered: retire Harness's own card so it does not hold the composer.
60
+ if (fromIsland) retire.abort(new Error('answered in the island'));
61
+ };
62
+ const onAbort = () => finish('cancelled', false);
63
+ original?.addEventListener?.('abort', onAbort, { once: true });
64
+ this.pending.set(id, {
65
+ id, agent: request.agent, sessionId: request.agent.session.id, at: Date.now(),
66
+ toolName: clip(request.toolName, 60), reason: clip(request.displayReason || request.reason, 300),
67
+ detail: callDetail(request.agent.session, request.callId),
68
+ decide: outcome => finish(outcome, true)
69
+ });
70
+ this.onChange();
71
+ let downstream;
72
+ try { downstream = Promise.resolve(next()); } catch { downstream = Promise.resolve('unavailable'); }
73
+ // Harness's own card answered first. `unavailable` means no window is open: the island keeps asking.
74
+ downstream.then(outcome => { if (outcome !== 'unavailable') finish(outcome, false); }, () => {});
75
+ });
76
+ }
77
+ list() {
78
+ if (!this.enabled) return [];
79
+ return [...this.pending.values()].map(({ id, sessionId, at, toolName, reason, detail }) => ({ id, sessionId, at, toolName, reason, detail })).slice(0, 4);
80
+ }
81
+ /** @returns `{ ok }` or `{ ok: false, reason }`. */
82
+ decide(id, outcome) {
83
+ const entry = this.pending.get(id);
84
+ if (!entry) return { ok: false, reason: '这个请求已经处理过或已取消' };
85
+ if (!OUTCOMES.has(outcome)) return { ok: false, reason: '无效的决定' };
86
+ entry.decide(outcome);
87
+ return { ok: true };
88
+ }
89
+ }
package/src/host.js CHANGED
@@ -7,6 +7,8 @@ import { ActivityStore } from './state.js';
7
7
  import { runtimePath } from './runtime.js';
8
8
  import { Config, readPrefs } from './settings.js';
9
9
  import { QuestionDesk } from './questions.js';
10
+ import { ApprovalDesk } from './approvals.js';
11
+ import { UsageLedger } from './usage.js';
10
12
 
11
13
  export { Config };
12
14
  export const name = 'dsh-island';
@@ -41,13 +43,31 @@ export function stopSession(ctx, sessionId) {
41
43
  return true;
42
44
  }
43
45
 
46
+ /** Context pressure from Harness's own token-meter projection, when the session is live. */
47
+ function contextFromProjection(ctx, sessionId) {
48
+ try {
49
+ const session = ctx.agents.get?.(sessionId)?.session;
50
+ const view = session && ctx.get?.('sessionProjections')?.stateOf?.(session, 'contextPressure');
51
+ return view && typeof view === 'object' ? view : null;
52
+ } catch { return null; }
53
+ }
54
+
44
55
  /** Snapshot sent to the island: top-level tasks only, plus sub-agents that need the user. */
45
- export function islandSnapshot(ctx, store, known, desk) {
56
+ export function islandSnapshot(ctx, store, known, desk, extra = {}) {
46
57
  const roots = rootsOf(ctx);
47
58
  for (const agent of roots) if (agent?.session?.id) known.add(agent.session.id);
48
59
  const data = store.snapshot(id => known.size === 0 || known.has(id));
49
- data.questions = desk ? desk.list(roots).map(q => ({ ...q, title: store.sessions.get(q.sessionId)?.title ?? '' })) : [];
60
+ const title = id => store.sessions.get(id)?.title ?? '';
61
+ data.questions = desk ? desk.list(roots).map(q => ({ ...q, title: title(q.sessionId) })) : [];
62
+ data.approvals = extra.approvals ? extra.approvals.list().map(a => ({ ...a, title: title(a.sessionId) })) : [];
50
63
  data.stoppable = Boolean(data.sessionId && !['completed','paused','error','idle'].includes(data.state) && roots.some(a => a?.session?.id === data.sessionId));
64
+ if (data.detail) {
65
+ const view = contextFromProjection(ctx, data.sessionId);
66
+ if (view?.contextWindow) data.detail.contextWindow = view.contextWindow;
67
+ if (Number.isFinite(view?.projectedTokens) || Number.isFinite(view?.pressureTokens)) data.detail.contextTokens = view.projectedTokens ?? view.pressureTokens;
68
+ if (extra.prefs && extra.prefs.details === false) data.detail.reply = '';
69
+ }
70
+ if (extra.usage) data.usage = extra.usage;
51
71
  return data;
52
72
  }
53
73
 
@@ -81,14 +101,31 @@ export function apply(ctx, config = {}) {
81
101
  ctx.effect(() => {
82
102
  let child, last = '', stopped = false, pending, prefs = readPrefs(config);
83
103
  const store = new ActivityStore(), known = new Set();
104
+ const env={...process.env}; delete env.ELECTRON_RUN_AS_NODE;
105
+ const dataDir = read('dataDir') || join(env.DSH_HOME || join(homedir(),'.dsh'),'dsh-island');
84
106
  const desk = new QuestionDesk(ctx, () => publish());
85
107
  desk.enabled = prefs.questions;
86
108
  const offDesk = desk.attach();
109
+ const approvals = new ApprovalDesk(ctx, () => publish());
110
+ approvals.enabled = prefs.approvals;
111
+ const offApprovals = approvals.attach();
112
+ // 用量账本:实时事件 + 历史会话补算(通过 Harness 的 sessionQuery,读一次即缓存)。
113
+ const ledger = new UsageLedger({ file: join(dataDir, 'usage.json') }).load();
114
+ const offLedger = ctx.on('session/event', (session, event) => ledger.ingest(session?.id, event), { global: true });
115
+ let usage, usageAt = 0, usageVersion = -1;
116
+ const usageNow = () => {
117
+ if (ledger.version !== usageVersion || Date.now() - usageAt > 60000) { usage = ledger.panel(); usageAt = Date.now(); usageVersion = ledger.version; }
118
+ return usage;
119
+ };
120
+ const backfillAbort = new AbortController();
121
+ const backfill = () => { const query = ctx.get?.('sessionQuery'); ledger.backfill(query, { signal: backfillAbort.signal }).then(n => { if (n) publish(); }, () => {}); };
122
+ const backfillFirst = setTimeout(backfill, 8000); backfillFirst.unref?.();
123
+ const backfillTimer = setInterval(backfill, 30 * 60000); backfillTimer.unref?.();
87
124
  const message = value => { if (!stopped && child?.connected) child.send(value, () => {}); };
88
125
  const send = () => {
89
126
  pending = undefined;
90
127
  if (stopped || !child?.connected) return;
91
- const data=islandSnapshot(ctx,store,known,desk), encoded=JSON.stringify(data);
128
+ const data=islandSnapshot(ctx,store,known,desk,{approvals,prefs,usage:usageNow()}), encoded=JSON.stringify(data);
92
129
  if(encoded===last)return;
93
130
  last=encoded;
94
131
  child.send({type:'activity',data}, error=>{ if(error) last=''; });
@@ -109,12 +146,10 @@ export function apply(ctx, config = {}) {
109
146
  const next = readPrefs(config);
110
147
  if (next.enabled && !prefs.enabled) message({ type: 'show' });
111
148
  const balanceChanged = next.balance !== prefs.balance;
112
- prefs = next; desk.enabled = prefs.questions; message({ type: 'prefs', data: prefs }); publish();
149
+ prefs = next; desk.enabled = prefs.questions; approvals.enabled = prefs.approvals; message({ type: 'prefs', data: prefs }); publish();
113
150
  if (balanceChanged) refreshBalance(true);
114
151
  });
115
152
  try {
116
- const env={...process.env}; delete env.ELECTRON_RUN_AS_NODE;
117
- const dataDir = read('dataDir') || join(env.DSH_HOME || join(homedir(),'.dsh'),'dsh-island');
118
153
  child=spawn(runtimePath(env),[fileURLToPath(new URL('../desktop/main.cjs',import.meta.url)),`--island-data=${dataDir}`],{
119
154
  env, windowsHide:true, stdio:['ignore','ignore','pipe','ipc']
120
155
  });
@@ -125,11 +160,13 @@ export function apply(ctx, config = {}) {
125
160
  if(msg?.type==='panel-open') refreshBalance();
126
161
  if(msg?.type==='answer' && typeof msg.callId==='string'){ const result = desk.answer(msg.callId, msg.answers, rootsOf(ctx)); message({ type: 'answer-result', callId: msg.callId, ...result }); publish(); }
127
162
  if(msg?.type==='stop' && stopSession(ctx, msg.sessionId)) publish();
163
+ if(msg?.type==='approve' && typeof msg.id==='string'){ const result = approvals.decide(msg.id, msg.outcome); message({ type: 'approval-result', id: msg.id, ...result }); publish(); }
164
+ if(msg?.type==='stats'){ message({ type: 'stats', data: ledger.stats(['today','7d','30d'].includes(msg.range) ? msg.range : '7d') }); if (!ledger.sessions.size) backfill(); }
128
165
  });
129
166
  child.on('exit',code=>{ if(!stopped && code)ctx.logger.warn(`灵动岛窗口已退出 (${code}),重新启用插件可恢复。`); });
130
167
  } catch(error) { ctx.logger.warn(error.message); }
131
168
  const timer=setInterval(publish,1000); timer.unref();
132
169
  const balanceTimer=setInterval(() => refreshBalance(true), 10 * 60000); balanceTimer.unref();
133
- return () => { stopped=true; detach(); offDesk?.(); offSettings?.(); clearInterval(timer); clearInterval(balanceTimer); clearTimeout(pending); if(child?.connected)child.send({type:'shutdown'}); setTimeout(()=>{if(child?.exitCode===null)child.kill();},1500).unref(); };
170
+ return () => { stopped=true; detach(); offDesk?.(); offApprovals?.(); offLedger?.(); backfillAbort.abort(); clearTimeout(backfillFirst); clearInterval(backfillTimer); ledger.save(); offSettings?.(); clearInterval(timer); clearInterval(balanceTimer); clearTimeout(pending); if(child?.connected)child.send({type:'shutdown'}); setTimeout(()=>{if(child?.exitCode===null)child.kill();},1500).unref(); };
134
171
  });
135
172
  }
package/src/pricing.js ADDED
@@ -0,0 +1,42 @@
1
+ // DeepSeek 官方 API 价格(人民币 / 百万 tokens),用于估算费用。
2
+ // 来源:https://api-docs.deepseek.com/zh-cn/quick_start/pricing (2026-10-27 查询)。价格可能调整,估算仅供参考。
3
+ // 高峰时段:北京时间周一至周五 9:00–12:00、14:00–18:00;其余为空闲时段(法定节假日无法自动识别,按工作日计)。
4
+ export const PRICES_AS_OF = '2026-10-27';
5
+ export const PRICE_SOURCE = 'https://api-docs.deepseek.com/zh-cn/quick_start/pricing';
6
+
7
+ const TABLE = {
8
+ 'deepseek-flash': { offPeak: { hit: 0.02, miss: 1, out: 4 }, peak: { hit: 0.04, miss: 2, out: 8 } },
9
+ 'deepseek-v4-pro': { offPeak: { hit: 0.15, miss: 4.5, out: 13.5 }, peak: { hit: 0.30, miss: 9, out: 27 } }
10
+ };
11
+ // 已下线、但仍按 Flash 计费的旧模型名。
12
+ const ALIASES = { 'deepseek-v4-flash': 'deepseek-flash', 'deepseek-v4-flash-vision-exp': 'deepseek-flash' };
13
+
14
+ /** The priced model id for a model name, or null when no official price is known. */
15
+ export function pricedModel(model) {
16
+ if (typeof model !== 'string') return null;
17
+ const id = model.trim().toLowerCase();
18
+ if (TABLE[id]) return id;
19
+ if (ALIASES[id]) return ALIASES[id];
20
+ return null;
21
+ }
22
+
23
+ /** Whether a moment falls in DeepSeek's peak period (Beijing time, weekdays 9–12 and 14–18). */
24
+ export function isPeak(time) {
25
+ const beijing = new Date(time + 8 * 3600e3);
26
+ const day = beijing.getUTCDay(), minutes = beijing.getUTCHours() * 60 + beijing.getUTCMinutes();
27
+ if (day === 0 || day === 6) return false;
28
+ return (minutes >= 540 && minutes < 720) || (minutes >= 840 && minutes < 1080);
29
+ }
30
+
31
+ /**
32
+ * Estimated cost in CNY of one model call.
33
+ * Harness usage: inputTokens are uncached prompt tokens, cacheReadTokens hit the cache,
34
+ * cacheWriteTokens are billed as cache misses, outputTokens include reasoning.
35
+ * @returns the cost, or null when the model has no official price.
36
+ */
37
+ export function estimateCost({ model, time, inputTokens = 0, cacheReadTokens = 0, cacheWriteTokens = 0, outputTokens = 0 }) {
38
+ const id = pricedModel(model);
39
+ if (!id) return null;
40
+ const p = TABLE[id][isPeak(time) ? 'peak' : 'offPeak'];
41
+ return ((inputTokens + cacheWriteTokens) * p.miss + cacheReadTokens * p.hit + outputTokens * p.out) / 1e6;
42
+ }
package/src/settings.js CHANGED
@@ -4,7 +4,7 @@ import { dirname, join } from 'node:path';
4
4
  // 灵动岛在 Harness「设置 › 灵动岛」中的选项。字段都是 volatile:修改后即时生效,不重启插件。
5
5
  export const POSITIONS = ['top-center', 'top-left', 'top-right', 'left-center', 'right-center', 'bottom-center'];
6
6
  export const SIZES = { small: 0.85, medium: 1, large: 1.15 };
7
- export const DEFAULT_PREFS = { enabled: true, position: 'top-center', size: 'medium', reduceMotion: false, popups: true, details: true, balance: true, questions: true };
7
+ export const DEFAULT_PREFS = { enabled: true, position: 'top-center', size: 'medium', reduceMotion: false, popups: true, details: true, balance: true, questions: true, approvals: true, hoverExpand: true };
8
8
 
9
9
  async function loadSchemastery() {
10
10
  try { const m = await import('@deepseek-ai/schemastery'); return m.default ?? m; } catch {}
@@ -29,6 +29,8 @@ export const Config = z ? z.object({
29
29
  details: z.boolean().default(true).description('在灵动岛中显示任务标题、计划与工具').volatile(),
30
30
  balance: z.boolean().default(true).description('空闲时显示 DeepSeek 账户余额').volatile(),
31
31
  questions: z.boolean().default(true).description('在灵动岛中回答 Agent 的提问').volatile(),
32
+ approvals: z.boolean().default(true).description('在灵动岛中批准或拒绝权限请求').volatile(),
33
+ hoverExpand: z.boolean().default(true).description('鼠标停留时直接展开面板').volatile(),
32
34
  allowStandalone: z.boolean().default(false).hidden(),
33
35
  dataDir: z.string().hidden()
34
36
  }) : undefined;
@@ -44,6 +46,6 @@ export function readPrefs(config = {}) {
44
46
  }
45
47
  if (!POSITIONS.includes(prefs.position)) prefs.position = DEFAULT_PREFS.position;
46
48
  if (!Object.hasOwn(SIZES, prefs.size)) prefs.size = DEFAULT_PREFS.size;
47
- for (const key of ['enabled', 'reduceMotion', 'popups', 'details', 'balance', 'questions']) prefs[key] = prefs[key] !== false && prefs[key] !== 'false' ? Boolean(prefs[key]) : false;
49
+ for (const key of ['enabled', 'reduceMotion', 'popups', 'details', 'balance', 'questions', 'approvals', 'hoverExpand']) prefs[key] = prefs[key] !== false && prefs[key] !== 'false' ? Boolean(prefs[key]) : false;
48
50
  return prefs;
49
51
  }
package/src/state.js CHANGED
@@ -25,7 +25,7 @@ export class ActivityStore {
25
25
  if (!this.sessions.has(id)) this.sessions.set(id, {
26
26
  id, state: 'idle', title: '', updated: this.now(), started: 0, ended: 0,
27
27
  tools: new Map(), approvals: new Set(), questions: new Set(),
28
- todos: [], trail: [], toolCount: 0, model: '', contextTokens: 0, inputTokens: 0, cacheTokens: 0, outputTokens: 0
28
+ todos: [], trail: [], toolCount: 0, model: '', contextTokens: 0, contextWindow: 0, inputTokens: 0, cacheTokens: 0, outputTokens: 0, lastText: '', reply: ''
29
29
  });
30
30
  return this.sessions.get(id);
31
31
  }
@@ -42,7 +42,7 @@ export class ActivityStore {
42
42
  case 'session/title': e.title = clip(d.title); break;
43
43
  case 'turn/start':
44
44
  e.tools.clear(); e.approvals.clear(); e.questions.clear();
45
- e.trail = []; e.toolCount = 0; e.inputTokens = 0; e.cacheTokens = 0; e.outputTokens = 0;
45
+ e.trail = []; e.toolCount = 0; e.inputTokens = 0; e.cacheTokens = 0; e.outputTokens = 0; e.lastText = ''; e.reply = '';
46
46
  this.set(id, 'thinking', { started: this.now(), ended: 0, updated: this.now() }); break;
47
47
  case 'step/start': if (!e.approvals.size && !e.questions.size) this.set(id, 'thinking'); break;
48
48
  case 'tool/call': {
@@ -73,7 +73,10 @@ export class ActivityStore {
73
73
  break;
74
74
  case 'model/selection': { const m = typeof d.model === 'string' ? d.model : d.model?.id ?? d.selection?.model; if (typeof m === 'string') e.model = clip(m, 40); break; }
75
75
  case 'assistant/attempt': if (typeof d.source?.model === 'string') e.model = clip(d.source.model, 40); break;
76
+ case 'request/context': if (Number.isFinite(d.contextWindow) && d.contextWindow > 0) e.contextWindow = d.contextWindow; break;
76
77
  case 'assistant/message': {
78
+ const text = Array.isArray(d.message?.content) ? d.message.content.filter(b => b?.type === 'text' && typeof b.text === 'string').map(b => b.text).join(' ') : '';
79
+ if (text.trim()) e.lastText = clip(text.replace(/[#*`>_~|]+/g, ' ').replace(/\s+/g, ' '), 160);
77
80
  const u = d.usage;
78
81
  if (u && typeof u === 'object') {
79
82
  e.contextTokens = count(u.inputTokens) + count(u.cacheReadTokens) + count(u.cacheWriteTokens);
@@ -96,6 +99,7 @@ export class ActivityStore {
96
99
  const state = reason === 'completed' ? 'completed' : reason === 'aborted' ? 'paused' : 'error';
97
100
  e.tools.clear(); e.approvals.clear();
98
101
  if(state!=='completed')e.questions.clear();
102
+ if (state === 'completed') e.reply = e.lastText;
99
103
  this.set(id, e.questions.size?'waiting':state, { ended: this.now() });
100
104
  if (e.started) this.finished = [...this.finished, { id, title: e.title, state, started: e.started, ended: e.ended, toolCount: e.toolCount, inputTokens: e.inputTokens, cacheTokens: e.cacheTokens, outputTokens: e.outputTokens }].slice(-12);
101
105
  break;
@@ -131,7 +135,8 @@ export class ActivityStore {
131
135
  tool: e ? [...e.tools.values()].at(-1) ?? '' : '',
132
136
  detail: e ? {
133
137
  plan: todos.length ? { total: todos.length, done: todos.filter(t => t.status === 'completed').length, current: todos.find(t => t.status === 'in_progress')?.content ?? '' } : null,
134
- trail: e.trail.slice(-4), toolCount: e.toolCount, model: e.model, contextTokens: e.contextTokens, outputTokens: e.outputTokens,
138
+ trail: e.trail.slice(-4), toolCount: e.toolCount, model: e.model, contextTokens: e.contextTokens, contextWindow: e.contextWindow, outputTokens: e.outputTokens,
139
+ reply: e.state === 'completed' ? e.reply : '',
135
140
  cacheRate: e.inputTokens + e.cacheTokens > 0 ? Math.round(e.cacheTokens / (e.inputTokens + e.cacheTokens) * 100) : null
136
141
  } : null,
137
142
  sessions: rows.slice(0, 5).map(r => ({ id: r.id, title: r.title, state: r.state, started: r.started, ended: r.ended })),