dsh-message-actions 0.2.1 → 0.2.3
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.cn.md +83 -44
- package/README.md +84 -45
- package/icon.svg +4 -4
- package/lib/client.js +1973 -248
- package/lib/index.js +445 -55
- package/lib/shared.cjs +618 -31
- package/lib/store.cjs +13 -8
- package/locale/en.json +2 -2
- package/locale/zh.json +2 -2
- package/package.json +2 -2
package/lib/shared.cjs
CHANGED
|
@@ -37,6 +37,9 @@ const ERROR_LABELS = {
|
|
|
37
37
|
INVALID_AMOUNT: '金额格式不合法',
|
|
38
38
|
READ_ONLY: '状态文件只读,未保存',
|
|
39
39
|
WRITE_FAILED: '写入状态文件失败',
|
|
40
|
+
ATTACHMENT_NOT_FOUND: '附件不存在或已失效',
|
|
41
|
+
ATTACHMENT_UNAVAILABLE: '附件服务不可用',
|
|
42
|
+
ATTACHMENT_READ_FAILED: '附件读取失败',
|
|
40
43
|
INTERNAL: '内部错误'
|
|
41
44
|
},
|
|
42
45
|
en: {
|
|
@@ -52,6 +55,9 @@ const ERROR_LABELS = {
|
|
|
52
55
|
INVALID_AMOUNT: 'Invalid amount',
|
|
53
56
|
READ_ONLY: 'State file is read-only; nothing saved',
|
|
54
57
|
WRITE_FAILED: 'Could not write the state file',
|
|
58
|
+
ATTACHMENT_NOT_FOUND: 'Attachment not found or no longer available',
|
|
59
|
+
ATTACHMENT_UNAVAILABLE: 'Attachment service is unavailable',
|
|
60
|
+
ATTACHMENT_READ_FAILED: 'Could not read the attachment',
|
|
55
61
|
INTERNAL: 'Internal error'
|
|
56
62
|
}
|
|
57
63
|
};
|
|
@@ -64,7 +70,8 @@ const ERROR_LABELS = {
|
|
|
64
70
|
* 折叠 OpenAI 风格 content(字符串或 block 数组)为纯文本。
|
|
65
71
|
* 只取用户可见的 text 块:reasoning(思维链)不属于回答正文,不能混进分享/导出。
|
|
66
72
|
*/
|
|
67
|
-
function contentText(content) {
|
|
73
|
+
function contentText(content, options) {
|
|
74
|
+
const placeholders = !options || options.attachments !== false;
|
|
68
75
|
if (typeof content === 'string') return content;
|
|
69
76
|
if (!Array.isArray(content)) return '';
|
|
70
77
|
const parts = [];
|
|
@@ -77,14 +84,56 @@ function contentText(content) {
|
|
|
77
84
|
if (block.type === 'text' && typeof block.text === 'string') {
|
|
78
85
|
parts.push(block.text);
|
|
79
86
|
} else if (block.type === 'image') {
|
|
80
|
-
parts.push('[图片]');
|
|
87
|
+
if (placeholders) parts.push('[图片]');
|
|
81
88
|
} else if (block.type === 'file') {
|
|
82
|
-
parts.push('[文件]');
|
|
89
|
+
if (placeholders) parts.push('[文件]');
|
|
83
90
|
}
|
|
84
91
|
}
|
|
85
92
|
return parts.join('');
|
|
86
93
|
}
|
|
87
94
|
|
|
95
|
+
/**
|
|
96
|
+
* 撤回回填用的正文:只拼接文本块,不插入 `[图片]` / `[文件]` 占位符。
|
|
97
|
+
* 附件由客户端另行恢复(见 `attachmentsOfEvent`);只有附件恢复不可用时,
|
|
98
|
+
* 占位符才有意义,因此这里不留占位符,避免与真实附件重复。
|
|
99
|
+
*/
|
|
100
|
+
function refillTextOf(event) {
|
|
101
|
+
if (!event || event.type !== 'user/message') return '';
|
|
102
|
+
const content = event.data && event.data.content;
|
|
103
|
+
return contentText(content, { attachments: false });
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* 提取用户消息里的附件描述(图片与文件),供客户端按 id 取回字节后恢复。
|
|
108
|
+
* 只读取 durable `attachment` 引用,不展开内容;同一 id 只保留一次。
|
|
109
|
+
* @returns {{ kind: 'image'|'file', attachmentId: string, name: string, mediaType: string, bytes?: number, width?: number, height?: number }[]}
|
|
110
|
+
*/
|
|
111
|
+
function attachmentsOfEvent(event) {
|
|
112
|
+
const content = event && event.type === 'user/message' && event.data && event.data.content;
|
|
113
|
+
if (!Array.isArray(content)) return [];
|
|
114
|
+
const list = [];
|
|
115
|
+
const seen = new Set();
|
|
116
|
+
for (const block of content) {
|
|
117
|
+
if (!block || block.type !== 'image' && block.type !== 'file') continue;
|
|
118
|
+
const ref = block.attachment;
|
|
119
|
+
if (!ref || typeof ref.attachmentId !== 'string' || ref.attachmentId.length === 0) continue;
|
|
120
|
+
if (seen.has(ref.attachmentId)) continue;
|
|
121
|
+
seen.add(ref.attachmentId);
|
|
122
|
+
list.push({
|
|
123
|
+
kind: block.type,
|
|
124
|
+
attachmentId: ref.attachmentId,
|
|
125
|
+
name: typeof ref.name === 'string' && ref.name.length > 0
|
|
126
|
+
? ref.name
|
|
127
|
+
: (block.type === 'image' ? 'image' : 'file'),
|
|
128
|
+
mediaType: typeof ref.mediaType === 'string' ? ref.mediaType : '',
|
|
129
|
+
bytes: Number.isSafeInteger(ref.bytes) ? ref.bytes : undefined,
|
|
130
|
+
width: Number.isSafeInteger(ref.width) ? ref.width : undefined,
|
|
131
|
+
height: Number.isSafeInteger(ref.height) ? ref.height : undefined
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
return list;
|
|
135
|
+
}
|
|
136
|
+
|
|
88
137
|
/** 取一个事件的纯文本正文(按事件类型分发)。 */
|
|
89
138
|
function textOf(event) {
|
|
90
139
|
if (!event || typeof event !== 'object') return '';
|
|
@@ -492,7 +541,11 @@ function planAction(events, nodes, params) {
|
|
|
492
541
|
})();
|
|
493
542
|
// 撤回回填必须用被点的那条提问文本:轮次区间起点可能是运行时注入消息,
|
|
494
543
|
// 不能取 startSeq 的正文,否则会把注入上下文回填到输入框。
|
|
495
|
-
|
|
544
|
+
// 附件单独返回,客户端恢复成真实图片 / 文件;正文不再插入占位符。
|
|
545
|
+
if (plan.ok && action === 'recall') {
|
|
546
|
+
plan.refillText = refillTextOf(evt);
|
|
547
|
+
plan.attachments = attachmentsOfEvent(evt);
|
|
548
|
+
}
|
|
496
549
|
return plan;
|
|
497
550
|
}
|
|
498
551
|
|
|
@@ -550,7 +603,7 @@ function buildPlan(events, nodes, startSeq, endSeq, targetType, action, turn) {
|
|
|
550
603
|
via,
|
|
551
604
|
turn,
|
|
552
605
|
step,
|
|
553
|
-
refillText: action === 'recall' ?
|
|
606
|
+
refillText: action === 'recall' ? refillTextOf(events[startSeq]) : null
|
|
554
607
|
};
|
|
555
608
|
}
|
|
556
609
|
|
|
@@ -616,6 +669,25 @@ function goneTurnsOf(events, nodes, lookup) {
|
|
|
616
669
|
return turnIndex.filter((info) => !live.has(info.turn)).map((info) => info.turn);
|
|
617
670
|
}
|
|
618
671
|
|
|
672
|
+
/**
|
|
673
|
+
* 单条回答的估算成本:只针对该条 `assistant/message` 自己的 usage,
|
|
674
|
+
* 不复用同一轮其它步骤的数据,避免同轮多步骤重复计价。
|
|
675
|
+
* 本地 / 非 DeepSeek 路由返回 `{ micros: 0, billable: false }`;
|
|
676
|
+
* 无 usage 或无法判定路由时返回 undefined(界面不显示金额)。
|
|
677
|
+
* @returns {{ micros: number, billable: boolean } | undefined}
|
|
678
|
+
*/
|
|
679
|
+
function replyCostOf(event) {
|
|
680
|
+
if (!event || event.type !== 'assistant/message') return undefined;
|
|
681
|
+
const usage = stepUsageOf(event);
|
|
682
|
+
if (!usage) return undefined;
|
|
683
|
+
const data = event.data || {};
|
|
684
|
+
const route = routeOfUsage(data.usage) || routeOfMessage(data.message);
|
|
685
|
+
if (!route) return undefined;
|
|
686
|
+
if (!isBillableRoute(route.provider, route.model)) return { micros: 0, billable: false };
|
|
687
|
+
const at = Number.isFinite(event.time) ? event.time : Date.now();
|
|
688
|
+
return { micros: turnCost(usage, route.model, periodInfo(at).period), billable: true };
|
|
689
|
+
}
|
|
690
|
+
|
|
619
691
|
/**
|
|
620
692
|
* `/messages` 摘要快照:只返回预览、字数、用量与 callId,不返回正文。
|
|
621
693
|
* 分享图 / 导出需要全文时,走 `full=1&turns=a,b` 的按需接口(见 index.mjs)。
|
|
@@ -661,6 +733,7 @@ function messagesSummaryOf(events, nodes, lookup, options) {
|
|
|
661
733
|
(data.source === undefined || data.source === null || data.source.kind === undefined || data.source.kind === 'user');
|
|
662
734
|
const isText = isUserQuestion || event.type === 'assistant/message';
|
|
663
735
|
const text = isText ? textOf(event) : '';
|
|
736
|
+
const replyCost = event.type === 'assistant/message' ? replyCostOf(event) : undefined;
|
|
664
737
|
const summary = {
|
|
665
738
|
seq,
|
|
666
739
|
type: event.type,
|
|
@@ -672,6 +745,8 @@ function messagesSummaryOf(events, nodes, lookup, options) {
|
|
|
672
745
|
preview: isText ? previewText(text, previewLimit) : '',
|
|
673
746
|
words: isText ? wordCount(text) : 0,
|
|
674
747
|
usage: usageSummaryOf(event),
|
|
748
|
+
costMicros: replyCost ? replyCost.micros : null,
|
|
749
|
+
billable: replyCost ? replyCost.billable : null,
|
|
675
750
|
callId: toolCallIdOf(event)
|
|
676
751
|
};
|
|
677
752
|
const beyondCursor = since === null || seq > since;
|
|
@@ -1205,6 +1280,29 @@ function routingOfProvider(provider) {
|
|
|
1205
1280
|
return 'local';
|
|
1206
1281
|
}
|
|
1207
1282
|
|
|
1283
|
+
/** 模型名是否为 DeepSeek 官方模型(无 provider 时用于兜底判定)。 */
|
|
1284
|
+
function isDeepseekModel(model) {
|
|
1285
|
+
return typeof model === 'string' && /^deepseek/i.test(model.trim());
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
/**
|
|
1289
|
+
* 该次用量是否计入 DeepSeek 费用(统计表「估算成本」/「预算使用」/「日用」)。
|
|
1290
|
+
*
|
|
1291
|
+
* - provider 已知:`deepseek-account` / `deepseek-*` 计费,其余(本地模型、第三方网关)不计费;
|
|
1292
|
+
* - provider 缺失:只有模型名明确是 `deepseek-*` 才计费,未知来源一律不计费(不臆测)。
|
|
1293
|
+
*
|
|
1294
|
+
* 本地 / 未知来源的 token 仍照常统计,只是成本记 0。
|
|
1295
|
+
* @param provider 路由 provider(如 `deepseek-account` / `ninfer-27b`)
|
|
1296
|
+
* @param model 模型名(如 `deepseek-flash`)
|
|
1297
|
+
* @returns {boolean}
|
|
1298
|
+
*/
|
|
1299
|
+
function isBillableRoute(provider, model) {
|
|
1300
|
+
const routing = routingOfProvider(provider);
|
|
1301
|
+
if (routing === 'local') return false;
|
|
1302
|
+
if (routing === 'account' || routing === 'api-key') return true;
|
|
1303
|
+
return isDeepseekModel(model);
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1208
1306
|
/**
|
|
1209
1307
|
* 费用卡片样式枚举。数组顺序即设置页选项顺序:单行样式排在第一位。
|
|
1210
1308
|
* 内部存储值沿用 `compact` / `default`,与旧版本配置兼容。
|
|
@@ -1235,6 +1333,81 @@ function costSwitches(config) {
|
|
|
1235
1333
|
};
|
|
1236
1334
|
}
|
|
1237
1335
|
|
|
1336
|
+
/** 可选音色(Web Audio 现场合成,无音频文件)。 */
|
|
1337
|
+
const SOUND_TONES = ['double', 'bell', 'soft'];
|
|
1338
|
+
const DEFAULT_SOUND_TONE = 'double';
|
|
1339
|
+
|
|
1340
|
+
/** 音色归一化:未知值回落到默认双音('off' 由 completionSoundTone 单独处理)。 */
|
|
1341
|
+
function normalizeSoundTone(value) {
|
|
1342
|
+
return typeof value === 'string' && SOUND_TONES.indexOf(value) >= 0 ? value : DEFAULT_SOUND_TONE;
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
/**
|
|
1346
|
+
* 运行时音色。0.2.2 起不再有独立开关:
|
|
1347
|
+
* - `soundTone === 'off'` 即关闭;
|
|
1348
|
+
* - 旧配置只有 `sound: false`(没有音色)时,映射为「关闭」,保持旧行为;
|
|
1349
|
+
* - 旧配置 `sound: false` + 已有音色,同样显示「关闭」(旧开关优先)。
|
|
1350
|
+
*/
|
|
1351
|
+
function completionSoundTone(config) {
|
|
1352
|
+
const cfg = config || {};
|
|
1353
|
+
if (cfg.sound === false) return 'off';
|
|
1354
|
+
if (cfg.soundTone === 'off') return 'off';
|
|
1355
|
+
return normalizeSoundTone(cfg.soundTone);
|
|
1356
|
+
}
|
|
1357
|
+
|
|
1358
|
+
/** 完成提示音是否开启:等价于音色不为「关闭」。 */
|
|
1359
|
+
function completionSoundEnabled(config) {
|
|
1360
|
+
return completionSoundTone(config) !== 'off';
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1363
|
+
/**
|
|
1364
|
+
* 设置页音色选项:3 个音色 + 「关闭」。
|
|
1365
|
+
* 选中「关闭」即关闭完成提示音;选中任一音色即开启并试听。
|
|
1366
|
+
* 供客户端渲染与离线断言共用。
|
|
1367
|
+
*/
|
|
1368
|
+
function soundToneOptions() {
|
|
1369
|
+
return SOUND_TONES.concat(['off']);
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
// 音量:0–100 整数,默认 50(= 现有增益基准),步进 5 由滑杆约束。
|
|
1373
|
+
const DEFAULT_SOUND_VOLUME = 50;
|
|
1374
|
+
|
|
1375
|
+
/** 音量归一化:非法值回默认 50,其余夹到 0–100 的整数。 */
|
|
1376
|
+
function clampSoundVolume(value) {
|
|
1377
|
+
const num = typeof value === 'number' ? value : Number(value);
|
|
1378
|
+
if (!Number.isFinite(num)) return DEFAULT_SOUND_VOLUME;
|
|
1379
|
+
return Math.min(100, Math.max(0, Math.round(num)));
|
|
1380
|
+
}
|
|
1381
|
+
|
|
1382
|
+
/**
|
|
1383
|
+
* 音量倍数:50 为基准 1.0,0 为 0(静音),100 为 2.0。
|
|
1384
|
+
* 播放端用 `TONE_SPECS[音色].gain * soundGainScale(音量)`,避免 0 音量仍发声。
|
|
1385
|
+
*/
|
|
1386
|
+
function soundGainScale(volume) {
|
|
1387
|
+
return clampSoundVolume(volume) / 50;
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
/**
|
|
1391
|
+
* 判断这一轮是否该播放完成提示音。
|
|
1392
|
+
* - 开关必须开启、本轮已结算(`settled !== false`)且拿到有效结算时间;
|
|
1393
|
+
* - `previousAt` 相同说明还是上一轮(重渲染 / 重复拉取),不重复响;
|
|
1394
|
+
* - `lastPlayedAt` 记录已响过的轮次,迟到回调不补响;
|
|
1395
|
+
* - 宿主仍忙(`busy === true`)时不响。
|
|
1396
|
+
* @param {{enabled?:boolean, busy?:boolean, settled?:boolean, previousAt?:number|null, at?:number|null, lastPlayedAt?:number|null}} options
|
|
1397
|
+
* @returns {boolean}
|
|
1398
|
+
*/
|
|
1399
|
+
function shouldPlayCompletionSound(options) {
|
|
1400
|
+
const opt = options || {};
|
|
1401
|
+
if (opt.enabled !== true) return false;
|
|
1402
|
+
if (opt.busy === true) return false;
|
|
1403
|
+
if (opt.settled === false) return false;
|
|
1404
|
+
const at = opt.at;
|
|
1405
|
+
if (!Number.isFinite(at) || at <= 0) return false;
|
|
1406
|
+
if (Number.isFinite(opt.previousAt) && opt.previousAt === at) return false;
|
|
1407
|
+
if (Number.isFinite(opt.lastPlayedAt) && opt.lastPlayedAt === at) return false;
|
|
1408
|
+
return true;
|
|
1409
|
+
}
|
|
1410
|
+
|
|
1238
1411
|
/**
|
|
1239
1412
|
* 聚合一轮(turn/start…turn/end)内各 step 的 usage。
|
|
1240
1413
|
* 每个 step 只取最后一个有效 assistant 结果(message 优先,其次 attempt),
|
|
@@ -1350,31 +1523,61 @@ function appendTurnEvent(buffer, event) {
|
|
|
1350
1523
|
}
|
|
1351
1524
|
|
|
1352
1525
|
// ---------------------------------------------------------------------------
|
|
1353
|
-
//
|
|
1526
|
+
// 费用统计:余额观测(账户口径)
|
|
1354
1527
|
// ---------------------------------------------------------------------------
|
|
1355
1528
|
|
|
1356
1529
|
/** 间隔超过 25 小时视为应用长时间未运行,不补记差额。 */
|
|
1357
1530
|
const MAX_OBSERVE_GAP_MS = 25 * 60 * 60 * 1000;
|
|
1358
1531
|
|
|
1359
|
-
/**
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1532
|
+
/**
|
|
1533
|
+
* 轮次结算累加当日用量(纯函数)。
|
|
1534
|
+
*
|
|
1535
|
+
* 口径:**以结算累加为主**——每轮 `turn/end` 落地时立即把估算金额(分)
|
|
1536
|
+
* 记入当日桶,并与「自上次余额观测以来已结算的金额」一起累计;
|
|
1537
|
+
* 余额观测随后只对差额做校正(见 observeBalance),避免重复计入。
|
|
1538
|
+
*
|
|
1539
|
+
* 幂等:同一 `key`(会话 + 轮次 + 结束时刻)只累加一次,重复推送不会二次计数。
|
|
1540
|
+
* 跨零点:按结算时刻(endedAt)的北京日期入桶。
|
|
1541
|
+
*
|
|
1542
|
+
* @param state 持久化状态(不修改入参)
|
|
1543
|
+
* @param params { micros, at, key }
|
|
1544
|
+
* @returns {{ state, applied, cents }}
|
|
1545
|
+
*/
|
|
1546
|
+
function settleSpend(state, params) {
|
|
1547
|
+
const s = state || {};
|
|
1548
|
+
const p = params || {};
|
|
1549
|
+
const micros = Number.isFinite(p.micros) ? p.micros : 0;
|
|
1550
|
+
const cents = micros > 0 ? Math.round(micros / 10000) : 0;
|
|
1551
|
+
const out = {
|
|
1552
|
+
dailySpendCents: Object.assign({}, s.dailySpendCents || {}),
|
|
1553
|
+
settledSpendTotalCents: Number.isFinite(s.settledSpendTotalCents) ? s.settledSpendTotalCents : 0,
|
|
1554
|
+
settledSinceObserveCents: Number.isFinite(s.settledSinceObserveCents) ? s.settledSinceObserveCents : 0,
|
|
1555
|
+
lastSettledKey: typeof s.lastSettledKey === 'string' ? s.lastSettledKey : ''
|
|
1556
|
+
};
|
|
1557
|
+
const key = typeof p.key === 'string' ? p.key : '';
|
|
1558
|
+
if (cents === 0) return { state: out, applied: false, cents: 0 };
|
|
1559
|
+
if (key !== '' && key === out.lastSettledKey) return { state: out, applied: false, cents: 0 };
|
|
1560
|
+
const at = Number.isFinite(p.at) ? p.at : Date.now();
|
|
1561
|
+
const day = beijingDateKey(at);
|
|
1562
|
+
out.dailySpendCents[day] = (out.dailySpendCents[day] || 0) + cents;
|
|
1563
|
+
out.settledSpendTotalCents += cents;
|
|
1564
|
+
out.settledSinceObserveCents += cents;
|
|
1565
|
+
if (key !== '') out.lastSettledKey = key;
|
|
1566
|
+
return { state: out, applied: true, cents };
|
|
1368
1567
|
}
|
|
1369
1568
|
|
|
1370
1569
|
/**
|
|
1371
1570
|
* 一次余额观测的记账(纯函数,返回新状态与本次记账原因)。
|
|
1372
1571
|
*
|
|
1373
1572
|
* - 下降 → 累计「已观测消费」,按北京时间日期计入「日用」;
|
|
1374
|
-
* - 上升 →
|
|
1573
|
+
* - 上升 → 只更新 lastBalance,不冲减消费(不再维护手工校正字段);
|
|
1375
1574
|
* - 跨日 / 间隔超 25h / 路由切换 → 只更新 lastBalance,跳过本次差额;
|
|
1376
1575
|
* - 非 account 路由 → 完全不记账。
|
|
1377
1576
|
*
|
|
1577
|
+
* 与轮次结算共用同一份「日用」:本轮已结算的金额先由 settleSpend 记入,
|
|
1578
|
+
* 观测到差额时只把 **超出已结算部分** 补进当日桶(`diff - settledSinceObserveCents`),
|
|
1579
|
+
* 不重复计入;估算高于实际(差额为负)时不做减法,保持「日用」为花费上限提示。
|
|
1580
|
+
*
|
|
1378
1581
|
* @param state 持久化状态(不修改入参)
|
|
1379
1582
|
* @param params { cents, routing, at }
|
|
1380
1583
|
* @returns {{ state, reason }}
|
|
@@ -1391,8 +1594,9 @@ function observeBalance(state, params) {
|
|
|
1391
1594
|
lastRouting: typeof s.lastRouting === 'string' ? s.lastRouting : null,
|
|
1392
1595
|
observedSpendTotalCents: Number.isFinite(s.observedSpendTotalCents) ? s.observedSpendTotalCents : 0,
|
|
1393
1596
|
dailySpendCents: Object.assign({}, s.dailySpendCents || {}),
|
|
1394
|
-
|
|
1395
|
-
|
|
1597
|
+
settledSpendTotalCents: Number.isFinite(s.settledSpendTotalCents) ? s.settledSpendTotalCents : 0,
|
|
1598
|
+
settledSinceObserveCents: Number.isFinite(s.settledSinceObserveCents) ? s.settledSinceObserveCents : 0,
|
|
1599
|
+
lastSettledKey: typeof s.lastSettledKey === 'string' ? s.lastSettledKey : ''
|
|
1396
1600
|
};
|
|
1397
1601
|
if (cents === null) return { state: out, reason: 'invalid' };
|
|
1398
1602
|
if (routing !== 'account') return { state: out, reason: 'not-account' };
|
|
@@ -1402,28 +1606,34 @@ function observeBalance(state, params) {
|
|
|
1402
1606
|
out.lastBalanceCents = cents;
|
|
1403
1607
|
out.lastBalanceAt = at;
|
|
1404
1608
|
out.lastRouting = routing;
|
|
1609
|
+
out.settledSinceObserveCents = 0;
|
|
1405
1610
|
return { state: out, reason: 'baseline' };
|
|
1406
1611
|
}
|
|
1407
1612
|
if (out.lastBalanceCents === null || out.lastBalanceAt === 0) {
|
|
1408
1613
|
out.lastBalanceCents = cents;
|
|
1409
1614
|
out.lastBalanceAt = at;
|
|
1410
1615
|
out.lastRouting = routing;
|
|
1616
|
+
out.settledSinceObserveCents = 0;
|
|
1411
1617
|
return { state: out, reason: 'first' };
|
|
1412
1618
|
}
|
|
1413
1619
|
if (out.lastRouting !== routing) {
|
|
1414
1620
|
out.lastBalanceCents = cents;
|
|
1415
1621
|
out.lastBalanceAt = at;
|
|
1416
1622
|
out.lastRouting = routing;
|
|
1623
|
+
out.settledSinceObserveCents = 0;
|
|
1417
1624
|
return { state: out, reason: 'routing-switch' };
|
|
1418
1625
|
}
|
|
1419
1626
|
if (beijingDateKey(out.lastBalanceAt) !== beijingDateKey(at)) {
|
|
1420
1627
|
out.lastBalanceCents = cents;
|
|
1421
1628
|
out.lastBalanceAt = at;
|
|
1629
|
+
// 跨日不补记差额;同时清空待核对结算,避免把昨天的金额算进今天的差值。
|
|
1630
|
+
out.settledSinceObserveCents = 0;
|
|
1422
1631
|
return { state: out, reason: 'cross-day' };
|
|
1423
1632
|
}
|
|
1424
1633
|
if (at - out.lastBalanceAt > MAX_OBSERVE_GAP_MS) {
|
|
1425
1634
|
out.lastBalanceCents = cents;
|
|
1426
1635
|
out.lastBalanceAt = at;
|
|
1636
|
+
out.settledSinceObserveCents = 0;
|
|
1427
1637
|
return { state: out, reason: 'too-long' };
|
|
1428
1638
|
}
|
|
1429
1639
|
|
|
@@ -1431,12 +1641,16 @@ function observeBalance(state, params) {
|
|
|
1431
1641
|
let reason = 'none';
|
|
1432
1642
|
if (diff > 0) {
|
|
1433
1643
|
out.observedSpendTotalCents += diff;
|
|
1434
|
-
|
|
1435
|
-
|
|
1644
|
+
// 已结算部分已计入「日用」,这里只补超出部分,避免同一轮被计两次。
|
|
1645
|
+
const extra = diff - out.settledSinceObserveCents;
|
|
1646
|
+
if (extra > 0) {
|
|
1647
|
+
const key = beijingDateKey(at);
|
|
1648
|
+
out.dailySpendCents[key] = (out.dailySpendCents[key] || 0) + extra;
|
|
1649
|
+
}
|
|
1650
|
+
out.settledSinceObserveCents = 0;
|
|
1436
1651
|
reason = 'spend';
|
|
1437
1652
|
} else if (diff < 0) {
|
|
1438
|
-
|
|
1439
|
-
out.pendingAdjustmentAt = at;
|
|
1653
|
+
// 余额上升(充值 / 退货):只更新基准,不冲减消费,也不做手工校正。
|
|
1440
1654
|
reason = 'adjust';
|
|
1441
1655
|
}
|
|
1442
1656
|
out.lastBalanceCents = cents;
|
|
@@ -1445,10 +1659,15 @@ function observeBalance(state, params) {
|
|
|
1445
1659
|
}
|
|
1446
1660
|
|
|
1447
1661
|
/** 元(数字或字符串)转分;非法返回 null。 */
|
|
1448
|
-
function yuanToCents(value) {
|
|
1662
|
+
function yuanToCents(value, mode) {
|
|
1663
|
+
const truncate = mode === 'truncate';
|
|
1449
1664
|
if (typeof value === 'number') {
|
|
1450
1665
|
if (!Number.isFinite(value)) return null;
|
|
1451
|
-
|
|
1666
|
+
// 数字先转十进制字符串再按分解析:避免 `5.99 * 100 = 598.999…` 的浮点误差把分差成 1。
|
|
1667
|
+
const asText = String(value);
|
|
1668
|
+
if (/^-?\d+(\.\d+)?$/.test(asText.trim())) return yuanToCents(asText, mode);
|
|
1669
|
+
// 科学计数法等无法逐位解析的极端值,退回浮点换算。
|
|
1670
|
+
return truncate && value >= 0 ? Math.floor(value * 100 + 1e-6) : Math.round(value * 100);
|
|
1452
1671
|
}
|
|
1453
1672
|
if (typeof value !== 'string') return null;
|
|
1454
1673
|
const raw = value.trim().replace(/,/g, '');
|
|
@@ -1459,7 +1678,9 @@ function yuanToCents(value) {
|
|
|
1459
1678
|
const whole = split[0];
|
|
1460
1679
|
const frac = split[1] || '';
|
|
1461
1680
|
let cents = Number(whole) * 100 + Number((frac + '00').slice(0, 2));
|
|
1462
|
-
|
|
1681
|
+
// 官方「账号与余额」对正金额截断至分:原始余额字符串可能带三位以上小数,
|
|
1682
|
+
// 这里必须同样截断,否则 5.999… 会进位成 6.00,比官方页面多一分。
|
|
1683
|
+
if (frac.length > 2 && !(truncate && !negative) && Number(frac.charAt(2)) >= 5) cents += 1;
|
|
1463
1684
|
return negative ? -cents : cents;
|
|
1464
1685
|
}
|
|
1465
1686
|
|
|
@@ -1533,6 +1754,17 @@ function formatCostMicros(micros) {
|
|
|
1533
1754
|
return formatYuanCents(Math.round(micros / 10000));
|
|
1534
1755
|
}
|
|
1535
1756
|
|
|
1757
|
+
/**
|
|
1758
|
+
* 微元 -> 单条回答金额展示(保留 4 位小数,避免每轮几厘钱被舍成 0):
|
|
1759
|
+
* 0 → `¥0.0000`;0 < x < ¥0.0001 → `<¥0.0001`;其余四舍五入到 4 位。
|
|
1760
|
+
*/
|
|
1761
|
+
function formatReplyCost(micros) {
|
|
1762
|
+
if (!Number.isFinite(micros)) return '';
|
|
1763
|
+
if (micros <= 0) return '¥0.0000';
|
|
1764
|
+
if (micros < 100) return '<¥0.0001';
|
|
1765
|
+
return '¥' + (micros / 1000000).toFixed(4);
|
|
1766
|
+
}
|
|
1767
|
+
|
|
1536
1768
|
/** 自动关闭时刻:秒数 0 / 非法返回 null(不自动关闭);上限 600 秒。 */
|
|
1537
1769
|
function autoCloseAt(firstSeenAt, seconds) {
|
|
1538
1770
|
const s = typeof seconds === 'string' ? Number(seconds) : seconds;
|
|
@@ -1546,6 +1778,329 @@ function easeOutCubic(t) {
|
|
|
1546
1778
|
return 1 - Math.pow(1 - x, 3);
|
|
1547
1779
|
}
|
|
1548
1780
|
|
|
1781
|
+
// ---------------------------------------------------------------------------
|
|
1782
|
+
// 会话统计:从真实会话日志折叠 token / 成本 / 时间线(宿主与测试共用)
|
|
1783
|
+
// ---------------------------------------------------------------------------
|
|
1784
|
+
|
|
1785
|
+
/** 时间线桶数:小时视图 48 个(客户端展示最近 24 个),日视图 30 个。 */
|
|
1786
|
+
const STATS_HOURLY_BUCKETS = 48;
|
|
1787
|
+
const STATS_DAILY_BUCKETS = 30;
|
|
1788
|
+
|
|
1789
|
+
/** 四类 token 的空桶。 */
|
|
1790
|
+
function emptyStatsTokens() {
|
|
1791
|
+
return { input: 0, cacheRead: 0, cacheWrite: 0, output: 0 };
|
|
1792
|
+
}
|
|
1793
|
+
|
|
1794
|
+
/** 四类 token 合计。 */
|
|
1795
|
+
function statsTokenTotal(tokens) {
|
|
1796
|
+
const t = tokens || {};
|
|
1797
|
+
return tokenCount(t.input) + tokenCount(t.cacheRead) + tokenCount(t.cacheWrite) + tokenCount(t.output);
|
|
1798
|
+
}
|
|
1799
|
+
|
|
1800
|
+
/**
|
|
1801
|
+
* 原始 usage → 四类 token 桶。缺 input/output 计数时返回 null(该条不计入)。
|
|
1802
|
+
* 与费用统计共用 `normalizeCostUsage`,保证同一份日志得到同一组数字。
|
|
1803
|
+
*/
|
|
1804
|
+
function statsUsageBuckets(usage) {
|
|
1805
|
+
const normalized = normalizeCostUsage(usage);
|
|
1806
|
+
if (!normalized) return null;
|
|
1807
|
+
return {
|
|
1808
|
+
input: normalized.inputTokens,
|
|
1809
|
+
cacheRead: normalized.cacheReadTokens,
|
|
1810
|
+
cacheWrite: normalized.cacheWriteTokens,
|
|
1811
|
+
output: normalized.outputTokens
|
|
1812
|
+
};
|
|
1813
|
+
}
|
|
1814
|
+
|
|
1815
|
+
/**
|
|
1816
|
+
* 单个时间点的估算成本(微元):按该点时刻的峰 / 谷价与当时模型价目计算,
|
|
1817
|
+
* 与费用卡片的「单次」共用 `turnCost`,因此两处口径一致。
|
|
1818
|
+
*/
|
|
1819
|
+
function statsPointCostMicros(point) {
|
|
1820
|
+
if (!point) return 0;
|
|
1821
|
+
// 本地 / 未知来源的 token 照常统计,但成本记 0(不套用 DeepSeek 价目)。
|
|
1822
|
+
if (point.billable === false) return 0;
|
|
1823
|
+
const at = Number.isFinite(point.t) ? point.t : Date.now();
|
|
1824
|
+
const period = periodInfo(at).period;
|
|
1825
|
+
const usage = {
|
|
1826
|
+
inputTokens: tokenCount(point.input),
|
|
1827
|
+
cacheReadTokens: tokenCount(point.cacheRead),
|
|
1828
|
+
cacheWriteTokens: tokenCount(point.cacheWrite),
|
|
1829
|
+
outputTokens: tokenCount(point.output),
|
|
1830
|
+
reasoningTokens: 0
|
|
1831
|
+
};
|
|
1832
|
+
return turnCost(usage, point.model, period);
|
|
1833
|
+
}
|
|
1834
|
+
|
|
1835
|
+
/** 取目录的最后一段,作为无标题会话的兜底名称。 */
|
|
1836
|
+
function baseNameOfPath(value) {
|
|
1837
|
+
if (typeof value !== 'string' || value.length === 0) return '';
|
|
1838
|
+
const parts = value.split(/[\\/]/).filter(Boolean);
|
|
1839
|
+
return parts.length === 0 ? '' : parts[parts.length - 1];
|
|
1840
|
+
}
|
|
1841
|
+
|
|
1842
|
+
/**
|
|
1843
|
+
* 折叠一条会话日志:四类 token 汇总、时间线点(含计价时刻的模型)、
|
|
1844
|
+
* 标题 / 首个问题 / 模型与最后活跃时间。与宿主的 `tokenUsage` 投影口径一致:
|
|
1845
|
+
* 每个 assistant/message 的 usage 只取一次。
|
|
1846
|
+
* @param events 会话事件数组(读取日志得到的原始事件)
|
|
1847
|
+
*/
|
|
1848
|
+
function foldSessionStats(events) {
|
|
1849
|
+
const list = Array.isArray(events) ? events : [];
|
|
1850
|
+
const tokens = emptyStatsTokens();
|
|
1851
|
+
const points = [];
|
|
1852
|
+
let title = '';
|
|
1853
|
+
let firstPrompt = '';
|
|
1854
|
+
let model = '';
|
|
1855
|
+
let provider = '';
|
|
1856
|
+
let currentModel = '';
|
|
1857
|
+
let lastActiveAt = 0;
|
|
1858
|
+
let turns = 0;
|
|
1859
|
+
let steps = 0;
|
|
1860
|
+
let messages = 0;
|
|
1861
|
+
|
|
1862
|
+
for (const event of list) {
|
|
1863
|
+
if (!event || typeof event.type !== 'string') continue;
|
|
1864
|
+
const time = Number.isFinite(event.time) ? event.time : 0;
|
|
1865
|
+
if (time > lastActiveAt) lastActiveAt = time;
|
|
1866
|
+
const data = event.data || {};
|
|
1867
|
+
|
|
1868
|
+
if (event.type === 'assistant/message') {
|
|
1869
|
+
messages += 1;
|
|
1870
|
+
if (Number.isSafeInteger(data.turn) && data.turn > turns) turns = data.turn;
|
|
1871
|
+
const route = routeOfMessage(data.message) || routeOfUsage(data.usage);
|
|
1872
|
+
if (route) {
|
|
1873
|
+
provider = route.provider;
|
|
1874
|
+
if (route.model) currentModel = route.model;
|
|
1875
|
+
}
|
|
1876
|
+
const buckets = statsUsageBuckets(data.usage);
|
|
1877
|
+
if (buckets) {
|
|
1878
|
+
const pointModel = currentModel || model;
|
|
1879
|
+
const point = {
|
|
1880
|
+
t: time,
|
|
1881
|
+
input: buckets.input,
|
|
1882
|
+
cacheRead: buckets.cacheRead,
|
|
1883
|
+
cacheWrite: buckets.cacheWrite,
|
|
1884
|
+
output: buckets.output,
|
|
1885
|
+
model: pointModel,
|
|
1886
|
+
// 只对 DeepSeek 官方路由计价;本地模型仍统计 token,但成本为 0。
|
|
1887
|
+
billable: isBillableRoute(provider, pointModel)
|
|
1888
|
+
};
|
|
1889
|
+
tokens.input += point.input;
|
|
1890
|
+
tokens.cacheRead += point.cacheRead;
|
|
1891
|
+
tokens.cacheWrite += point.cacheWrite;
|
|
1892
|
+
tokens.output += point.output;
|
|
1893
|
+
points.push(point);
|
|
1894
|
+
}
|
|
1895
|
+
continue;
|
|
1896
|
+
}
|
|
1897
|
+
|
|
1898
|
+
if (event.type === 'step/end') {
|
|
1899
|
+
steps += 1;
|
|
1900
|
+
continue;
|
|
1901
|
+
}
|
|
1902
|
+
|
|
1903
|
+
if (event.type === 'session/title') {
|
|
1904
|
+
if (typeof data.title === 'string' && data.title.trim()) title = data.title.trim();
|
|
1905
|
+
continue;
|
|
1906
|
+
}
|
|
1907
|
+
|
|
1908
|
+
if (event.type === 'request/header') {
|
|
1909
|
+
const config = data.header && data.header.config;
|
|
1910
|
+
if (config && typeof config === 'object') {
|
|
1911
|
+
if (typeof config.model === 'string' && config.model) {
|
|
1912
|
+
model = config.model;
|
|
1913
|
+
currentModel = config.model;
|
|
1914
|
+
}
|
|
1915
|
+
if (typeof config.provider === 'string' && config.provider) provider = config.provider;
|
|
1916
|
+
}
|
|
1917
|
+
continue;
|
|
1918
|
+
}
|
|
1919
|
+
|
|
1920
|
+
if (event.type === 'user/message' && !firstPrompt) {
|
|
1921
|
+
// 会话日志两种历史形状都兼容:data.message.content 或 data.content。
|
|
1922
|
+
const message = data.message && typeof data.message === 'object' ? data.message : data;
|
|
1923
|
+
const text = contentText(message.content).replace(/\s+/g, ' ').trim();
|
|
1924
|
+
if (text) firstPrompt = text.length > 80 ? text.slice(0, 80) + '…' : text;
|
|
1925
|
+
}
|
|
1926
|
+
}
|
|
1927
|
+
|
|
1928
|
+
return { tokens, points, title, firstPrompt, model, provider, lastActiveAt, turns, steps, messages };
|
|
1929
|
+
}
|
|
1930
|
+
|
|
1931
|
+
/** 本地时间的小时起点。 */
|
|
1932
|
+
function statsFloorHour(ts) {
|
|
1933
|
+
const date = new Date(ts);
|
|
1934
|
+
date.setMinutes(0, 0, 0);
|
|
1935
|
+
return date.getTime();
|
|
1936
|
+
}
|
|
1937
|
+
|
|
1938
|
+
/** 本地时间的日起点。 */
|
|
1939
|
+
function statsFloorDay(ts) {
|
|
1940
|
+
const date = new Date(ts);
|
|
1941
|
+
date.setHours(0, 0, 0, 0);
|
|
1942
|
+
return date.getTime();
|
|
1943
|
+
}
|
|
1944
|
+
|
|
1945
|
+
/** 以 `now` 为终点、向过去生成连续桶起点(旧 → 新)。 */
|
|
1946
|
+
function statsBucketStarts(now, count, unit) {
|
|
1947
|
+
const total = Number.isSafeInteger(count) && count > 0 ? count : 1;
|
|
1948
|
+
const starts = [];
|
|
1949
|
+
const cursor = new Date(unit === 'hour' ? statsFloorHour(now) : statsFloorDay(now));
|
|
1950
|
+
for (let index = 0; index < total; index += 1) {
|
|
1951
|
+
starts.push(cursor.getTime());
|
|
1952
|
+
if (unit === 'hour') cursor.setHours(cursor.getHours() - 1);
|
|
1953
|
+
else cursor.setDate(cursor.getDate() - 1);
|
|
1954
|
+
}
|
|
1955
|
+
return starts.reverse();
|
|
1956
|
+
}
|
|
1957
|
+
|
|
1958
|
+
/** 把时间点聚合成桶(含 token 合计与成本合计,微元)。 */
|
|
1959
|
+
function statsAggregate(points, starts, unit) {
|
|
1960
|
+
const list = starts || [];
|
|
1961
|
+
const buckets = list.map((t) => ({
|
|
1962
|
+
t,
|
|
1963
|
+
...emptyStatsTokens(),
|
|
1964
|
+
tokens: 0,
|
|
1965
|
+
billableTokens: 0,
|
|
1966
|
+
localTokens: 0,
|
|
1967
|
+
costMicros: 0
|
|
1968
|
+
}));
|
|
1969
|
+
const positionOf = new Map();
|
|
1970
|
+
buckets.forEach((bucket, index) => positionOf.set(bucket.t, index));
|
|
1971
|
+
for (const point of points || []) {
|
|
1972
|
+
if (!point || !Number.isFinite(point.t)) continue;
|
|
1973
|
+
const start = unit === 'hour' ? statsFloorHour(point.t) : statsFloorDay(point.t);
|
|
1974
|
+
const position = positionOf.get(start);
|
|
1975
|
+
if (position === undefined) continue;
|
|
1976
|
+
const bucket = buckets[position];
|
|
1977
|
+
bucket.input += tokenCount(point.input);
|
|
1978
|
+
bucket.cacheRead += tokenCount(point.cacheRead);
|
|
1979
|
+
bucket.cacheWrite += tokenCount(point.cacheWrite);
|
|
1980
|
+
bucket.output += tokenCount(point.output);
|
|
1981
|
+
const pointTokens = tokenCount(point.input) + tokenCount(point.cacheRead) +
|
|
1982
|
+
tokenCount(point.cacheWrite) + tokenCount(point.output);
|
|
1983
|
+
bucket.tokens += pointTokens;
|
|
1984
|
+
if (point.billable === false) bucket.localTokens += pointTokens;
|
|
1985
|
+
else bucket.billableTokens += pointTokens;
|
|
1986
|
+
bucket.costMicros += statsPointCostMicros(point);
|
|
1987
|
+
}
|
|
1988
|
+
return buckets;
|
|
1989
|
+
}
|
|
1990
|
+
|
|
1991
|
+
/** 小时 / 日两条时间线(宿主一次性算好,客户端只切换显示)。 */
|
|
1992
|
+
function statsTimeline(points, now) {
|
|
1993
|
+
const at = Number.isFinite(now) ? now : Date.now();
|
|
1994
|
+
return {
|
|
1995
|
+
hourly: statsAggregate(points, statsBucketStarts(at, STATS_HOURLY_BUCKETS, 'hour'), 'hour'),
|
|
1996
|
+
daily: statsAggregate(points, statsBucketStarts(at, STATS_DAILY_BUCKETS, 'day'), 'day')
|
|
1997
|
+
};
|
|
1998
|
+
}
|
|
1999
|
+
|
|
2000
|
+
/** 会话行(供表格与汇总;纯函数便于离线断言)。 */
|
|
2001
|
+
function statsSessionRow(header, fold, options) {
|
|
2002
|
+
const h = header && typeof header === 'object' ? header : {};
|
|
2003
|
+
const f = fold && typeof fold === 'object' ? fold : {};
|
|
2004
|
+
const opt = options || {};
|
|
2005
|
+
const source = f.tokens && typeof f.tokens === 'object' ? f.tokens : emptyStatsTokens();
|
|
2006
|
+
const tokens = {
|
|
2007
|
+
input: tokenCount(source.input),
|
|
2008
|
+
cacheRead: tokenCount(source.cacheRead),
|
|
2009
|
+
cacheWrite: tokenCount(source.cacheWrite),
|
|
2010
|
+
output: tokenCount(source.output)
|
|
2011
|
+
};
|
|
2012
|
+
const total = statsTokenTotal(tokens);
|
|
2013
|
+
let costMicros = 0;
|
|
2014
|
+
let billableTokens = 0;
|
|
2015
|
+
let localTokens = 0;
|
|
2016
|
+
for (const point of Array.isArray(f.points) ? f.points : []) {
|
|
2017
|
+
if (!point) continue;
|
|
2018
|
+
const pointTokens = tokenCount(point.input) + tokenCount(point.cacheRead) +
|
|
2019
|
+
tokenCount(point.cacheWrite) + tokenCount(point.output);
|
|
2020
|
+
if (point.billable === false) localTokens += pointTokens;
|
|
2021
|
+
else billableTokens += pointTokens;
|
|
2022
|
+
costMicros += statsPointCostMicros(point);
|
|
2023
|
+
}
|
|
2024
|
+
const id = typeof h.id === 'string' ? h.id : '';
|
|
2025
|
+
return {
|
|
2026
|
+
id,
|
|
2027
|
+
title: f.title || f.firstPrompt || baseNameOfPath(h.cwd) || id,
|
|
2028
|
+
cwd: typeof h.cwd === 'string' ? h.cwd : '',
|
|
2029
|
+
createdAt: Number.isFinite(h.createdAt) ? h.createdAt : 0,
|
|
2030
|
+
lastActiveAt: Number.isFinite(f.lastActiveAt) ? f.lastActiveAt : 0,
|
|
2031
|
+
model: f.model || '',
|
|
2032
|
+
provider: f.provider || '',
|
|
2033
|
+
turns: Number.isSafeInteger(f.turns) ? f.turns : 0,
|
|
2034
|
+
steps: Number.isSafeInteger(f.steps) ? f.steps : 0,
|
|
2035
|
+
messages: Number.isSafeInteger(f.messages) ? f.messages : 0,
|
|
2036
|
+
tokens: { ...tokens, total },
|
|
2037
|
+
billableTokens,
|
|
2038
|
+
localTokens,
|
|
2039
|
+
/** 该会话是否有任何 DeepSeek 计费用量(用于会话表「本地 · 不计费」展示)。 */
|
|
2040
|
+
billable: billableTokens > 0,
|
|
2041
|
+
costMicros,
|
|
2042
|
+
running: opt.running === true,
|
|
2043
|
+
live: opt.live === true,
|
|
2044
|
+
subagent: h.origin === 'subagent'
|
|
2045
|
+
};
|
|
2046
|
+
}
|
|
2047
|
+
|
|
2048
|
+
/** 汇总多行:四类 token、成本、会话数、运行中数量与轮 / step / 消息数。 */
|
|
2049
|
+
function statsSummary(rows) {
|
|
2050
|
+
const list = Array.isArray(rows) ? rows : [];
|
|
2051
|
+
const tokens = emptyStatsTokens();
|
|
2052
|
+
let costMicros = 0;
|
|
2053
|
+
let billableTokens = 0;
|
|
2054
|
+
let localTokens = 0;
|
|
2055
|
+
let running = 0;
|
|
2056
|
+
let turns = 0;
|
|
2057
|
+
let steps = 0;
|
|
2058
|
+
let messages = 0;
|
|
2059
|
+
for (const row of list) {
|
|
2060
|
+
if (!row) continue;
|
|
2061
|
+
const source = row.tokens || {};
|
|
2062
|
+
tokens.input += tokenCount(source.input);
|
|
2063
|
+
tokens.cacheRead += tokenCount(source.cacheRead);
|
|
2064
|
+
tokens.cacheWrite += tokenCount(source.cacheWrite);
|
|
2065
|
+
tokens.output += tokenCount(source.output);
|
|
2066
|
+
costMicros += Number.isFinite(row.costMicros) ? Math.max(0, Math.round(row.costMicros)) : 0;
|
|
2067
|
+
billableTokens += Number.isFinite(row.billableTokens) ? Math.max(0, row.billableTokens) : 0;
|
|
2068
|
+
localTokens += Number.isFinite(row.localTokens) ? Math.max(0, row.localTokens) : 0;
|
|
2069
|
+
turns += Number.isSafeInteger(row.turns) ? row.turns : 0;
|
|
2070
|
+
steps += Number.isSafeInteger(row.steps) ? row.steps : 0;
|
|
2071
|
+
messages += Number.isSafeInteger(row.messages) ? row.messages : 0;
|
|
2072
|
+
if (row.running === true) running += 1;
|
|
2073
|
+
}
|
|
2074
|
+
return {
|
|
2075
|
+
tokens: { ...tokens, total: statsTokenTotal(tokens) },
|
|
2076
|
+
billableTokens,
|
|
2077
|
+
localTokens,
|
|
2078
|
+
costMicros,
|
|
2079
|
+
sessions: list.length,
|
|
2080
|
+
running,
|
|
2081
|
+
turns,
|
|
2082
|
+
steps,
|
|
2083
|
+
messages
|
|
2084
|
+
};
|
|
2085
|
+
}
|
|
2086
|
+
|
|
2087
|
+
/**
|
|
2088
|
+
* 预算视图:金额为分(人民币,与费用卡片币种一致)。
|
|
2089
|
+
* budgetCents 为 0 视为未设预算(enabled=false,比例不显示)。
|
|
2090
|
+
*/
|
|
2091
|
+
function statsBudget(spentMicros, budgetCents) {
|
|
2092
|
+
const amountCents = Number.isFinite(budgetCents) && budgetCents > 0 ? Math.round(budgetCents) : 0;
|
|
2093
|
+
const spentCents = Number.isFinite(spentMicros) ? Math.max(0, Math.round(spentMicros / 10000)) : 0;
|
|
2094
|
+
const enabled = amountCents > 0;
|
|
2095
|
+
return {
|
|
2096
|
+
amountCents,
|
|
2097
|
+
spentCents,
|
|
2098
|
+
remainingCents: enabled ? Math.max(0, amountCents - spentCents) : 0,
|
|
2099
|
+
ratio: enabled ? spentCents / amountCents : 0,
|
|
2100
|
+
enabled
|
|
2101
|
+
};
|
|
2102
|
+
}
|
|
2103
|
+
|
|
1549
2104
|
// ---------------------------------------------------------------------------
|
|
1550
2105
|
// 工具函数
|
|
1551
2106
|
// ---------------------------------------------------------------------------
|
|
@@ -1654,10 +2209,12 @@ const CSS = `
|
|
|
1654
2209
|
.dma-stats{order:1;display:inline-flex;align-items:center;font-size:11px;line-height:1;color:var(--dsw-alias-label-tertiary,#8a919e);white-space:nowrap;user-select:text;margin-inline:2px}
|
|
1655
2210
|
[data-dma-hidden="1"]{display:none!important}
|
|
1656
2211
|
[data-dma-rail="1"]{display:none!important}
|
|
1657
|
-
.dma-overlay{position:fixed;inset:0;z-index:2147483000;background:var(--dsw-alias-bg-mask-1,rgba(0,0,0,.45));display:
|
|
1658
|
-
.dma-panel{width:min(680px,calc(100vw - 48px));max-height:
|
|
1659
|
-
.dma-
|
|
1660
|
-
.dma-panel-
|
|
2212
|
+
.dma-overlay{position:fixed;inset:0;z-index:2147483000;background:var(--dsw-alias-bg-mask-1,rgba(0,0,0,.45));display:grid;place-items:center;padding:16px;overflow:auto}
|
|
2213
|
+
.dma-panel{width:min(680px,calc(100vw - 48px));max-height:calc(100vh - 32px);display:flex;flex-direction:column;background:var(--dsw-alias-bg-layer-1,#ffffff);border:.5px solid var(--dsw-alias-border-l2,rgba(0,0,0,.1));border-radius:var(--dsw-radius-panel,12px);box-shadow:var(--dsw-elevation-panel,0 18px 48px rgba(0,0,0,.18));overflow:hidden;color:var(--dsw-alias-label-primary,#1f2329)}
|
|
2214
|
+
.dma-confirm{width:min(420px,calc(100vw - 48px))}
|
|
2215
|
+
@media (max-width:480px){.dma-confirm{width:calc(100vw - 32px)}.dma-panel-foot{gap:8px}.dma-panel-foot .dma-btn{padding:0 12px}}
|
|
2216
|
+
.dma-panel-head{flex:none;padding:16px 20px;border-bottom:.5px solid var(--dsw-alias-border-l2,rgba(0,0,0,.1));font-size:16px;font-weight:600}
|
|
2217
|
+
.dma-panel-body{flex:1 1 auto;min-height:0;overflow:auto;padding:12px 16px}
|
|
1661
2218
|
.dma-round{display:flex;gap:12px;align-items:flex-start;padding:10px 8px;border-bottom:.5px solid var(--dsw-alias-border-l2,rgba(0,0,0,.08));border-radius:8px}
|
|
1662
2219
|
.dma-round:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(0,0,0,.04))}
|
|
1663
2220
|
.dma-round-box{flex:0 0 auto;width:20px;height:20px;border-radius:50%;border:1.5px solid var(--dsw-alias-border-l3,#c9ced6);display:inline-flex;align-items:center;justify-content:center;cursor:pointer;padding:0;background:transparent;color:transparent;margin-top:2px}
|
|
@@ -1671,7 +2228,7 @@ const CSS = `
|
|
|
1671
2228
|
.dma-round-tag-a{color:var(--dsw-alias-label-tertiary,#8a919e)}
|
|
1672
2229
|
.dma-round-a{color:var(--dsw-alias-label-secondary,#5b6472)}
|
|
1673
2230
|
.dma-round-text{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
1674
|
-
.dma-panel-foot{display:flex;align-items:center;justify-content:space-between;padding:12px 20px;border-top:.5px solid var(--dsw-alias-border-l2,rgba(0,0,0,.1))}
|
|
2231
|
+
.dma-panel-foot{flex:none;display:flex;align-items:center;justify-content:space-between;padding:12px 20px;border-top:.5px solid var(--dsw-alias-border-l2,rgba(0,0,0,.1))}
|
|
1675
2232
|
.dma-panel-foot .dma-btn{width:auto;height:32px;padding:0 14px;border:.5px solid var(--dsw-alias-border-l3,#c9ced6);border-radius:8px;color:var(--dsw-alias-label-secondary,#5b6472)}
|
|
1676
2233
|
.dma-panel-foot .dma-primary{background:var(--dsw-alias-button-primary-fill,#4c8dff);color:var(--dsw-alias-label-primary-inverted,#fff);border-color:transparent}
|
|
1677
2234
|
.dma-panel-foot .dma-primary.dma-danger{background:var(--dsw-alias-state-error-primary,#e5484d);color:#fff}
|
|
@@ -1689,6 +2246,8 @@ module.exports = {
|
|
|
1689
2246
|
TOMBSTONE_TEXT,
|
|
1690
2247
|
ERROR_LABELS,
|
|
1691
2248
|
contentText,
|
|
2249
|
+
refillTextOf,
|
|
2250
|
+
attachmentsOfEvent,
|
|
1692
2251
|
textOf,
|
|
1693
2252
|
messageRoleOf,
|
|
1694
2253
|
messageIdOf,
|
|
@@ -1757,7 +2316,19 @@ module.exports = {
|
|
|
1757
2316
|
routeOfMessage,
|
|
1758
2317
|
routeOfUsage,
|
|
1759
2318
|
routingOfProvider,
|
|
2319
|
+
isDeepseekModel,
|
|
2320
|
+
isBillableRoute,
|
|
1760
2321
|
costSwitches,
|
|
2322
|
+
completionSoundEnabled,
|
|
2323
|
+
SOUND_TONES,
|
|
2324
|
+
DEFAULT_SOUND_TONE,
|
|
2325
|
+
normalizeSoundTone,
|
|
2326
|
+
completionSoundTone,
|
|
2327
|
+
soundToneOptions,
|
|
2328
|
+
DEFAULT_SOUND_VOLUME,
|
|
2329
|
+
clampSoundVolume,
|
|
2330
|
+
soundGainScale,
|
|
2331
|
+
shouldPlayCompletionSound,
|
|
1761
2332
|
COST_LAYOUTS,
|
|
1762
2333
|
DEFAULT_COST_LAYOUT,
|
|
1763
2334
|
normalizeCostLayout,
|
|
@@ -1766,16 +2337,32 @@ module.exports = {
|
|
|
1766
2337
|
deriveTurnUsage,
|
|
1767
2338
|
createTurnBuffer,
|
|
1768
2339
|
appendTurnEvent,
|
|
1769
|
-
correctedBalanceCents,
|
|
1770
2340
|
observeBalance,
|
|
2341
|
+
settleSpend,
|
|
1771
2342
|
yuanToCents,
|
|
1772
2343
|
validateCorrectionAmount,
|
|
1773
2344
|
pruneDailySpend,
|
|
1774
2345
|
formatCents,
|
|
1775
2346
|
formatYuanCents,
|
|
1776
2347
|
formatCostMicros,
|
|
2348
|
+
formatReplyCost,
|
|
1777
2349
|
autoCloseAt,
|
|
1778
2350
|
easeOutCubic,
|
|
2351
|
+
STATS_HOURLY_BUCKETS,
|
|
2352
|
+
STATS_DAILY_BUCKETS,
|
|
2353
|
+
emptyStatsTokens,
|
|
2354
|
+
statsTokenTotal,
|
|
2355
|
+
statsUsageBuckets,
|
|
2356
|
+
statsPointCostMicros,
|
|
2357
|
+
foldSessionStats,
|
|
2358
|
+
statsFloorHour,
|
|
2359
|
+
statsFloorDay,
|
|
2360
|
+
statsBucketStarts,
|
|
2361
|
+
statsAggregate,
|
|
2362
|
+
statsTimeline,
|
|
2363
|
+
statsSessionRow,
|
|
2364
|
+
statsSummary,
|
|
2365
|
+
statsBudget,
|
|
1779
2366
|
ICONS,
|
|
1780
2367
|
CSS
|
|
1781
2368
|
};
|