dsh-message-actions 0.0.0-stage → 0.2.2
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/cordis.patch.yml +3 -0
- package/icon.svg +5 -0
- package/lib/client.js +5994 -0
- package/lib/http.cjs +131 -0
- package/lib/index.js +1252 -0
- package/lib/shared.cjs +2368 -0
- package/lib/store.cjs +266 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +56 -3
- package/README.md +0 -3
package/lib/shared.cjs
ADDED
|
@@ -0,0 +1,2368 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* dsh-message-actions — 共享纯函数(宿主与客户端共用)。
|
|
5
|
+
*
|
|
6
|
+
* 本模块不依赖任何 DSH / 第三方运行时,也不产生副作用,因此可被
|
|
7
|
+
* `test/check.mjs` 离线加载,也可被构建脚本内联进客户端 bundle。
|
|
8
|
+
*
|
|
9
|
+
* 命名与实现均为本项目自行设计,不复制任何第三方代码。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
// ---------------------------------------------------------------------------
|
|
13
|
+
// 常量
|
|
14
|
+
// ---------------------------------------------------------------------------
|
|
15
|
+
|
|
16
|
+
/** 墓碑事件的 producer 标识,用于在会话日志里识别本插件写入的删除/撤回标记。 */
|
|
17
|
+
const PRODUCER = 'dsh-message-actions';
|
|
18
|
+
|
|
19
|
+
/** 墓碑正文占位文本。 */
|
|
20
|
+
const TOMBSTONE_TEXT = { recall: '[已撤回]', delete: '[已删除]', deleteFrom: '[已删除]' };
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* 宿主 HTTP 错误码与文案(zh / en)。
|
|
24
|
+
* 错误码稳定;文案仅用于日志与客户端 toast 兜底展示。
|
|
25
|
+
*/
|
|
26
|
+
const ERROR_LABELS = {
|
|
27
|
+
zh: {
|
|
28
|
+
INVALID_REQUEST: '无效请求',
|
|
29
|
+
FORBIDDEN: '请求被拒绝',
|
|
30
|
+
PAYLOAD_TOO_LARGE: '请求体过大',
|
|
31
|
+
AGENT_BUSY: '正在生成回复,请稍后再试',
|
|
32
|
+
SESSION_NOT_LIVE: '会话不可用',
|
|
33
|
+
TARGET_NOT_FOUND: '目标消息不存在或已被删除',
|
|
34
|
+
NOT_DELETABLE: '该消息不可删除',
|
|
35
|
+
NOT_A_USER_MESSAGE: '仅用户消息可撤回',
|
|
36
|
+
SPAN_NOT_CONTIGUOUS: '目标回答与工具结果不连续,无法整体删除',
|
|
37
|
+
INVALID_AMOUNT: '金额格式不合法',
|
|
38
|
+
READ_ONLY: '状态文件只读,未保存',
|
|
39
|
+
WRITE_FAILED: '写入状态文件失败',
|
|
40
|
+
ATTACHMENT_NOT_FOUND: '附件不存在或已失效',
|
|
41
|
+
ATTACHMENT_UNAVAILABLE: '附件服务不可用',
|
|
42
|
+
ATTACHMENT_READ_FAILED: '附件读取失败',
|
|
43
|
+
INTERNAL: '内部错误'
|
|
44
|
+
},
|
|
45
|
+
en: {
|
|
46
|
+
INVALID_REQUEST: 'Invalid request',
|
|
47
|
+
FORBIDDEN: 'Forbidden',
|
|
48
|
+
PAYLOAD_TOO_LARGE: 'Payload too large',
|
|
49
|
+
AGENT_BUSY: 'A reply is being generated; try again later',
|
|
50
|
+
SESSION_NOT_LIVE: 'Session is not live',
|
|
51
|
+
TARGET_NOT_FOUND: 'Target message not found or already deleted',
|
|
52
|
+
NOT_DELETABLE: 'This message cannot be deleted',
|
|
53
|
+
NOT_A_USER_MESSAGE: 'Only user messages can be recalled',
|
|
54
|
+
SPAN_NOT_CONTIGUOUS: 'Answer and tool results are not contiguous',
|
|
55
|
+
INVALID_AMOUNT: 'Invalid amount',
|
|
56
|
+
READ_ONLY: 'State file is read-only; nothing saved',
|
|
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',
|
|
61
|
+
INTERNAL: 'Internal error'
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
// ---------------------------------------------------------------------------
|
|
66
|
+
// 文本提取
|
|
67
|
+
// ---------------------------------------------------------------------------
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* 折叠 OpenAI 风格 content(字符串或 block 数组)为纯文本。
|
|
71
|
+
* 只取用户可见的 text 块:reasoning(思维链)不属于回答正文,不能混进分享/导出。
|
|
72
|
+
*/
|
|
73
|
+
function contentText(content, options) {
|
|
74
|
+
const placeholders = !options || options.attachments !== false;
|
|
75
|
+
if (typeof content === 'string') return content;
|
|
76
|
+
if (!Array.isArray(content)) return '';
|
|
77
|
+
const parts = [];
|
|
78
|
+
for (const block of content) {
|
|
79
|
+
if (block == null) continue;
|
|
80
|
+
if (typeof block === 'string') {
|
|
81
|
+
parts.push(block);
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (block.type === 'text' && typeof block.text === 'string') {
|
|
85
|
+
parts.push(block.text);
|
|
86
|
+
} else if (block.type === 'image') {
|
|
87
|
+
if (placeholders) parts.push('[图片]');
|
|
88
|
+
} else if (block.type === 'file') {
|
|
89
|
+
if (placeholders) parts.push('[文件]');
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return parts.join('');
|
|
93
|
+
}
|
|
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
|
+
|
|
137
|
+
/** 取一个事件的纯文本正文(按事件类型分发)。 */
|
|
138
|
+
function textOf(event) {
|
|
139
|
+
if (!event || typeof event !== 'object') return '';
|
|
140
|
+
const data = event.data;
|
|
141
|
+
if (!data || typeof data !== 'object') return '';
|
|
142
|
+
switch (event.type) {
|
|
143
|
+
case 'user/message':
|
|
144
|
+
return contentText(data.content);
|
|
145
|
+
case 'assistant/message':
|
|
146
|
+
return contentText(data.message && data.message.content);
|
|
147
|
+
case 'tool/result':
|
|
148
|
+
return contentText(data.message && data.message.content);
|
|
149
|
+
case 'system/message':
|
|
150
|
+
return contentText(data.message && data.message.content);
|
|
151
|
+
case 'developer/message':
|
|
152
|
+
return contentText(data.message && data.message.content);
|
|
153
|
+
default:
|
|
154
|
+
return '';
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** 事件对应的角色(供 /messages 摘要与客户端槽位对齐)。 */
|
|
159
|
+
function messageRoleOf(event) {
|
|
160
|
+
if (!event || typeof event !== 'object') return 'other';
|
|
161
|
+
switch (event.type) {
|
|
162
|
+
case 'user/message': return 'user';
|
|
163
|
+
case 'assistant/message': return 'assistant';
|
|
164
|
+
case 'tool/result': return 'tool';
|
|
165
|
+
case 'system/message': return 'system';
|
|
166
|
+
case 'developer/message': return 'developer';
|
|
167
|
+
default: return 'other';
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** 取事件的稳定消息 id(供客户端与辅助/答行槽位对齐)。 */
|
|
172
|
+
function messageIdOf(event) {
|
|
173
|
+
if (!event || typeof event !== 'object' || !event.data) return undefined;
|
|
174
|
+
const data = event.data;
|
|
175
|
+
if (typeof data.id === 'string') return data.id;
|
|
176
|
+
if (data.message && typeof data.message.id === 'string') return data.message.id;
|
|
177
|
+
return undefined;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** 取事件的用量摘要(答行统计 tokens 来源);只回传 outputTokens。 */
|
|
181
|
+
function usageSummaryOf(event) {
|
|
182
|
+
if (!event || typeof event !== 'object' || !event.data) return undefined;
|
|
183
|
+
const usage = event.data.usage;
|
|
184
|
+
if (!usage || typeof usage !== 'object') return undefined;
|
|
185
|
+
return usage.outputTokens !== undefined ? { outputTokens: usage.outputTokens } : undefined;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* 取工具事件的 callId。
|
|
190
|
+
* 宿主工具行 DOM 的 `data-chat-node-key` = `9:tool-call<callId>`,
|
|
191
|
+
* callId 来自 `tool/call.data.callId` / `tool/result.data.message.source.callId`。
|
|
192
|
+
*/
|
|
193
|
+
function toolCallIdOf(event) {
|
|
194
|
+
if (!event || typeof event !== 'object' || !event.data) return undefined;
|
|
195
|
+
const data = event.data;
|
|
196
|
+
if (event.type === 'tool/result') {
|
|
197
|
+
const source = data.message && data.message.source;
|
|
198
|
+
if (source && typeof source.callId === 'string' && source.callId !== '') return source.callId;
|
|
199
|
+
}
|
|
200
|
+
if (event.type === 'tool/call' && typeof data.callId === 'string' && data.callId !== '') {
|
|
201
|
+
return data.callId;
|
|
202
|
+
}
|
|
203
|
+
return undefined;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** 宿主工具节点 key 前缀(`conversationContextKey("tool-call", id)` = `9:tool-call<id>`)。 */
|
|
207
|
+
const TOOL_NODE_KEY_PREFIX = '9:tool-call';
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* 从宿主 DOM 的 `data-chat-node-key` 解析工具 callId。
|
|
211
|
+
* 这不是序号 / 坐标猜测:前缀与 key 构造规则来自宿主
|
|
212
|
+
* `conversationContextKey(kind, id) = ${kind.length}:${kind}${id}`,
|
|
213
|
+
* 而 id 就是服务端 `tool/call` 事件的 callId。
|
|
214
|
+
* @param {string} nodeKey
|
|
215
|
+
* @returns {string|null}
|
|
216
|
+
*/
|
|
217
|
+
function toolCallIdFromNodeKey(nodeKey) {
|
|
218
|
+
if (typeof nodeKey !== 'string' || !nodeKey.startsWith(TOOL_NODE_KEY_PREFIX)) return null;
|
|
219
|
+
const id = nodeKey.slice(TOOL_NODE_KEY_PREFIX.length);
|
|
220
|
+
return id.length > 0 ? id : null;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* 从 DOM 上现存的工具节点 key 中,挑出应被隐藏的那些。
|
|
225
|
+
* 宿主切换会话 / 刷新会重建 DOM,新节点不带任何本地隐藏标记,
|
|
226
|
+
* 因此客户端每次重建后都要按墓碑里的 callId 重新判定一次。
|
|
227
|
+
* @param {string[]} nodeKeys 现存的 `data-chat-node-key`
|
|
228
|
+
* @param {string[]} callIds 墓碑覆盖的 callId(来自 /messages 的 goneTools)
|
|
229
|
+
* @returns {string[]} 需要隐藏的 nodeKey
|
|
230
|
+
*/
|
|
231
|
+
function toolNodeKeysToHide(nodeKeys, callIds) {
|
|
232
|
+
if (!Array.isArray(nodeKeys) || !Array.isArray(callIds) || callIds.length === 0) return [];
|
|
233
|
+
const gone = new Set();
|
|
234
|
+
for (const callId of callIds) {
|
|
235
|
+
if (typeof callId === 'string' && callId !== '') gone.add(callId);
|
|
236
|
+
}
|
|
237
|
+
if (gone.size === 0) return [];
|
|
238
|
+
const out = [];
|
|
239
|
+
for (const key of nodeKeys) {
|
|
240
|
+
const callId = toolCallIdFromNodeKey(key);
|
|
241
|
+
if (callId !== null && gone.has(callId)) out.push(key);
|
|
242
|
+
}
|
|
243
|
+
return out;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** 在 /messages 摘要 rows 中找到 callId 对应的 tool/result 行(表面顺序第一条)。 */
|
|
247
|
+
function findToolRowByCallId(rows, callId) {
|
|
248
|
+
if (!Array.isArray(rows) || typeof callId !== 'string' || callId === '') return null;
|
|
249
|
+
for (const row of rows) {
|
|
250
|
+
if (row && row.type === 'tool/result' && row.callId === callId) return row;
|
|
251
|
+
}
|
|
252
|
+
return null;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* 汇总所有墓碑声明的 removed seq。
|
|
257
|
+
* 墓碑随事件日志一起持久化(带 surfaceOp),因此即使宿主重建表面时
|
|
258
|
+
* 没有重放 surfaceOp,或客户端拿到旧快照,这里仍能还原「哪些节点已被删」。
|
|
259
|
+
* @param events 按 seq 索引的事件数组
|
|
260
|
+
* @returns {Set<number>}
|
|
261
|
+
*/
|
|
262
|
+
function tombstonedSeqsOf(events) {
|
|
263
|
+
const hidden = new Set();
|
|
264
|
+
if (!Array.isArray(events)) return hidden;
|
|
265
|
+
for (const event of events) {
|
|
266
|
+
if (!isTombstone(event)) continue;
|
|
267
|
+
const removed = event.data && event.data.source && event.data.source.removed;
|
|
268
|
+
if (!Array.isArray(removed)) continue;
|
|
269
|
+
for (const seq of removed) {
|
|
270
|
+
if (Number.isSafeInteger(seq) && seq >= 0) hidden.add(seq);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return hidden;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* 从 events + 表面节点得到「仍可见」的节点列表。
|
|
278
|
+
* 不信任宿主表面重放结果:被墓碑覆盖的 seq 一律剔除。
|
|
279
|
+
* @param events
|
|
280
|
+
* @param nodes
|
|
281
|
+
* @returns {number[]}
|
|
282
|
+
*/
|
|
283
|
+
function liveNodesOf(events, nodes) {
|
|
284
|
+
if (!Array.isArray(nodes)) return [];
|
|
285
|
+
const hidden = tombstonedSeqsOf(events);
|
|
286
|
+
if (hidden.size === 0) return nodes.slice();
|
|
287
|
+
return nodes.filter((seq) => !hidden.has(seq));
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* 已删除的工具行 callId 列表(供客户端在每次 DOM 重建后重新隐藏)。
|
|
292
|
+
* 工具行 DOM key = `9:tool-call<callId>`,因此只需 callId。
|
|
293
|
+
* @param events
|
|
294
|
+
* @returns {string[]}
|
|
295
|
+
*/
|
|
296
|
+
function goneToolsOf(events) {
|
|
297
|
+
const hidden = tombstonedSeqsOf(events);
|
|
298
|
+
const out = [];
|
|
299
|
+
const seen = new Set();
|
|
300
|
+
for (const seq of hidden) {
|
|
301
|
+
const event = events[seq];
|
|
302
|
+
if (!event) continue;
|
|
303
|
+
if (event.type !== 'tool/result' && event.type !== 'tool/call') continue;
|
|
304
|
+
const callId = toolCallIdOf(event);
|
|
305
|
+
if (typeof callId !== 'string' || callId === '' || seen.has(callId)) continue;
|
|
306
|
+
seen.add(callId);
|
|
307
|
+
out.push(callId);
|
|
308
|
+
}
|
|
309
|
+
return out;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** 判断键盘事件目标是否为可编辑控件(输入框内 Enter 必须交给控件自己处理)。 */
|
|
313
|
+
function isEditableTarget(target) {
|
|
314
|
+
if (!target || typeof target !== 'object') return false;
|
|
315
|
+
if (target.isContentEditable === true) return true;
|
|
316
|
+
const tag = typeof target.tagName === 'string' ? target.tagName.toUpperCase() : '';
|
|
317
|
+
return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT';
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** 判断键盘事件目标是否落在按钮上(按钮上的 Enter 由原生 click 处理)。 */
|
|
321
|
+
function isButtonTarget(target) {
|
|
322
|
+
if (!target || typeof target !== 'object') return false;
|
|
323
|
+
if (typeof target.closest === 'function') {
|
|
324
|
+
try {
|
|
325
|
+
if (target.closest('button')) return true;
|
|
326
|
+
} catch {
|
|
327
|
+
/* 非 DOM 环境,回退到 tagName */
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
const tag = typeof target.tagName === 'string' ? target.tagName.toUpperCase() : '';
|
|
331
|
+
return tag === 'BUTTON';
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* 浮层键盘行为判定(纯函数,供客户端与离线测试共用)。
|
|
336
|
+
*
|
|
337
|
+
* - 浮层未打开:一律 none(不拦截宿主快捷键)。
|
|
338
|
+
* - Esc:dismiss。
|
|
339
|
+
* - Enter:焦点在输入框 / 可编辑区域 / 按钮上、或主操作不可用 / 正在执行时返回 none;
|
|
340
|
+
* 否则返回 primary。disabled 时客户端选择「什么都不做」,与点击禁用按钮一致。
|
|
341
|
+
* - 其它键:none。
|
|
342
|
+
*
|
|
343
|
+
* @param params {{ key?: string, target?: object, overlayOpen?: boolean, primaryEnabled?: boolean, busy?: boolean }}
|
|
344
|
+
* @returns {'none'|'dismiss'|'primary'}
|
|
345
|
+
*/
|
|
346
|
+
function resolveKeyAction(params) {
|
|
347
|
+
const opts = params || {};
|
|
348
|
+
if (opts.overlayOpen !== true) return 'none';
|
|
349
|
+
if (opts.key === 'Escape' || opts.key === 'Esc') return 'dismiss';
|
|
350
|
+
if (opts.key !== 'Enter') return 'none';
|
|
351
|
+
// 焦点落在按钮上时交给原生 click:否则「取消」按钮上按 Enter 会同时触发主操作。
|
|
352
|
+
if (isEditableTarget(opts.target) || isButtonTarget(opts.target)) return 'none';
|
|
353
|
+
if (opts.busy === true) return 'none';
|
|
354
|
+
if (opts.primaryEnabled === false) return 'none';
|
|
355
|
+
return 'primary';
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** 去掉空白后的字符数(用于「答行统计」的“字数”)。 */
|
|
359
|
+
function wordCount(text) {
|
|
360
|
+
return String(text == null ? '' : text).replace(/\s/g, '').length;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* 生成单行预览文本(供分享/导出多选列表使用)。
|
|
365
|
+
* 折叠换行与连续空白后截断,超出部分以 `…` 结尾;不改变原始文本,导出仍用全文。
|
|
366
|
+
* @param {string} text
|
|
367
|
+
* @param {number} limit 最大字符数(<=0 视为空)
|
|
368
|
+
* @returns {string}
|
|
369
|
+
*/
|
|
370
|
+
function previewText(text, limit) {
|
|
371
|
+
const raw = String(text == null ? '' : text).replace(/\r\n?/g, '\n');
|
|
372
|
+
const flat = raw.replace(/[ \t\f\v]+/g, ' ').replace(/\s*\n\s*/g, ' ').trim();
|
|
373
|
+
if (!Number.isFinite(limit) || limit <= 0) return '';
|
|
374
|
+
if (flat.length <= limit) return flat;
|
|
375
|
+
return flat.slice(0, limit).trimEnd() + '…';
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* 紧凑的 token 计数:`169` / `1.2k` / `39.1k` / `120k`。
|
|
380
|
+
* @param {number} n
|
|
381
|
+
* @returns {string}
|
|
382
|
+
*/
|
|
383
|
+
function formatTokens(n) {
|
|
384
|
+
if (!Number.isFinite(n) || n < 0) return '';
|
|
385
|
+
if (n < 1000) return String(Math.round(n));
|
|
386
|
+
const k = n / 1000;
|
|
387
|
+
return (k >= 100 ? String(Math.round(k)) : k.toFixed(1).replace(/\.0$/, '')) + 'k';
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
// ---------------------------------------------------------------------------
|
|
391
|
+
// 事件与表面结构
|
|
392
|
+
// ---------------------------------------------------------------------------
|
|
393
|
+
|
|
394
|
+
/** 判断某事件是否为本插件写入的墓碑。 */
|
|
395
|
+
function isTombstone(event) {
|
|
396
|
+
return !!event &&
|
|
397
|
+
event.type === 'user/message' &&
|
|
398
|
+
!!event.data &&
|
|
399
|
+
!!event.data.source &&
|
|
400
|
+
event.data.source.producer === PRODUCER;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* 扫描日志,建立「轮次 -> { startSeq, endSeq }」索引。
|
|
405
|
+
* turn/start、turn/end 是 log-only 事件,不在 surface.nodes 里,
|
|
406
|
+
* 但它们的 seq 可用来界定该轮表面的上下界。
|
|
407
|
+
*/
|
|
408
|
+
function buildTurnIndex(events) {
|
|
409
|
+
const starts = new Map();
|
|
410
|
+
events.forEach((evt, seq) => {
|
|
411
|
+
if (evt && evt.type === 'turn/start') {
|
|
412
|
+
const turn = evt.data && evt.data.turn;
|
|
413
|
+
if (typeof turn === 'number' && !starts.has(turn)) starts.set(turn, seq);
|
|
414
|
+
}
|
|
415
|
+
});
|
|
416
|
+
const index = [];
|
|
417
|
+
events.forEach((evt, seq) => {
|
|
418
|
+
if (evt && evt.type === 'turn/end') {
|
|
419
|
+
const turn = evt.data && evt.data.turn;
|
|
420
|
+
if (typeof turn === 'number' && starts.has(turn)) {
|
|
421
|
+
index.push({ turn, startSeq: starts.get(turn), endSeq: seq });
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
});
|
|
425
|
+
index.sort((a, b) => a.startSeq - b.startSeq);
|
|
426
|
+
return index;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/** 返回包含给定 seq 的轮次号;孤立(无 turn/start)返回 null。 */
|
|
430
|
+
function turnOf(turnIndex, seq) {
|
|
431
|
+
for (const info of turnIndex) {
|
|
432
|
+
if (seq > info.startSeq && seq < info.endSeq) return info.turn;
|
|
433
|
+
}
|
|
434
|
+
return null;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* 把轮次区间展开成 seq → turn 的 Map,避免逐条消息线性扫描 turnIndex。
|
|
439
|
+
* 结果必须与 turnOf(turnIndex, seq) 一致(见离线测试)。
|
|
440
|
+
* @param turnIndex buildTurnIndex 的返回值
|
|
441
|
+
* @returns {Map<number, number>}
|
|
442
|
+
*/
|
|
443
|
+
function buildTurnSeqMap(turnIndex) {
|
|
444
|
+
const map = new Map();
|
|
445
|
+
if (!Array.isArray(turnIndex)) return map;
|
|
446
|
+
for (const info of turnIndex) {
|
|
447
|
+
// 与 turnOf 的「按 startSeq 顺序取第一个命中」语义保持一致:
|
|
448
|
+
// 轮次区间若有重叠 / 嵌套,先出现的轮次优先,后出现的不得覆盖。
|
|
449
|
+
for (let seq = info.startSeq + 1; seq < info.endSeq; seq += 1) {
|
|
450
|
+
if (!map.has(seq)) map.set(seq, info.turn);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
return map;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/** 一次构建轮次索引与 seq 映射,供 /messages 复用。 */
|
|
457
|
+
function createTurnLookup(events) {
|
|
458
|
+
const index = buildTurnIndex(events);
|
|
459
|
+
return { index, seqTurn: buildTurnSeqMap(index) };
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/** 从 lookup(或现建)取某 seq 所属轮次。 */
|
|
463
|
+
function turnOfLookup(lookup, seq) {
|
|
464
|
+
if (lookup && lookup.seqTurn instanceof Map) {
|
|
465
|
+
const turn = lookup.seqTurn.get(seq);
|
|
466
|
+
return Number.isSafeInteger(turn) ? turn : null;
|
|
467
|
+
}
|
|
468
|
+
if (lookup && Array.isArray(lookup.index)) return turnOf(lookup.index, seq);
|
|
469
|
+
return null;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/** 返回同一 (turn, step) 的全部表面节点 seq(按出现顺序)。 */
|
|
473
|
+
function stepNodesOf(events, nodes, turn, step) {
|
|
474
|
+
const out = [];
|
|
475
|
+
for (const seq of nodes) {
|
|
476
|
+
const data = events[seq] && events[seq].data;
|
|
477
|
+
if (data && data.turn === turn && data.step === step) out.push(seq);
|
|
478
|
+
}
|
|
479
|
+
return out;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// ---------------------------------------------------------------------------
|
|
483
|
+
// 删除/撤回区间规划(核心纯函数)
|
|
484
|
+
// ---------------------------------------------------------------------------
|
|
485
|
+
|
|
486
|
+
/**
|
|
487
|
+
* 由目标 seq + action 规划要遮蔽的区间。
|
|
488
|
+
*
|
|
489
|
+
* @param events 完整日志事件数组(events[seq] = event)
|
|
490
|
+
* @param nodes 当前 surface.nodes(模型可见有序 seq 数组)
|
|
491
|
+
* @param params { action: "recall"|"delete"|"deleteFrom", seq: number }
|
|
492
|
+
* @returns
|
|
493
|
+
* 成功:{ ok:true, startSeq, endSeq, removed, kinds, via, turn, refillText }
|
|
494
|
+
* 失败:{ ok:false, code }
|
|
495
|
+
*/
|
|
496
|
+
function planAction(events, nodes, params) {
|
|
497
|
+
const action = params && params.action;
|
|
498
|
+
const targetSeq = params && params.seq;
|
|
499
|
+
if ((action !== 'recall' && action !== 'delete' && action !== 'deleteFrom') ||
|
|
500
|
+
!Number.isSafeInteger(targetSeq) || targetSeq < 0) {
|
|
501
|
+
return { ok: false, code: 'INVALID_REQUEST' };
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// 已写墓碑的节点不再可操作:宿主重建表面时可能仍把旧节点留在 nodes 里,
|
|
505
|
+
// 这里统一按「墓碑 → 可见集合」判定,避免对同一段内容重复撤回 / 重复删除。
|
|
506
|
+
const liveNodes = liveNodesOf(events, nodes);
|
|
507
|
+
const idx = liveNodes.indexOf(targetSeq);
|
|
508
|
+
if (idx === -1) return { ok: false, code: 'TARGET_NOT_FOUND' };
|
|
509
|
+
const evt = events[targetSeq];
|
|
510
|
+
if (!evt) return { ok: false, code: 'TARGET_NOT_FOUND' };
|
|
511
|
+
|
|
512
|
+
// 系统提示(节点 0)与 system/message 一律拒绝。
|
|
513
|
+
if (targetSeq === 0 || evt.type === 'system/message') {
|
|
514
|
+
return { ok: false, code: 'NOT_DELETABLE' };
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
// 撤回仅允许 user/message 且非系统/开发者来源。
|
|
518
|
+
if (action === 'recall') {
|
|
519
|
+
if (evt.type !== 'user/message') return { ok: false, code: 'NOT_A_USER_MESSAGE' };
|
|
520
|
+
const kind = evt.data && evt.data.source && evt.data.source.kind;
|
|
521
|
+
if (kind === 'system' || kind === 'developer') return { ok: false, code: 'NOT_DELETABLE' };
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
const turnIndex = buildTurnIndex(events);
|
|
525
|
+
|
|
526
|
+
// 删至末尾:从目标节点到 surface 末尾全部遮蔽。
|
|
527
|
+
if (action === 'deleteFrom') {
|
|
528
|
+
const endSeq = liveNodes[liveNodes.length - 1];
|
|
529
|
+
return buildPlan(events, liveNodes, targetSeq, endSeq, evt.type, 'deleteFrom',
|
|
530
|
+
turnOf(turnIndex, targetSeq));
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
// 问行:整轮;孤立提问只删自身。
|
|
534
|
+
if (evt.type === 'user/message') {
|
|
535
|
+
const turn = turnOf(turnIndex, targetSeq);
|
|
536
|
+
const plan = turn === null
|
|
537
|
+
? buildPlan(events, liveNodes, targetSeq, targetSeq, evt.type, action, null)
|
|
538
|
+
: (() => {
|
|
539
|
+
const span = turnSpan(events, liveNodes, turnIndex, turn);
|
|
540
|
+
return buildPlan(events, liveNodes, span.startSeq, span.endSeq, evt.type, action, turn);
|
|
541
|
+
})();
|
|
542
|
+
// 撤回回填必须用被点的那条提问文本:轮次区间起点可能是运行时注入消息,
|
|
543
|
+
// 不能取 startSeq 的正文,否则会把注入上下文回填到输入框。
|
|
544
|
+
// 附件单独返回,客户端恢复成真实图片 / 文件;正文不再插入占位符。
|
|
545
|
+
if (plan.ok && action === 'recall') {
|
|
546
|
+
plan.refillText = refillTextOf(evt);
|
|
547
|
+
plan.attachments = attachmentsOfEvent(evt);
|
|
548
|
+
}
|
|
549
|
+
return plan;
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
// 答行 / 工具行:同 (turn, step) 的整 step。
|
|
553
|
+
if (evt.type === 'assistant/message' || evt.type === 'tool/result') {
|
|
554
|
+
const data = evt.data || {};
|
|
555
|
+
const { turn, step } = data;
|
|
556
|
+
if (!Number.isSafeInteger(turn) || !Number.isSafeInteger(step)) {
|
|
557
|
+
return { ok: false, code: 'NOT_DELETABLE' };
|
|
558
|
+
}
|
|
559
|
+
const stepNodes = stepNodesOf(events, liveNodes, turn, step);
|
|
560
|
+
if (stepNodes.length === 0) return { ok: false, code: 'TARGET_NOT_FOUND' };
|
|
561
|
+
const start = stepNodes[0];
|
|
562
|
+
const end = stepNodes[stepNodes.length - 1];
|
|
563
|
+
const startIdx = liveNodes.indexOf(start);
|
|
564
|
+
const endIdx = liveNodes.indexOf(end);
|
|
565
|
+
for (let i = startIdx; i <= endIdx; i++) {
|
|
566
|
+
if (!stepNodes.includes(liveNodes[i])) return { ok: false, code: 'SPAN_NOT_CONTIGUOUS' };
|
|
567
|
+
}
|
|
568
|
+
return buildPlan(events, liveNodes, start, end, evt.type, action, turn);
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
return { ok: false, code: 'NOT_DELETABLE' };
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/** 计算某个轮次在 surface 中覆盖的 [startSeq, endSeq](含边界)。 */
|
|
575
|
+
function turnSpan(events, nodes, turnIndex, turn) {
|
|
576
|
+
const info = turnIndex.find((item) => item.turn === turn);
|
|
577
|
+
if (!info) return { startSeq: null, endSeq: null };
|
|
578
|
+
const inTurn = nodes.filter((seq) => seq > info.startSeq && seq < info.endSeq);
|
|
579
|
+
if (inTurn.length === 0) return { startSeq: null, endSeq: null };
|
|
580
|
+
return { startSeq: inTurn[0], endSeq: inTurn[inTurn.length - 1] };
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/** 由区间组装一个可落地的删除计划。 */
|
|
584
|
+
function buildPlan(events, nodes, startSeq, endSeq, targetType, action, turn) {
|
|
585
|
+
const startIdx = nodes.indexOf(startSeq);
|
|
586
|
+
const endIdx = nodes.indexOf(endSeq);
|
|
587
|
+
if (startIdx === -1 || endIdx === -1 || endIdx < startIdx) {
|
|
588
|
+
return { ok: false, code: 'TARGET_NOT_FOUND' };
|
|
589
|
+
}
|
|
590
|
+
const removed = nodes.slice(startIdx, endIdx + 1);
|
|
591
|
+
const kinds = removed.map((seq) => (events[seq] ? events[seq].type : 'unknown'));
|
|
592
|
+
const via = targetType === 'user/message' ? 'user' :
|
|
593
|
+
targetType === 'assistant/message' ? 'assistant' :
|
|
594
|
+
targetType === 'tool/result' ? 'tool' : 'unknown';
|
|
595
|
+
const target = events[startSeq] || {};
|
|
596
|
+
const step = target.data && Number.isSafeInteger(target.data.step) ? target.data.step : undefined;
|
|
597
|
+
return {
|
|
598
|
+
ok: true,
|
|
599
|
+
startSeq,
|
|
600
|
+
endSeq,
|
|
601
|
+
removed,
|
|
602
|
+
kinds,
|
|
603
|
+
via,
|
|
604
|
+
turn,
|
|
605
|
+
step,
|
|
606
|
+
refillText: action === 'recall' ? refillTextOf(events[startSeq]) : null
|
|
607
|
+
};
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
// ---------------------------------------------------------------------------
|
|
611
|
+
// 分享 / 导出:活表面分组
|
|
612
|
+
// ---------------------------------------------------------------------------
|
|
613
|
+
|
|
614
|
+
/**
|
|
615
|
+
* 从活表面分离出「轮次」列表(排除墓碑与系统提示),供分享/导出使用。
|
|
616
|
+
* @returns [{ turn, question, answer }],按轮次升序。
|
|
617
|
+
*/
|
|
618
|
+
function roundsOf(events, nodes, lookup) {
|
|
619
|
+
const turns = lookup || createTurnLookup(events);
|
|
620
|
+
const rounds = new Map();
|
|
621
|
+
const ensure = (turn) => {
|
|
622
|
+
if (!rounds.has(turn)) rounds.set(turn, { turn, question: '', answer: '' });
|
|
623
|
+
return rounds.get(turn);
|
|
624
|
+
};
|
|
625
|
+
// 不依赖宿主表面是否重放了 surfaceOp:被墓碑覆盖的节点一律不导出。
|
|
626
|
+
for (const seq of liveNodesOf(events, nodes)) {
|
|
627
|
+
const evt = events[seq];
|
|
628
|
+
if (!evt || isTombstone(evt)) continue;
|
|
629
|
+
if (evt.type === 'user/message') {
|
|
630
|
+
const turn = turnOfLookup(turns, seq);
|
|
631
|
+
if (turn === null) continue; // 无轮次归属的游离消息不进导出
|
|
632
|
+
// 运行时上下文 / 技能目录 / 时间上下文也是 user/message,但不算用户提问。
|
|
633
|
+
const kind = evt.data && evt.data.source && evt.data.source.kind;
|
|
634
|
+
if (kind !== undefined && kind !== 'user') continue;
|
|
635
|
+
const r = ensure(turn);
|
|
636
|
+
const text = textOf(evt);
|
|
637
|
+
// 一轮只取第一条真实提问:runtime context / system-reminder 等注入消息不混入导出。
|
|
638
|
+
if (text && !r.question) r.question = text;
|
|
639
|
+
} else if (evt.type === 'assistant/message') {
|
|
640
|
+
const data = evt.data || {};
|
|
641
|
+
const turn = Number.isSafeInteger(data.turn) ? data.turn : turnOfLookup(turns, seq);
|
|
642
|
+
if (turn === null) continue;
|
|
643
|
+
const r = ensure(turn);
|
|
644
|
+
const text = textOf(evt);
|
|
645
|
+
// 一轮只保留最后一条回答,避免把中间步骤 / 重试内容拼进导出。
|
|
646
|
+
if (text) r.answer = text;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
return [...rounds.values()].sort((a, b) => a.turn - b.turn);
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
/**
|
|
653
|
+
* 计算「已消失轮次」:日志里有 turn/start 但当前 surface 中已无任何活节点的轮次。
|
|
654
|
+
* 用于导航刻度隐藏(turnOutline 只看 turn/start,忽略 surfaceOp,必须靠客户端补齐)。
|
|
655
|
+
* @returns 升序的轮次号数组。
|
|
656
|
+
*/
|
|
657
|
+
function goneTurnsOf(events, nodes, lookup) {
|
|
658
|
+
const turns = lookup || createTurnLookup(events);
|
|
659
|
+
const turnIndex = turns.index;
|
|
660
|
+
if (turnIndex.length === 0) return [];
|
|
661
|
+
const live = new Set();
|
|
662
|
+
for (const seq of liveNodesOf(events, nodes)) {
|
|
663
|
+
const evt = events[seq];
|
|
664
|
+
if (!evt || isTombstone(evt)) continue;
|
|
665
|
+
const data = evt.data || {};
|
|
666
|
+
const turn = Number.isSafeInteger(data.turn) ? data.turn : turnOfLookup(turns, seq);
|
|
667
|
+
if (Number.isSafeInteger(turn)) live.add(turn);
|
|
668
|
+
}
|
|
669
|
+
return turnIndex.filter((info) => !live.has(info.turn)).map((info) => info.turn);
|
|
670
|
+
}
|
|
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
|
+
|
|
691
|
+
/**
|
|
692
|
+
* `/messages` 摘要快照:只返回预览、字数、用量与 callId,不返回正文。
|
|
693
|
+
* 分享图 / 导出需要全文时,走 `full=1&turns=a,b` 的按需接口(见 index.mjs)。
|
|
694
|
+
*
|
|
695
|
+
* 增量:传入 `since`(上次快照的 version)时,rows 只回 seq > since 的行,
|
|
696
|
+
* rounds 只回本次有新增行的轮次,并额外回 `removedSeqs`(since 之后墓碑
|
|
697
|
+
* 覆盖的 seq),供客户端合并并剔除已删行;不带 since 仍是全量快照。
|
|
698
|
+
* goneTurns / goneTools 始终全量返回,删除同步不受增量影响。
|
|
699
|
+
*
|
|
700
|
+
* @param events 按 seq 索引的事件数组
|
|
701
|
+
* @param nodes 当前 surface.nodes
|
|
702
|
+
* @param lookup createTurnLookup 的返回值(可缺省)
|
|
703
|
+
* @param options { filter?: Set<number>, since?: number, previewLimit?: number }
|
|
704
|
+
* @returns {{ version: number, nodeCount: number, rows: Array, rounds: Array, goneTurns: number[], goneTools: string[], removedSeqs: number[] }}
|
|
705
|
+
*/
|
|
706
|
+
function messagesSummaryOf(events, nodes, lookup, options) {
|
|
707
|
+
const opts = options || {};
|
|
708
|
+
const turns = lookup || createTurnLookup(events);
|
|
709
|
+
const filter = opts.filter instanceof Set ? opts.filter : null;
|
|
710
|
+
// 游标 v.s. seqs 列表:seqs 是「包含列表」,且长会话里已持有的 seq 数量会无限增长;
|
|
711
|
+
// 游标只传一个整数,天然表达「只要新的」。
|
|
712
|
+
const since = Number.isSafeInteger(opts.since) && opts.since >= 0 ? opts.since : null;
|
|
713
|
+
const previewLimit = Number.isFinite(opts.previewLimit) && opts.previewLimit > 0
|
|
714
|
+
? Math.floor(opts.previewLimit)
|
|
715
|
+
: 200;
|
|
716
|
+
const rows = [];
|
|
717
|
+
const rounds = new Map();
|
|
718
|
+
const touched = since === null ? null : new Set();
|
|
719
|
+
const ensure = (turn) => {
|
|
720
|
+
if (!rounds.has(turn)) rounds.set(turn, { turn, questionPreview: '', answerPreview: '' });
|
|
721
|
+
return rounds.get(turn);
|
|
722
|
+
};
|
|
723
|
+
const liveNodes = liveNodesOf(events, nodes);
|
|
724
|
+
for (const seq of liveNodes) {
|
|
725
|
+
const event = events[seq];
|
|
726
|
+
if (!event || isTombstone(event)) continue;
|
|
727
|
+
const data = event.data || {};
|
|
728
|
+
const explicitTurn = data.turn;
|
|
729
|
+
const turn = Number.isSafeInteger(explicitTurn) ? explicitTurn : turnOfLookup(turns, seq);
|
|
730
|
+
// 只有真实提问与助手回答进入预览:system / developer 消息、运行时注入的
|
|
731
|
+
// 上下文(user/message + 非 user 来源)与工具结果都不回传正文。
|
|
732
|
+
const isUserQuestion = event.type === 'user/message' &&
|
|
733
|
+
(data.source === undefined || data.source === null || data.source.kind === undefined || data.source.kind === 'user');
|
|
734
|
+
const isText = isUserQuestion || event.type === 'assistant/message';
|
|
735
|
+
const text = isText ? textOf(event) : '';
|
|
736
|
+
const replyCost = event.type === 'assistant/message' ? replyCostOf(event) : undefined;
|
|
737
|
+
const summary = {
|
|
738
|
+
seq,
|
|
739
|
+
type: event.type,
|
|
740
|
+
id: messageIdOf(event),
|
|
741
|
+
turn,
|
|
742
|
+
step: data.step,
|
|
743
|
+
role: messageRoleOf(event),
|
|
744
|
+
sourceKind: (data.source && data.source.kind) || 'user',
|
|
745
|
+
preview: isText ? previewText(text, previewLimit) : '',
|
|
746
|
+
words: isText ? wordCount(text) : 0,
|
|
747
|
+
usage: usageSummaryOf(event),
|
|
748
|
+
costMicros: replyCost ? replyCost.micros : null,
|
|
749
|
+
billable: replyCost ? replyCost.billable : null,
|
|
750
|
+
callId: toolCallIdOf(event)
|
|
751
|
+
};
|
|
752
|
+
const beyondCursor = since === null || seq > since;
|
|
753
|
+
if (beyondCursor && (!filter || filter.has(seq))) rows.push(summary);
|
|
754
|
+
|
|
755
|
+
if (isUserQuestion) {
|
|
756
|
+
if (turn === null) continue;
|
|
757
|
+
const round = ensure(turn);
|
|
758
|
+
if (summary.preview && !round.questionPreview) round.questionPreview = summary.preview;
|
|
759
|
+
} else if (event.type === 'assistant/message') {
|
|
760
|
+
if (turn === null) continue;
|
|
761
|
+
const round = ensure(turn);
|
|
762
|
+
if (summary.preview) round.answerPreview = summary.preview;
|
|
763
|
+
}
|
|
764
|
+
if (touched && beyondCursor && turn !== null) touched.add(turn);
|
|
765
|
+
}
|
|
766
|
+
const lastSeq = liveNodes.length > 0 ? liveNodes[liveNodes.length - 1] : 0;
|
|
767
|
+
// 增量响应附带 since 之后墓碑覆盖的 seq;全量响应不需要(rows 已不含它们)。
|
|
768
|
+
const removedSeqs = [];
|
|
769
|
+
if (since !== null && Array.isArray(events)) {
|
|
770
|
+
const seen = new Set();
|
|
771
|
+
for (let seq = since + 1; seq < events.length; seq += 1) {
|
|
772
|
+
const event = events[seq];
|
|
773
|
+
if (!isTombstone(event)) continue;
|
|
774
|
+
const removed = event.data && event.data.source && event.data.source.removed;
|
|
775
|
+
if (!Array.isArray(removed)) continue;
|
|
776
|
+
for (const target of removed) {
|
|
777
|
+
if (!Number.isSafeInteger(target) || target < 0 || seen.has(target)) continue;
|
|
778
|
+
seen.add(target);
|
|
779
|
+
removedSeqs.push(target);
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
const sortedRounds = [...rounds.values()].sort((a, b) => a.turn - b.turn);
|
|
784
|
+
return {
|
|
785
|
+
version: Number.isSafeInteger(lastSeq) ? lastSeq : 0,
|
|
786
|
+
nodeCount: liveNodes.length,
|
|
787
|
+
rows,
|
|
788
|
+
rounds: touched === null ? sortedRounds : sortedRounds.filter((round) => touched.has(round.turn)),
|
|
789
|
+
goneTurns: goneTurnsOf(events, nodes, turns),
|
|
790
|
+
// 客户端在每次 DOM 重建(切换会话 / 刷新)后据此重新隐藏工具行,
|
|
791
|
+
// 不能只在删除成功当下隐藏一次。
|
|
792
|
+
goneTools: goneToolsOf(events),
|
|
793
|
+
removedSeqs
|
|
794
|
+
};
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
/**
|
|
798
|
+
* 合并增量摘要到已持有的快照:按 seq 合并行、按 turn 合并轮次,
|
|
799
|
+
* 剔除增量确认删除的 seq 以及整轮消失的轮次。
|
|
800
|
+
* goneTurns / goneTools 以服务端最新结果为准(服务端始终全量返回)。
|
|
801
|
+
*/
|
|
802
|
+
function mergeMessageSummary(base, patch) {
|
|
803
|
+
const rows = new Map();
|
|
804
|
+
for (const row of (base && base.rows) || []) rows.set(row.seq, row);
|
|
805
|
+
for (const row of (patch && patch.rows) || []) rows.set(row.seq, row);
|
|
806
|
+
for (const seq of (patch && patch.removedSeqs) || []) rows.delete(seq);
|
|
807
|
+
|
|
808
|
+
const goneTurns = Array.isArray(patch && patch.goneTurns) ? patch.goneTurns : [];
|
|
809
|
+
for (const turn of goneTurns) {
|
|
810
|
+
for (const [seq, row] of rows) {
|
|
811
|
+
if (row.turn === turn) rows.delete(seq);
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
const rounds = new Map();
|
|
816
|
+
for (const round of (base && base.rounds) || []) rounds.set(round.turn, round);
|
|
817
|
+
for (const round of (patch && patch.rounds) || []) rounds.set(round.turn, round);
|
|
818
|
+
for (const turn of goneTurns) rounds.delete(turn);
|
|
819
|
+
|
|
820
|
+
return {
|
|
821
|
+
version: patch && Number.isSafeInteger(patch.version) ? patch.version : (base ? base.version : 0),
|
|
822
|
+
nodeCount: patch && Number.isSafeInteger(patch.nodeCount) ? patch.nodeCount : (base ? base.nodeCount : 0),
|
|
823
|
+
rows: [...rows.values()].sort((a, b) => a.seq - b.seq),
|
|
824
|
+
rounds: [...rounds.values()].sort((a, b) => a.turn - b.turn),
|
|
825
|
+
goneTurns,
|
|
826
|
+
goneTools: Array.isArray(patch && patch.goneTools) ? patch.goneTools : []
|
|
827
|
+
};
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/** 生成本轮导出的 Markdown 文本(不含被删内容)。 */
|
|
831
|
+
function markdownOf(rounds, meta) {
|
|
832
|
+
const m = meta || {};
|
|
833
|
+
const lines = [];
|
|
834
|
+
if (m.title) lines.push(`# ${m.title}`);
|
|
835
|
+
lines.push(`> ${m.sessionId || ''}${m.exportedAt ? ' / ' + m.exportedAt : ''}`);
|
|
836
|
+
const qLabel = m.questionLabel || '问';
|
|
837
|
+
const aLabel = m.answerLabel || '答';
|
|
838
|
+
for (const round of rounds) {
|
|
839
|
+
lines.push('');
|
|
840
|
+
lines.push(`## ${qLabel} ${round.turn}`);
|
|
841
|
+
const question = (round.question || '').trim();
|
|
842
|
+
if (question) {
|
|
843
|
+
lines.push('');
|
|
844
|
+
lines.push(question);
|
|
845
|
+
}
|
|
846
|
+
lines.push('');
|
|
847
|
+
lines.push(`### ${aLabel}`);
|
|
848
|
+
const answer = (round.answer || '').trim();
|
|
849
|
+
lines.push('');
|
|
850
|
+
lines.push(answer || '');
|
|
851
|
+
}
|
|
852
|
+
return lines.join('\n').replace(/\n{3,}/g, '\n\n').trim() + '\n';
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
/** 导出文件名:dsh-{sessionId}-{YYYYMMDD-HHmm}.md */
|
|
856
|
+
function exportFilename(sessionId, date) {
|
|
857
|
+
const d = date instanceof Date ? date : new Date();
|
|
858
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
859
|
+
const stamp = `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}`;
|
|
860
|
+
const safeId = String(sessionId == null ? '' : sessionId).replace(/[^\w.-]/g, '_').slice(0, 64);
|
|
861
|
+
return `dsh-${safeId}-${stamp}.md`;
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
// ---------------------------------------------------------------------------
|
|
865
|
+
// 导航刻度
|
|
866
|
+
// ---------------------------------------------------------------------------
|
|
867
|
+
|
|
868
|
+
/**
|
|
869
|
+
* 从导航刻度 aria-label(中/英)解析轮号:取最后一个整数。
|
|
870
|
+
* 例:'第 3 问' -> 3,'Turn 12' -> 12,'第 10 问,共 5 轮' -> 5。
|
|
871
|
+
*/
|
|
872
|
+
function railTurnOf(label) {
|
|
873
|
+
if (typeof label !== 'string') return null;
|
|
874
|
+
const nums = label.match(/\d+/g);
|
|
875
|
+
if (!nums || nums.length === 0) return null;
|
|
876
|
+
const value = parseInt(nums[nums.length - 1], 10);
|
|
877
|
+
return Number.isFinite(value) ? value : null;
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
/**
|
|
881
|
+
* 导航刻度的轮号解析:`data-index` 语义未验证,只在它与 aria-label 结果
|
|
882
|
+
* 一致时才采用;不一致或缺失时完全回退到原有 railTurnOf,避免改变现状。
|
|
883
|
+
* @param dataIndex 元素 data-index 属性(可能是 0-based,未验证)
|
|
884
|
+
* @param label aria-label 文本
|
|
885
|
+
*/
|
|
886
|
+
function railTurnOfAttributes(dataIndex, label) {
|
|
887
|
+
const byLabel = railTurnOf(label);
|
|
888
|
+
const raw = typeof dataIndex === 'number'
|
|
889
|
+
? String(dataIndex)
|
|
890
|
+
: (typeof dataIndex === 'string' ? dataIndex.trim() : '');
|
|
891
|
+
const byIndex = /^\d+$/.test(raw) ? parseInt(raw, 10) : null;
|
|
892
|
+
if (byIndex !== null && Number.isFinite(byIndex) && byIndex >= 1) {
|
|
893
|
+
if (byLabel === null) return byIndex;
|
|
894
|
+
// aria-label 可能同时含「第 N 问」与「共 M 轮」:与首个整数或旧解析结果
|
|
895
|
+
// 任一一致即可信;都不一致说明 data-index 语义不同(如 0-based),回退旧逻辑。
|
|
896
|
+
const nums = typeof label === 'string' ? label.match(/\d+/g) : null;
|
|
897
|
+
const first = nums && nums.length > 0 ? parseInt(nums[0], 10) : null;
|
|
898
|
+
if (byIndex === byLabel || byIndex === first) return byIndex;
|
|
899
|
+
}
|
|
900
|
+
return byLabel;
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
/**
|
|
904
|
+
* 计算虚拟轨道上每个可见刻度的向上压缩偏移。
|
|
905
|
+
* @param items [{ turn, hidden }] 按轨道顺序
|
|
906
|
+
* @returns [{ turn, hidden, offset }],offset 为「排在它前面被隐藏的数量 * 10」像素。
|
|
907
|
+
*/
|
|
908
|
+
function collapseRail(items) {
|
|
909
|
+
let hiddenBefore = 0;
|
|
910
|
+
return (items || []).map((item) => {
|
|
911
|
+
if (item.hidden) {
|
|
912
|
+
hiddenBefore += 1;
|
|
913
|
+
return { turn: item.turn, hidden: true, offset: 0 };
|
|
914
|
+
}
|
|
915
|
+
return { turn: item.turn, hidden: false, offset: hiddenBefore * 10 };
|
|
916
|
+
});
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
// ---------------------------------------------------------------------------
|
|
920
|
+
// HTTP 围栏与状态码
|
|
921
|
+
// ---------------------------------------------------------------------------
|
|
922
|
+
|
|
923
|
+
/** 写请求体上限(字节)。 */
|
|
924
|
+
const MAX_BODY_BYTES = 1024 * 1024;
|
|
925
|
+
|
|
926
|
+
/** 判断 Host 头是否为回环地址(localhost / 127.0.0.0/8 / ::1)。 */
|
|
927
|
+
function isLoopbackHost(hostHeader) {
|
|
928
|
+
if (typeof hostHeader !== 'string' || hostHeader.trim().length === 0) return false;
|
|
929
|
+
const raw = hostHeader.trim();
|
|
930
|
+
let host;
|
|
931
|
+
if (raw.startsWith('[')) {
|
|
932
|
+
// 带方括号的 IPv6(可含端口):[::1] 或 [::1]:8080
|
|
933
|
+
const close = raw.indexOf(']');
|
|
934
|
+
if (close === -1) return false;
|
|
935
|
+
host = raw.slice(1, close);
|
|
936
|
+
} else if (raw.startsWith(':')) {
|
|
937
|
+
// 裸 IPv6(如 ::1)
|
|
938
|
+
host = raw;
|
|
939
|
+
} else {
|
|
940
|
+
// 主机名或 IPv4,剥端口
|
|
941
|
+
const colon = raw.indexOf(':');
|
|
942
|
+
host = colon === -1 ? raw : raw.slice(0, colon);
|
|
943
|
+
}
|
|
944
|
+
host = host.toLowerCase();
|
|
945
|
+
return host === 'localhost' || host === '::1' || /^127\.\d+\.\d+\.\d+$/.test(host);
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
/**
|
|
949
|
+
* 入站请求三重围栏(纯函数,便于离线测试):
|
|
950
|
+
* 1. 仅回环 Host(挡住 DNS rebinding / 局域网来源);
|
|
951
|
+
* 2. Sec-Fetch-Site 只接受 `same-origin` / `none`(用户直达)或缺失(非浏览器客户端);
|
|
952
|
+
* 显式拒绝 `cross-site` 与 `same-site`(同站不同端口 / 子域的本机页面);
|
|
953
|
+
* 3. 携带 Origin 时必须与服务同源(expectedOrigin 由宿主实时计算);
|
|
954
|
+
* `expectedOrigin` 未知时一律拒绝带 Origin 的请求(失败即关闭)。
|
|
955
|
+
*/
|
|
956
|
+
function isTrustedRequest(info) {
|
|
957
|
+
const { host, secFetchSite, origin, expectedOrigin } = info || {};
|
|
958
|
+
if (!isLoopbackHost(host)) return false;
|
|
959
|
+
if (secFetchSite !== undefined && secFetchSite !== 'same-origin' && secFetchSite !== 'none') {
|
|
960
|
+
return false;
|
|
961
|
+
}
|
|
962
|
+
if (origin === undefined) return true;
|
|
963
|
+
return expectedOrigin !== undefined && origin === expectedOrigin;
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
/** 错误码 -> HTTP 状态码映射。 */
|
|
967
|
+
function statusCodeOf(code) {
|
|
968
|
+
switch (code) {
|
|
969
|
+
case 'INVALID_REQUEST':
|
|
970
|
+
case 'INVALID_AMOUNT': return 400;
|
|
971
|
+
case 'FORBIDDEN': return 403;
|
|
972
|
+
case 'PAYLOAD_TOO_LARGE': return 413;
|
|
973
|
+
case 'AGENT_BUSY': return 423;
|
|
974
|
+
case 'SESSION_NOT_LIVE':
|
|
975
|
+
case 'TARGET_NOT_FOUND':
|
|
976
|
+
case 'NOT_DELETABLE':
|
|
977
|
+
case 'NOT_A_USER_MESSAGE':
|
|
978
|
+
case 'SPAN_NOT_CONTIGUOUS': return 409;
|
|
979
|
+
case 'INTERNAL': return 500;
|
|
980
|
+
default: return 500;
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
/**
|
|
985
|
+
* 判断异常是否为「智能体正忙」。
|
|
986
|
+
* 优先使用结构化字段(err.code / err.status / err.statusCode),
|
|
987
|
+
* 文案匹配只作为没有结构化字段时的兜底:
|
|
988
|
+
* 宿主 @deepseek-ai/dsh-agent-loop 抛出的忙错误目前是普通 Error(无 code),
|
|
989
|
+
* 因此兜底文案必须保留;但只要带了结构化字段,就以字段判定为准。
|
|
990
|
+
*/
|
|
991
|
+
const BUSY_CODES = new Set(['AGENT_BUSY', 'ALREADY_ACTIVE', 'EBUSY', 'BUSY']);
|
|
992
|
+
|
|
993
|
+
function isBusyError(err) {
|
|
994
|
+
if (!err || typeof err !== 'object') return false;
|
|
995
|
+
const code = typeof err.code === 'string' ? err.code.trim().toUpperCase() : '';
|
|
996
|
+
const statusRaw = err.status != null ? err.status : err.statusCode;
|
|
997
|
+
const status = typeof statusRaw === 'number' && Number.isFinite(statusRaw) ? statusRaw : null;
|
|
998
|
+
if (code !== '' && BUSY_CODES.has(code)) return true;
|
|
999
|
+
if (status === 423) return true;
|
|
1000
|
+
if (code !== '' || status !== null) return false;
|
|
1001
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1002
|
+
return message.includes('already has active work');
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
/** 依据 Content-Length 判断是否超限(离线可测的 413 判据)。 */
|
|
1006
|
+
function bodyTooLarge(contentLength, limit = MAX_BODY_BYTES) {
|
|
1007
|
+
const length = Number(contentLength);
|
|
1008
|
+
return Number.isFinite(length) && length > limit;
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
// ---------------------------------------------------------------------------
|
|
1012
|
+
// 费用统计:北京时间、峰谷定价、token 计价
|
|
1013
|
+
// ---------------------------------------------------------------------------
|
|
1014
|
+
|
|
1015
|
+
/** 北京时间固定 UTC+8(无夏令时),不依赖宿主 / 浏览器本地时区。 */
|
|
1016
|
+
const BJ_OFFSET_MS = 8 * 60 * 60 * 1000;
|
|
1017
|
+
|
|
1018
|
+
/** 该日期起(含)周末全天谷价;之前周末仍按工作日时段判定。 */
|
|
1019
|
+
const WEEKEND_VALLEY_SINCE = '2026-08-23';
|
|
1020
|
+
|
|
1021
|
+
/** 谷价 = 高峰价的一半(官方固定规则,非可调)。 */
|
|
1022
|
+
const VALLEY_FACTOR = 0.5;
|
|
1023
|
+
|
|
1024
|
+
/**
|
|
1025
|
+
* 官方 2026 价目(单位 ¥/百万 token,取高峰价)。
|
|
1026
|
+
* 官方调价时只改这里与测试期望值;最后核对日期 2026-11-01。
|
|
1027
|
+
*/
|
|
1028
|
+
const PRICE_CHECKED_AT = '2026-11-01';
|
|
1029
|
+
const PRICE_TABLE = {
|
|
1030
|
+
'deepseek-flash': { cacheHit: 0.04, cacheMiss: 2.0, output: 8.0, reasoning: 0 },
|
|
1031
|
+
'deepseek-v4-pro': { cacheHit: 0.30, cacheMiss: 9.0, output: 27.0, reasoning: 0 },
|
|
1032
|
+
default: { cacheHit: 0.04, cacheMiss: 2.0, output: 8.0, reasoning: 0 }
|
|
1033
|
+
};
|
|
1034
|
+
|
|
1035
|
+
/** 需要缓冲的计价事件类型(turn/start 单独处理,不占缓冲配额)。 */
|
|
1036
|
+
const TURN_EVENT_TYPES = new Set(['request/header', 'assistant/attempt', 'assistant/message', 'turn/end']);
|
|
1037
|
+
|
|
1038
|
+
/** 单个 Turn 缓冲最多保留的计价事件条数;超出即放弃该轮(宁缺不错算)。 */
|
|
1039
|
+
const MAX_TURN_EVENTS = 2000;
|
|
1040
|
+
|
|
1041
|
+
/** 金额校正允许的最大值(元)。 */
|
|
1042
|
+
const MAX_CORRECTION_YUAN = 1e7;
|
|
1043
|
+
|
|
1044
|
+
/** 日累计保留天数(北京时间自然日)。 */
|
|
1045
|
+
const DAILY_KEEP_DAYS = 90;
|
|
1046
|
+
|
|
1047
|
+
/** 把毫秒时间换算成北京时间的年月日与星期。 */
|
|
1048
|
+
function beijingParts(ms) {
|
|
1049
|
+
const t = Number.isFinite(ms) ? ms : Date.now();
|
|
1050
|
+
const d = new Date(t + BJ_OFFSET_MS);
|
|
1051
|
+
const year = d.getUTCFullYear();
|
|
1052
|
+
const month = d.getUTCMonth() + 1;
|
|
1053
|
+
const day = d.getUTCDate();
|
|
1054
|
+
const minutes = d.getUTCHours() * 60 + d.getUTCMinutes();
|
|
1055
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
1056
|
+
return {
|
|
1057
|
+
year,
|
|
1058
|
+
month,
|
|
1059
|
+
day,
|
|
1060
|
+
weekday: d.getUTCDay(),
|
|
1061
|
+
minutes,
|
|
1062
|
+
dateKey: `${year}-${pad(month)}-${pad(day)}`
|
|
1063
|
+
};
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
/** 北京时间的自然日键 `YYYY-MM-DD`。 */
|
|
1067
|
+
function beijingDateKey(ms) {
|
|
1068
|
+
return beijingParts(ms).dateKey;
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
/** 由北京时间年月日 + 当日分钟数还原 epoch ms(日/月溢出由 Date.UTC 处理)。 */
|
|
1072
|
+
function beijingMsOf(year, month, day, minutes) {
|
|
1073
|
+
return Date.UTC(year, month - 1, day, 0, 0, 0, 0) + minutes * 60000 - BJ_OFFSET_MS;
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
/** 是否为「周末全天谷价」生效后的周末(含阈值当天)。 */
|
|
1077
|
+
function isValleyDay(parts) {
|
|
1078
|
+
const weekend = parts.weekday === 0 || parts.weekday === 6;
|
|
1079
|
+
return weekend && parts.dateKey >= WEEKEND_VALLEY_SINCE;
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
/** 高峰窗口:09:00–12:00、14:00–18:00(北京时间)。 */
|
|
1083
|
+
function inPeakWindow(minutes) {
|
|
1084
|
+
return (minutes >= 540 && minutes < 720) || (minutes >= 840 && minutes < 1080);
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
/** 下一个工作日的 09:00(跳过谷价周末)。 */
|
|
1088
|
+
function nextWeekdayPeak(parts) {
|
|
1089
|
+
for (let i = 1; i <= 8; i += 1) {
|
|
1090
|
+
const at = beijingMsOf(parts.year, parts.month, parts.day + i, 540);
|
|
1091
|
+
if (!isValleyDay(beijingParts(at))) return at;
|
|
1092
|
+
}
|
|
1093
|
+
return beijingMsOf(parts.year, parts.month, parts.day + 1, 540);
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
/**
|
|
1097
|
+
* 判定某时刻的峰 / 谷状态与下一次切换时刻。
|
|
1098
|
+
* @param {number} ms epoch ms(缺省取当前)
|
|
1099
|
+
* @returns {{ period: "peak"|"offpeak", nextChangeAt: number }}
|
|
1100
|
+
*/
|
|
1101
|
+
function periodInfo(ms) {
|
|
1102
|
+
const t = Number.isFinite(ms) ? ms : Date.now();
|
|
1103
|
+
const parts = beijingParts(t);
|
|
1104
|
+
if (!isValleyDay(parts) && inPeakWindow(parts.minutes)) {
|
|
1105
|
+
const end = parts.minutes < 720 ? 720 : 1080;
|
|
1106
|
+
return { period: 'peak', nextChangeAt: beijingMsOf(parts.year, parts.month, parts.day, end) };
|
|
1107
|
+
}
|
|
1108
|
+
if (!isValleyDay(parts)) {
|
|
1109
|
+
if (parts.minutes < 540) {
|
|
1110
|
+
return { period: 'offpeak', nextChangeAt: beijingMsOf(parts.year, parts.month, parts.day, 540) };
|
|
1111
|
+
}
|
|
1112
|
+
if (parts.minutes < 840) {
|
|
1113
|
+
return { period: 'offpeak', nextChangeAt: beijingMsOf(parts.year, parts.month, parts.day, 840) };
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
return { period: 'offpeak', nextChangeAt: nextWeekdayPeak(parts) };
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
/** 峰谷切换文案:`12:00 转谷价` / `明日 9:00 起高峰` / `周一 9:00 起高峰`。 */
|
|
1120
|
+
function periodChangeText(nowMs, nextChangeAt, lang) {
|
|
1121
|
+
const isEn = lang === 'en';
|
|
1122
|
+
const now = beijingParts(nowMs);
|
|
1123
|
+
const next = beijingParts(nextChangeAt);
|
|
1124
|
+
const zhWeekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
|
|
1125
|
+
const enWeekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
|
|
1126
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
1127
|
+
const time = `${Math.floor(next.minutes / 60)}:${pad(next.minutes % 60)}`;
|
|
1128
|
+
let dayPrefix = '';
|
|
1129
|
+
if (next.dateKey !== now.dateKey) {
|
|
1130
|
+
const tomorrowKey = beijingParts(nowMs + 24 * 3600 * 1000).dateKey;
|
|
1131
|
+
if (next.dateKey === tomorrowKey) {
|
|
1132
|
+
dayPrefix = isEn ? 'Tomorrow ' : '明日 ';
|
|
1133
|
+
} else {
|
|
1134
|
+
dayPrefix = (isEn ? enWeekdays : zhWeekdays)[next.weekday] + ' ';
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
const action = periodInfo(nowMs).period === 'peak'
|
|
1138
|
+
? (isEn ? 'off-peak at ' : '转谷价')
|
|
1139
|
+
: (isEn ? 'peak at ' : '起高峰');
|
|
1140
|
+
return isEn ? `${action}${dayPrefix}${time}` : `${dayPrefix}${time} ${action}`;
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
/** 按模型名取价目;未知 / 旧模型名回落到 default(与 deepseek-flash 同价)。 */
|
|
1144
|
+
function priceFor(model, table) {
|
|
1145
|
+
const prices = table && typeof table === 'object' ? table : PRICE_TABLE;
|
|
1146
|
+
const key = String(model == null ? '' : model).trim().toLowerCase();
|
|
1147
|
+
if (Object.prototype.hasOwnProperty.call(prices, key)) return prices[key];
|
|
1148
|
+
return prices.default || PRICE_TABLE.default;
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
/** 计数型 token 值:非负安全整数才认。 */
|
|
1152
|
+
function tokenCount(value) {
|
|
1153
|
+
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : 0;
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
/**
|
|
1157
|
+
* 单次金额:逐项用浮点元计算,最后一次性取整到微元(1e-6 元)。
|
|
1158
|
+
* reasoning 价一律 0(官方输出价已覆盖思考 token)。
|
|
1159
|
+
* @param usage 原始 usage(inputTokens / cacheReadTokens / outputTokens / reasoningTokens)
|
|
1160
|
+
* @param model 模型名
|
|
1161
|
+
* @param period "peak" | "offpeak"
|
|
1162
|
+
* @param table 价目表(缺省 PRICE_TABLE)
|
|
1163
|
+
* @returns {number} costMicros
|
|
1164
|
+
*/
|
|
1165
|
+
function turnCost(usage, model, period, table) {
|
|
1166
|
+
const u = usage && typeof usage === 'object' ? usage : {};
|
|
1167
|
+
const p = priceFor(model, table);
|
|
1168
|
+
const factor = period === 'peak' ? 1 : VALLEY_FACTOR;
|
|
1169
|
+
const yuan =
|
|
1170
|
+
tokenCount(u.inputTokens) * p.cacheMiss / 1e6 +
|
|
1171
|
+
tokenCount(u.cacheReadTokens) * p.cacheHit / 1e6 +
|
|
1172
|
+
tokenCount(u.outputTokens) * p.output / 1e6 +
|
|
1173
|
+
tokenCount(u.reasoningTokens) * p.reasoning / 1e6;
|
|
1174
|
+
return Math.round(yuan * factor * 1e6);
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
/** 多个 (route, usage) 分组分别计价后求和(不同模型不会用错单价)。 */
|
|
1178
|
+
function turnCostOfGroups(groups, period, table) {
|
|
1179
|
+
let micros = 0;
|
|
1180
|
+
for (const group of groups || []) {
|
|
1181
|
+
if (!group) continue;
|
|
1182
|
+
micros += turnCost(group.usage || group.tokens, group.model, period, table);
|
|
1183
|
+
}
|
|
1184
|
+
return micros;
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
/**
|
|
1188
|
+
* 取 assistant 流最后一帧 usage(stream 为官方 compact records 数组)。
|
|
1189
|
+
* 兼容 `{type:"chunk",chunk:{type:"usage",usage}}` 与直接 usage 记录。
|
|
1190
|
+
*/
|
|
1191
|
+
function streamUsageOf(stream) {
|
|
1192
|
+
if (Array.isArray(stream)) {
|
|
1193
|
+
for (let i = stream.length - 1; i >= 0; i -= 1) {
|
|
1194
|
+
const record = stream[i];
|
|
1195
|
+
if (!record || typeof record !== 'object') continue;
|
|
1196
|
+
if (record.type === 'chunk' && record.chunk && record.chunk.type === 'usage') {
|
|
1197
|
+
return record.chunk.usage;
|
|
1198
|
+
}
|
|
1199
|
+
if (record.type === 'usage' && record.usage) return record.usage;
|
|
1200
|
+
}
|
|
1201
|
+
return undefined;
|
|
1202
|
+
}
|
|
1203
|
+
if (stream && typeof stream === 'object' && stream.usage && typeof stream.usage === 'object') {
|
|
1204
|
+
return stream.usage;
|
|
1205
|
+
}
|
|
1206
|
+
return undefined;
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
/** 消息路由:`message.source` 的 provider / model。 */
|
|
1210
|
+
function routeOfMessage(message) {
|
|
1211
|
+
if (!message || typeof message !== 'object') return undefined;
|
|
1212
|
+
const source = message.source;
|
|
1213
|
+
if (!source || typeof source !== 'object') return undefined;
|
|
1214
|
+
if (typeof source.provider !== 'string' || source.provider.length === 0) return undefined;
|
|
1215
|
+
if (typeof source.model !== 'string' || source.model.length === 0) return undefined;
|
|
1216
|
+
return { provider: source.provider, model: source.model };
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
/** 归一化原始 usage:inputTokens / outputTokens 必须是计数,可选分项缺省按 0。 */
|
|
1220
|
+
function normalizeCostUsage(usage) {
|
|
1221
|
+
if (!usage || typeof usage !== 'object') return undefined;
|
|
1222
|
+
if (!Number.isSafeInteger(usage.inputTokens) || usage.inputTokens < 0) return undefined;
|
|
1223
|
+
if (!Number.isSafeInteger(usage.outputTokens) || usage.outputTokens < 0) return undefined;
|
|
1224
|
+
const cacheReadTokens = tokenCount(usage.cacheReadTokens);
|
|
1225
|
+
const cacheWriteTokens = tokenCount(usage.cacheWriteTokens);
|
|
1226
|
+
const reasoningTokens = tokenCount(usage.reasoningTokens);
|
|
1227
|
+
return {
|
|
1228
|
+
inputTokens: usage.inputTokens,
|
|
1229
|
+
cacheReadTokens,
|
|
1230
|
+
cacheWriteTokens,
|
|
1231
|
+
outputTokens: usage.outputTokens,
|
|
1232
|
+
reasoningTokens,
|
|
1233
|
+
totalTokens: tokenCount(usage.totalTokens) || usage.inputTokens + cacheReadTokens + cacheWriteTokens + usage.outputTokens
|
|
1234
|
+
};
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
/** 从一个 step 的 message / attempt 取原始 usage(message 优先)。 */
|
|
1238
|
+
function stepUsageOf(messageEvent, attemptEvent) {
|
|
1239
|
+
const messageData = messageEvent && messageEvent.data;
|
|
1240
|
+
if (messageData && messageData.usage) {
|
|
1241
|
+
const normalized = normalizeCostUsage(messageData.usage);
|
|
1242
|
+
if (normalized) return normalized;
|
|
1243
|
+
}
|
|
1244
|
+
if (messageData) {
|
|
1245
|
+
const fromStream = normalizeCostUsage(streamUsageOf(messageData.stream));
|
|
1246
|
+
if (fromStream) return fromStream;
|
|
1247
|
+
}
|
|
1248
|
+
const attemptData = attemptEvent && attemptEvent.data;
|
|
1249
|
+
if (attemptData) {
|
|
1250
|
+
const normalized = normalizeCostUsage(streamUsageOf(attemptData.stream));
|
|
1251
|
+
if (normalized) return normalized;
|
|
1252
|
+
}
|
|
1253
|
+
return undefined;
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
/** 路由列表里的第一条合法 route。 */
|
|
1257
|
+
function routeOfUsage(usage) {
|
|
1258
|
+
if (!usage || typeof usage !== 'object' || !Array.isArray(usage.routes)) return undefined;
|
|
1259
|
+
for (const route of usage.routes) {
|
|
1260
|
+
if (!route) continue;
|
|
1261
|
+
if (typeof route.provider !== 'string' || route.provider.length === 0) continue;
|
|
1262
|
+
if (typeof route.model !== 'string' || route.model.length === 0) continue;
|
|
1263
|
+
return { provider: route.provider, model: route.model };
|
|
1264
|
+
}
|
|
1265
|
+
return undefined;
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
/**
|
|
1269
|
+
* provider → 计费口径:
|
|
1270
|
+
* - `deepseek-account` → account(账户余额可观测)
|
|
1271
|
+
* - 其他 DeepSeek 官方路由(如 deepseek-official)→ api-key
|
|
1272
|
+
* - 非 DeepSeek 的 provider(本地模型、第三方网关)→ local(不消耗 DeepSeek 余额)
|
|
1273
|
+
*/
|
|
1274
|
+
function routingOfProvider(provider) {
|
|
1275
|
+
if (typeof provider !== 'string' || provider.length === 0) return null;
|
|
1276
|
+
const key = provider.trim().toLowerCase();
|
|
1277
|
+
if (!key) return null;
|
|
1278
|
+
if (key === 'deepseek-account') return 'account';
|
|
1279
|
+
if (key.startsWith('deepseek')) return 'api-key';
|
|
1280
|
+
return 'local';
|
|
1281
|
+
}
|
|
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
|
+
|
|
1306
|
+
/**
|
|
1307
|
+
* 费用卡片样式枚举。数组顺序即设置页选项顺序:单行样式排在第一位。
|
|
1308
|
+
* 内部存储值沿用 `compact` / `default`,与旧版本配置兼容。
|
|
1309
|
+
*/
|
|
1310
|
+
const COST_LAYOUTS = ['compact', 'default'];
|
|
1311
|
+
const DEFAULT_COST_LAYOUT = 'compact';
|
|
1312
|
+
|
|
1313
|
+
/**
|
|
1314
|
+
* 把已保存 / 未配置的样式值归一为枚举值。
|
|
1315
|
+
* 旧配置里的 `default` 保持不变(映射到「多行样式」),未知值回退到当前默认值。
|
|
1316
|
+
* @param value 配置中的 costLayout
|
|
1317
|
+
* @returns {'compact' | 'default'}
|
|
1318
|
+
*/
|
|
1319
|
+
function normalizeCostLayout(value) {
|
|
1320
|
+
return value === 'default' ? 'default' : DEFAULT_COST_LAYOUT;
|
|
1321
|
+
}
|
|
1322
|
+
|
|
1323
|
+
/**
|
|
1324
|
+
* 费用相关开关的运行时视图:每次调用都重新读取 Config,默认值保持「开启」。
|
|
1325
|
+
* @param config 宿主 Config(可能被配置通道原地更新)
|
|
1326
|
+
* @returns {{ enabled: boolean, perTurn: boolean }}
|
|
1327
|
+
*/
|
|
1328
|
+
function costSwitches(config) {
|
|
1329
|
+
const cfg = config || {};
|
|
1330
|
+
return {
|
|
1331
|
+
enabled: cfg.usageStats !== false,
|
|
1332
|
+
perTurn: cfg.costPerTurn !== false
|
|
1333
|
+
};
|
|
1334
|
+
}
|
|
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
|
+
|
|
1411
|
+
/**
|
|
1412
|
+
* 聚合一轮(turn/start…turn/end)内各 step 的 usage。
|
|
1413
|
+
* 每个 step 只取最后一个有效 assistant 结果(message 优先,其次 attempt),
|
|
1414
|
+
* 重试产生的多个 attempt 不重复累加;不同 route 的 step 分别成组,由调用方分价求和。
|
|
1415
|
+
*
|
|
1416
|
+
* @param events 本轮缓冲事件(可含 turn/start、turn/end)
|
|
1417
|
+
* @param options { fallbackRoute } 本轮回退路由(最近一次 request/header)
|
|
1418
|
+
* @returns undefined 或 { at, endedAt, turn, provider, models, tokens, groups }
|
|
1419
|
+
*/
|
|
1420
|
+
function deriveTurnUsage(events, options) {
|
|
1421
|
+
if (!Array.isArray(events) || events.length === 0) return undefined;
|
|
1422
|
+
const fallbackRoute = options && options.fallbackRoute;
|
|
1423
|
+
let at;
|
|
1424
|
+
let endedAt;
|
|
1425
|
+
let turn;
|
|
1426
|
+
let headerRoute;
|
|
1427
|
+
const steps = new Map();
|
|
1428
|
+
const timeOf = (event) => {
|
|
1429
|
+
if (Number.isFinite(event.time)) return event.time;
|
|
1430
|
+
if (event.data && Number.isFinite(event.data.at)) return event.data.at;
|
|
1431
|
+
return undefined;
|
|
1432
|
+
};
|
|
1433
|
+
|
|
1434
|
+
for (const event of events) {
|
|
1435
|
+
if (!event || typeof event !== 'object') continue;
|
|
1436
|
+
const data = event.data || {};
|
|
1437
|
+
if (event.type === 'turn/start') {
|
|
1438
|
+
if (turn === undefined && Number.isSafeInteger(data.turn)) turn = data.turn;
|
|
1439
|
+
if (at === undefined) at = timeOf(event);
|
|
1440
|
+
continue;
|
|
1441
|
+
}
|
|
1442
|
+
if (event.type === 'turn/end') {
|
|
1443
|
+
if (endedAt === undefined) endedAt = timeOf(event);
|
|
1444
|
+
continue;
|
|
1445
|
+
}
|
|
1446
|
+
if (event.type === 'request/header') {
|
|
1447
|
+
const config = data.header && data.header.config;
|
|
1448
|
+
if (config && typeof config.provider === 'string' && typeof config.model === 'string') {
|
|
1449
|
+
headerRoute = { provider: config.provider, model: config.model };
|
|
1450
|
+
}
|
|
1451
|
+
continue;
|
|
1452
|
+
}
|
|
1453
|
+
if (event.type !== 'assistant/attempt' && event.type !== 'assistant/message') continue;
|
|
1454
|
+
const step = Number.isSafeInteger(data.step) ? data.step : 0;
|
|
1455
|
+
let entry = steps.get(step);
|
|
1456
|
+
if (!entry) {
|
|
1457
|
+
entry = { message: undefined, attempt: undefined, headerRoute };
|
|
1458
|
+
steps.set(step, entry);
|
|
1459
|
+
}
|
|
1460
|
+
if (event.type === 'assistant/message') entry.message = event;
|
|
1461
|
+
else entry.attempt = event;
|
|
1462
|
+
}
|
|
1463
|
+
|
|
1464
|
+
const groups = [];
|
|
1465
|
+
const models = [];
|
|
1466
|
+
const totals = {
|
|
1467
|
+
inputTokens: 0,
|
|
1468
|
+
cacheReadTokens: 0,
|
|
1469
|
+
cacheWriteTokens: 0,
|
|
1470
|
+
outputTokens: 0,
|
|
1471
|
+
reasoningTokens: 0,
|
|
1472
|
+
totalTokens: 0
|
|
1473
|
+
};
|
|
1474
|
+
let provider;
|
|
1475
|
+
for (const entry of steps.values()) {
|
|
1476
|
+
const usage = stepUsageOf(entry.message, entry.attempt);
|
|
1477
|
+
if (!usage) continue;
|
|
1478
|
+
const messageRoute = entry.message ? routeOfMessage(entry.message.data && entry.message.data.message) : undefined;
|
|
1479
|
+
const route = messageRoute ||
|
|
1480
|
+
routeOfUsage(entry.message && entry.message.data && entry.message.data.usage) ||
|
|
1481
|
+
routeOfUsage(entry.attempt && entry.attempt.data && entry.attempt.data.usage) ||
|
|
1482
|
+
entry.headerRoute ||
|
|
1483
|
+
headerRoute ||
|
|
1484
|
+
fallbackRoute;
|
|
1485
|
+
const model = route && route.model ? route.model : undefined;
|
|
1486
|
+
groups.push({ provider: route ? route.provider : undefined, model, usage });
|
|
1487
|
+
if (!provider && route && route.provider) provider = route.provider;
|
|
1488
|
+
if (model && models.indexOf(model) === -1) models.push(model);
|
|
1489
|
+
for (const key of Object.keys(totals)) totals[key] += usage[key] || 0;
|
|
1490
|
+
}
|
|
1491
|
+
if (groups.length === 0) return undefined;
|
|
1492
|
+
|
|
1493
|
+
return {
|
|
1494
|
+
at,
|
|
1495
|
+
endedAt,
|
|
1496
|
+
turn,
|
|
1497
|
+
provider: provider || undefined,
|
|
1498
|
+
models,
|
|
1499
|
+
tokens: totals,
|
|
1500
|
+
groups
|
|
1501
|
+
};
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
/** 新建一轮缓冲。 */
|
|
1505
|
+
function createTurnBuffer(turn, at) {
|
|
1506
|
+
return { turn, at: Number.isFinite(at) ? at : Date.now(), events: [], overflow: false };
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
/**
|
|
1510
|
+
* 向缓冲追加一条计价事件。
|
|
1511
|
+
* @returns true 表示已收下;false 表示类型不需要 / 已溢出(overflow 置位)
|
|
1512
|
+
*/
|
|
1513
|
+
function appendTurnEvent(buffer, event) {
|
|
1514
|
+
if (!buffer || !event) return false;
|
|
1515
|
+
if (buffer.overflow) return false;
|
|
1516
|
+
if (!TURN_EVENT_TYPES.has(event.type)) return false;
|
|
1517
|
+
if (buffer.events.length >= MAX_TURN_EVENTS) {
|
|
1518
|
+
buffer.overflow = true;
|
|
1519
|
+
return false;
|
|
1520
|
+
}
|
|
1521
|
+
buffer.events.push(event);
|
|
1522
|
+
return true;
|
|
1523
|
+
}
|
|
1524
|
+
|
|
1525
|
+
// ---------------------------------------------------------------------------
|
|
1526
|
+
// 费用统计:余额观测(账户口径)
|
|
1527
|
+
// ---------------------------------------------------------------------------
|
|
1528
|
+
|
|
1529
|
+
/** 间隔超过 25 小时视为应用长时间未运行,不补记差额。 */
|
|
1530
|
+
const MAX_OBSERVE_GAP_MS = 25 * 60 * 60 * 1000;
|
|
1531
|
+
|
|
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 };
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1569
|
+
/**
|
|
1570
|
+
* 一次余额观测的记账(纯函数,返回新状态与本次记账原因)。
|
|
1571
|
+
*
|
|
1572
|
+
* - 下降 → 累计「已观测消费」,按北京时间日期计入「日用」;
|
|
1573
|
+
* - 上升 → 只更新 lastBalance,不冲减消费(不再维护手工校正字段);
|
|
1574
|
+
* - 跨日 / 间隔超 25h / 路由切换 → 只更新 lastBalance,跳过本次差额;
|
|
1575
|
+
* - 非 account 路由 → 完全不记账。
|
|
1576
|
+
*
|
|
1577
|
+
* 与轮次结算共用同一份「日用」:本轮已结算的金额先由 settleSpend 记入,
|
|
1578
|
+
* 观测到差额时只把 **超出已结算部分** 补进当日桶(`diff - settledSinceObserveCents`),
|
|
1579
|
+
* 不重复计入;估算高于实际(差额为负)时不做减法,保持「日用」为花费上限提示。
|
|
1580
|
+
*
|
|
1581
|
+
* @param state 持久化状态(不修改入参)
|
|
1582
|
+
* @param params { cents, routing, at }
|
|
1583
|
+
* @returns {{ state, reason }}
|
|
1584
|
+
*/
|
|
1585
|
+
function observeBalance(state, params) {
|
|
1586
|
+
const s = state || {};
|
|
1587
|
+
const cents = params && Number.isFinite(params.cents) ? Math.round(params.cents) : null;
|
|
1588
|
+
const routing = params && params.routing;
|
|
1589
|
+
const at = params && Number.isFinite(params.at) ? params.at : Date.now();
|
|
1590
|
+
const out = {
|
|
1591
|
+
baselineBalanceCents: Number.isFinite(s.baselineBalanceCents) ? s.baselineBalanceCents : null,
|
|
1592
|
+
lastBalanceCents: Number.isFinite(s.lastBalanceCents) ? s.lastBalanceCents : null,
|
|
1593
|
+
lastBalanceAt: Number.isFinite(s.lastBalanceAt) ? s.lastBalanceAt : 0,
|
|
1594
|
+
lastRouting: typeof s.lastRouting === 'string' ? s.lastRouting : null,
|
|
1595
|
+
observedSpendTotalCents: Number.isFinite(s.observedSpendTotalCents) ? s.observedSpendTotalCents : 0,
|
|
1596
|
+
dailySpendCents: Object.assign({}, s.dailySpendCents || {}),
|
|
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 : ''
|
|
1600
|
+
};
|
|
1601
|
+
if (cents === null) return { state: out, reason: 'invalid' };
|
|
1602
|
+
if (routing !== 'account') return { state: out, reason: 'not-account' };
|
|
1603
|
+
|
|
1604
|
+
if (out.baselineBalanceCents === null) {
|
|
1605
|
+
out.baselineBalanceCents = cents;
|
|
1606
|
+
out.lastBalanceCents = cents;
|
|
1607
|
+
out.lastBalanceAt = at;
|
|
1608
|
+
out.lastRouting = routing;
|
|
1609
|
+
out.settledSinceObserveCents = 0;
|
|
1610
|
+
return { state: out, reason: 'baseline' };
|
|
1611
|
+
}
|
|
1612
|
+
if (out.lastBalanceCents === null || out.lastBalanceAt === 0) {
|
|
1613
|
+
out.lastBalanceCents = cents;
|
|
1614
|
+
out.lastBalanceAt = at;
|
|
1615
|
+
out.lastRouting = routing;
|
|
1616
|
+
out.settledSinceObserveCents = 0;
|
|
1617
|
+
return { state: out, reason: 'first' };
|
|
1618
|
+
}
|
|
1619
|
+
if (out.lastRouting !== routing) {
|
|
1620
|
+
out.lastBalanceCents = cents;
|
|
1621
|
+
out.lastBalanceAt = at;
|
|
1622
|
+
out.lastRouting = routing;
|
|
1623
|
+
out.settledSinceObserveCents = 0;
|
|
1624
|
+
return { state: out, reason: 'routing-switch' };
|
|
1625
|
+
}
|
|
1626
|
+
if (beijingDateKey(out.lastBalanceAt) !== beijingDateKey(at)) {
|
|
1627
|
+
out.lastBalanceCents = cents;
|
|
1628
|
+
out.lastBalanceAt = at;
|
|
1629
|
+
// 跨日不补记差额;同时清空待核对结算,避免把昨天的金额算进今天的差值。
|
|
1630
|
+
out.settledSinceObserveCents = 0;
|
|
1631
|
+
return { state: out, reason: 'cross-day' };
|
|
1632
|
+
}
|
|
1633
|
+
if (at - out.lastBalanceAt > MAX_OBSERVE_GAP_MS) {
|
|
1634
|
+
out.lastBalanceCents = cents;
|
|
1635
|
+
out.lastBalanceAt = at;
|
|
1636
|
+
out.settledSinceObserveCents = 0;
|
|
1637
|
+
return { state: out, reason: 'too-long' };
|
|
1638
|
+
}
|
|
1639
|
+
|
|
1640
|
+
const diff = out.lastBalanceCents - cents;
|
|
1641
|
+
let reason = 'none';
|
|
1642
|
+
if (diff > 0) {
|
|
1643
|
+
out.observedSpendTotalCents += diff;
|
|
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;
|
|
1651
|
+
reason = 'spend';
|
|
1652
|
+
} else if (diff < 0) {
|
|
1653
|
+
// 余额上升(充值 / 退货):只更新基准,不冲减消费,也不做手工校正。
|
|
1654
|
+
reason = 'adjust';
|
|
1655
|
+
}
|
|
1656
|
+
out.lastBalanceCents = cents;
|
|
1657
|
+
out.lastBalanceAt = at;
|
|
1658
|
+
return { state: out, reason };
|
|
1659
|
+
}
|
|
1660
|
+
|
|
1661
|
+
/** 元(数字或字符串)转分;非法返回 null。 */
|
|
1662
|
+
function yuanToCents(value, mode) {
|
|
1663
|
+
const truncate = mode === 'truncate';
|
|
1664
|
+
if (typeof value === 'number') {
|
|
1665
|
+
if (!Number.isFinite(value)) return null;
|
|
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);
|
|
1671
|
+
}
|
|
1672
|
+
if (typeof value !== 'string') return null;
|
|
1673
|
+
const raw = value.trim().replace(/,/g, '');
|
|
1674
|
+
if (!/^-?\d+(\.\d+)?$/.test(raw)) return null;
|
|
1675
|
+
const negative = raw.startsWith('-');
|
|
1676
|
+
const body = negative ? raw.slice(1) : raw;
|
|
1677
|
+
const split = body.split('.');
|
|
1678
|
+
const whole = split[0];
|
|
1679
|
+
const frac = split[1] || '';
|
|
1680
|
+
let cents = Number(whole) * 100 + Number((frac + '00').slice(0, 2));
|
|
1681
|
+
// 官方「账号与余额」对正金额截断至分:原始余额字符串可能带三位以上小数,
|
|
1682
|
+
// 这里必须同样截断,否则 5.999… 会进位成 6.00,比官方页面多一分。
|
|
1683
|
+
if (frac.length > 2 && !(truncate && !negative) && Number(frac.charAt(2)) >= 5) cents += 1;
|
|
1684
|
+
return negative ? -cents : cents;
|
|
1685
|
+
}
|
|
1686
|
+
|
|
1687
|
+
/**
|
|
1688
|
+
* 校正金额校验:有限数字(或数字字符串)、≥ 0、最多两位小数、≤ 1e7。
|
|
1689
|
+
* @returns {{ ok: true, cents } | { ok: false, code: "INVALID_AMOUNT" }}
|
|
1690
|
+
*/
|
|
1691
|
+
function validateCorrectionAmount(value) {
|
|
1692
|
+
let num;
|
|
1693
|
+
if (typeof value === 'number') {
|
|
1694
|
+
num = value;
|
|
1695
|
+
} else if (typeof value === 'string' && value.trim().length > 0) {
|
|
1696
|
+
const raw = value.trim().replace(/,/g, '');
|
|
1697
|
+
if (!/^\d+(\.\d{0,2})?$/.test(raw)) return { ok: false, code: 'INVALID_AMOUNT' };
|
|
1698
|
+
num = Number(raw);
|
|
1699
|
+
} else {
|
|
1700
|
+
return { ok: false, code: 'INVALID_AMOUNT' };
|
|
1701
|
+
}
|
|
1702
|
+
if (!Number.isFinite(num)) return { ok: false, code: 'INVALID_AMOUNT' };
|
|
1703
|
+
if (num < 0 || num > MAX_CORRECTION_YUAN) return { ok: false, code: 'INVALID_AMOUNT' };
|
|
1704
|
+
const cents = Math.round(num * 100);
|
|
1705
|
+
if (Math.abs(cents / 100 - num) > 1e-9) {
|
|
1706
|
+
return { ok: false, code: 'INVALID_AMOUNT' };
|
|
1707
|
+
}
|
|
1708
|
+
return { ok: true, cents };
|
|
1709
|
+
}
|
|
1710
|
+
|
|
1711
|
+
/** 删除早于「北京今天 − keepDays 天」的日累计键(返回新对象)。 */
|
|
1712
|
+
function pruneDailySpend(daily, nowMs, keepDays) {
|
|
1713
|
+
const days = Number.isFinite(keepDays) ? keepDays : DAILY_KEEP_DAYS;
|
|
1714
|
+
const cutoff = beijingDateKey((Number.isFinite(nowMs) ? nowMs : Date.now()) - days * 24 * 3600 * 1000);
|
|
1715
|
+
const out = {};
|
|
1716
|
+
for (const [key, value] of Object.entries(daily || {})) {
|
|
1717
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(key)) continue;
|
|
1718
|
+
if (key < cutoff) continue;
|
|
1719
|
+
if (!Number.isFinite(value)) continue;
|
|
1720
|
+
out[key] = value;
|
|
1721
|
+
}
|
|
1722
|
+
return out;
|
|
1723
|
+
}
|
|
1724
|
+
|
|
1725
|
+
// ---------------------------------------------------------------------------
|
|
1726
|
+
// 费用统计:展示格式与动画辅助(客户端与离线测试共用)
|
|
1727
|
+
// ---------------------------------------------------------------------------
|
|
1728
|
+
|
|
1729
|
+
/** 分 -> `16.84`(千分位、两位小数、允许负号);非有限值返回 `—`。 */
|
|
1730
|
+
function formatCents(cents) {
|
|
1731
|
+
if (!Number.isFinite(cents)) return '—';
|
|
1732
|
+
const rounded = Math.round(cents);
|
|
1733
|
+
const negative = rounded < 0;
|
|
1734
|
+
const abs = Math.abs(rounded);
|
|
1735
|
+
const yuan = String(Math.floor(abs / 100)).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
|
1736
|
+
const fen = String(abs % 100).padStart(2, '0');
|
|
1737
|
+
return (negative ? '-' : '') + yuan + '.' + fen;
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1740
|
+
/** 分 -> `¥16.84`。 */
|
|
1741
|
+
function formatYuanCents(cents) {
|
|
1742
|
+
const text = formatCents(cents);
|
|
1743
|
+
return text === '—' ? text : '¥' + text;
|
|
1744
|
+
}
|
|
1745
|
+
|
|
1746
|
+
/**
|
|
1747
|
+
* 微元 -> 单次金额展示:
|
|
1748
|
+
* 0 → `¥0.00`;0 < x < ¥0.01 → `<¥0.01`;其余按分四舍五入。
|
|
1749
|
+
*/
|
|
1750
|
+
function formatCostMicros(micros) {
|
|
1751
|
+
if (!Number.isFinite(micros)) return '—';
|
|
1752
|
+
if (micros <= 0) return '¥0.00';
|
|
1753
|
+
if (micros < 10000) return '<¥0.01';
|
|
1754
|
+
return formatYuanCents(Math.round(micros / 10000));
|
|
1755
|
+
}
|
|
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
|
+
|
|
1768
|
+
/** 自动关闭时刻:秒数 0 / 非法返回 null(不自动关闭);上限 600 秒。 */
|
|
1769
|
+
function autoCloseAt(firstSeenAt, seconds) {
|
|
1770
|
+
const s = typeof seconds === 'string' ? Number(seconds) : seconds;
|
|
1771
|
+
if (!Number.isFinite(firstSeenAt) || !Number.isFinite(s) || s <= 0) return null;
|
|
1772
|
+
return firstSeenAt + Math.min(600, s) * 1000;
|
|
1773
|
+
}
|
|
1774
|
+
|
|
1775
|
+
/** 数字滚动动画缓动:easeOutCubic,端点 0 → 0、1 → 1。 */
|
|
1776
|
+
function easeOutCubic(t) {
|
|
1777
|
+
const x = t <= 0 ? 0 : t >= 1 ? 1 : t;
|
|
1778
|
+
return 1 - Math.pow(1 - x, 3);
|
|
1779
|
+
}
|
|
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
|
+
|
|
2104
|
+
// ---------------------------------------------------------------------------
|
|
2105
|
+
// 工具函数
|
|
2106
|
+
// ---------------------------------------------------------------------------
|
|
2107
|
+
|
|
2108
|
+
/**
|
|
2109
|
+
* 可取消的延迟执行器(DOM 观察器节流 / rAF 合并)。
|
|
2110
|
+
* 定时/取消函数可注入,便于离线测试「卸载后不再执行」。
|
|
2111
|
+
*
|
|
2112
|
+
* @param run 到点执行的回调
|
|
2113
|
+
* @param options { delay?: number, schedule?: (fn) => handle, cancel?: (handle) => void }
|
|
2114
|
+
* @returns {{ request: () => boolean, dispose: () => void, disposed: boolean }}
|
|
2115
|
+
*/
|
|
2116
|
+
function createScheduler(run, options) {
|
|
2117
|
+
const o = options || {};
|
|
2118
|
+
const schedule = typeof o.schedule === 'function'
|
|
2119
|
+
? o.schedule
|
|
2120
|
+
: (fn) => setTimeout(fn, Number.isFinite(o.delay) ? o.delay : 0);
|
|
2121
|
+
const cancel = typeof o.cancel === 'function'
|
|
2122
|
+
? o.cancel
|
|
2123
|
+
: (handle) => clearTimeout(handle);
|
|
2124
|
+
let handle = null;
|
|
2125
|
+
let disposed = false;
|
|
2126
|
+
|
|
2127
|
+
return {
|
|
2128
|
+
request() {
|
|
2129
|
+
if (disposed || handle !== null) return false;
|
|
2130
|
+
handle = schedule(() => {
|
|
2131
|
+
handle = null;
|
|
2132
|
+
if (!disposed) run();
|
|
2133
|
+
});
|
|
2134
|
+
return true;
|
|
2135
|
+
},
|
|
2136
|
+
dispose() {
|
|
2137
|
+
disposed = true;
|
|
2138
|
+
if (handle !== null) {
|
|
2139
|
+
try { cancel(handle); } catch { /* 已触发 */ }
|
|
2140
|
+
handle = null;
|
|
2141
|
+
}
|
|
2142
|
+
},
|
|
2143
|
+
get disposed() {
|
|
2144
|
+
return disposed;
|
|
2145
|
+
}
|
|
2146
|
+
};
|
|
2147
|
+
}
|
|
2148
|
+
|
|
2149
|
+
/**
|
|
2150
|
+
* 请求代际栅栏:用于丢弃「后发先至」的旧快照。
|
|
2151
|
+
* 每次 begin() 递增代号,只有最新代号的结果才允许写回。
|
|
2152
|
+
* @returns {{ begin: () => number, isLatest: (token: number) => boolean }}
|
|
2153
|
+
*/
|
|
2154
|
+
function createRequestGate() {
|
|
2155
|
+
let seq = 0;
|
|
2156
|
+
return {
|
|
2157
|
+
begin() {
|
|
2158
|
+
seq += 1;
|
|
2159
|
+
return seq;
|
|
2160
|
+
},
|
|
2161
|
+
isLatest(token) {
|
|
2162
|
+
return token === seq;
|
|
2163
|
+
}
|
|
2164
|
+
};
|
|
2165
|
+
}
|
|
2166
|
+
|
|
2167
|
+
/** HTML 转义(用于浮层内注入标题/正文)。 */
|
|
2168
|
+
function escapeHtml(value) {
|
|
2169
|
+
return String(value == null ? '' : value)
|
|
2170
|
+
.replaceAll('&', '&')
|
|
2171
|
+
.replaceAll('<', '<')
|
|
2172
|
+
.replaceAll('>', '>')
|
|
2173
|
+
.replaceAll('"', '"')
|
|
2174
|
+
.replaceAll("'", ''');
|
|
2175
|
+
}
|
|
2176
|
+
|
|
2177
|
+
// ---------------------------------------------------------------------------
|
|
2178
|
+
// 图标(内置兜底:24 网格 / 1.5px 线宽 / round cap 的通用线性图标)
|
|
2179
|
+
//
|
|
2180
|
+
// 线宽 1.5 与官方图标(16 网格 / 1px 线宽)在 15px 尺寸下的视觉粗细一致,
|
|
2181
|
+
// 因此官方组件缺失时混用也不会出现粗细差异。
|
|
2182
|
+
// 运行时优先使用 DSH 官方图标组件(见 client.js 的 OFFICIAL_ICON_NAMES)。
|
|
2183
|
+
// ---------------------------------------------------------------------------
|
|
2184
|
+
|
|
2185
|
+
const ICONS = {
|
|
2186
|
+
recall: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 14 4 9l5-5"/><path d="M4 9h10.5a5.5 5.5 0 0 1 0 11H11"/></svg>',
|
|
2187
|
+
share: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 12v7a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-7"/><path d="M12 16V3"/><path d="m8 7 4-4 4 4"/></svg>',
|
|
2188
|
+
export: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 14v5a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-5"/><path d="M12 3v11"/><path d="m8 10 4 4 4-4"/></svg>',
|
|
2189
|
+
delete: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 6h18"/><path d="M8 6V4h8v2"/><path d="M19 6l-1 14H6L5 6"/><path d="M10 11v5M14 11v5"/></svg>',
|
|
2190
|
+
deleteFrom: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 6h18"/><path d="M8 6V4h8v2"/><path d="M19 6l-1 14H6L5 6"/><path d="M12 10v6"/><path d="m9 13 3 3 3-3"/></svg>',
|
|
2191
|
+
check: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 12 5 5L19 7"/></svg>'
|
|
2192
|
+
};
|
|
2193
|
+
|
|
2194
|
+
// ---------------------------------------------------------------------------
|
|
2195
|
+
// 客户端注入样式表
|
|
2196
|
+
// ---------------------------------------------------------------------------
|
|
2197
|
+
|
|
2198
|
+
/**
|
|
2199
|
+
* 客户端注入的行内样式。仅依赖 CSS 变量(DSH 主题提供),不硬编码品牌色。
|
|
2200
|
+
*/
|
|
2201
|
+
const CSS = `
|
|
2202
|
+
.dma-row-actions{display:inline-flex;align-items:center;gap:2px;vertical-align:middle}
|
|
2203
|
+
.dma-tool-actions{display:inline-flex;align-items:center;gap:2px;margin-inline-start:6px;vertical-align:middle}
|
|
2204
|
+
.dma-btn{display:inline-flex;align-items:center;justify-content:center;width:calc(28px + var(--dsh-content-font-delta,0px));height:calc(28px + var(--dsh-content-font-delta,0px));padding:0;border:0;border-radius:var(--dsw-radius-sm,6px);background:transparent;color:var(--dsw-alias-label-tertiary,#8a919e);cursor:pointer;line-height:1;transition:background 80ms ease,color 80ms ease}
|
|
2205
|
+
.dma-btn svg{display:block;width:calc(15px + var(--dsh-content-font-delta,0px));height:calc(15px + var(--dsh-content-font-delta,0px))}
|
|
2206
|
+
.dma-btn:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(0,0,0,.06));color:var(--dsw-alias-label-secondary,#5b6472)}
|
|
2207
|
+
.dma-btn:disabled{opacity:.35;cursor:not-allowed}
|
|
2208
|
+
.dma-btn.dma-danger:hover{background:var(--dsw-alias-interactive-bg-hover-danger,rgba(229,72,77,.12));color:var(--dsw-alias-state-error-primary,#e5484d)}
|
|
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}
|
|
2210
|
+
[data-dma-hidden="1"]{display:none!important}
|
|
2211
|
+
[data-dma-rail="1"]{display:none!important}
|
|
2212
|
+
.dma-overlay{position:fixed;inset:0;z-index:2147483000;background:var(--dsw-alias-bg-mask-1,rgba(0,0,0,.45));display:flex;align-items:center;justify-content:center}
|
|
2213
|
+
.dma-panel{width:min(680px,calc(100vw - 48px));max-height:80vh;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{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{overflow:auto;padding:12px 16px}
|
|
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}
|
|
2219
|
+
.dma-round:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(0,0,0,.04))}
|
|
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}
|
|
2221
|
+
.dma-round-box[aria-checked="true"]{border-color:var(--dsw-alias-state-business-primary,#4c8dff);background:var(--dsw-alias-state-business-primary,#4c8dff);color:#fff}
|
|
2222
|
+
.dma-round-box svg{width:13px;height:13px}
|
|
2223
|
+
.dma-round-main{flex:1 1 auto;min-width:0;display:flex;flex-direction:column;gap:4px}
|
|
2224
|
+
.dma-round-line{display:flex;align-items:center;gap:8px;min-width:0;font-size:13px}
|
|
2225
|
+
.dma-round-tag{flex:0 0 auto;font-size:11px;line-height:18px;padding:0 6px;border-radius:9px;background:var(--dsw-alias-bg-layer-2,#f2f3f5);color:var(--dsw-alias-label-secondary,#5b6472)}
|
|
2226
|
+
.dma-round-q{font-weight:600}
|
|
2227
|
+
.dma-round-q .dma-round-tag{background:var(--dsw-alias-button-primary-dimmed,rgba(76,141,255,.14));color:var(--dsw-alias-state-business-primary,#4c8dff)}
|
|
2228
|
+
.dma-round-tag-a{color:var(--dsw-alias-label-tertiary,#8a919e)}
|
|
2229
|
+
.dma-round-a{color:var(--dsw-alias-label-secondary,#5b6472)}
|
|
2230
|
+
.dma-round-text{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
2231
|
+
.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))}
|
|
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)}
|
|
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}
|
|
2234
|
+
.dma-panel-foot .dma-primary.dma-danger{background:var(--dsw-alias-state-error-primary,#e5484d);color:#fff}
|
|
2235
|
+
.dma-panel-foot .dma-primary:disabled{background:var(--dsw-alias-bg-layer-2,#f2f3f5);color:var(--dsw-alias-label-dimmed,#a0a6b0)}
|
|
2236
|
+
.dma-panel-foot .dma-btn:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4c8dff);outline-offset:2px}
|
|
2237
|
+
.dma-toast{position:fixed;left:50%;bottom:32px;transform:translateX(-50%);z-index:2147483100;padding:8px 16px;border-radius:999px;background:var(--dsw-alias-toast-bg,rgba(32,35,42,.96));box-shadow:0 6px 20px rgba(0,0,0,.22);font-size:12px;line-height:1.6;color:var(--dsw-alias-toast-label,#fff);pointer-events:none}
|
|
2238
|
+
`;
|
|
2239
|
+
|
|
2240
|
+
// ---------------------------------------------------------------------------
|
|
2241
|
+
// 导出
|
|
2242
|
+
// ---------------------------------------------------------------------------
|
|
2243
|
+
|
|
2244
|
+
module.exports = {
|
|
2245
|
+
PRODUCER,
|
|
2246
|
+
TOMBSTONE_TEXT,
|
|
2247
|
+
ERROR_LABELS,
|
|
2248
|
+
contentText,
|
|
2249
|
+
refillTextOf,
|
|
2250
|
+
attachmentsOfEvent,
|
|
2251
|
+
textOf,
|
|
2252
|
+
messageRoleOf,
|
|
2253
|
+
messageIdOf,
|
|
2254
|
+
usageSummaryOf,
|
|
2255
|
+
toolCallIdOf,
|
|
2256
|
+
toolCallIdFromNodeKey,
|
|
2257
|
+
toolNodeKeysToHide,
|
|
2258
|
+
findToolRowByCallId,
|
|
2259
|
+
tombstonedSeqsOf,
|
|
2260
|
+
liveNodesOf,
|
|
2261
|
+
goneToolsOf,
|
|
2262
|
+
resolveKeyAction,
|
|
2263
|
+
isEditableTarget,
|
|
2264
|
+
TOOL_NODE_KEY_PREFIX,
|
|
2265
|
+
wordCount,
|
|
2266
|
+
previewText,
|
|
2267
|
+
formatTokens,
|
|
2268
|
+
isTombstone,
|
|
2269
|
+
buildTurnIndex,
|
|
2270
|
+
buildTurnSeqMap,
|
|
2271
|
+
createTurnLookup,
|
|
2272
|
+
turnOf,
|
|
2273
|
+
turnOfLookup,
|
|
2274
|
+
stepNodesOf,
|
|
2275
|
+
planAction,
|
|
2276
|
+
turnSpan,
|
|
2277
|
+
buildPlan,
|
|
2278
|
+
roundsOf,
|
|
2279
|
+
goneTurnsOf,
|
|
2280
|
+
messagesSummaryOf,
|
|
2281
|
+
mergeMessageSummary,
|
|
2282
|
+
markdownOf,
|
|
2283
|
+
exportFilename,
|
|
2284
|
+
railTurnOf,
|
|
2285
|
+
railTurnOfAttributes,
|
|
2286
|
+
collapseRail,
|
|
2287
|
+
createScheduler,
|
|
2288
|
+
createRequestGate,
|
|
2289
|
+
escapeHtml,
|
|
2290
|
+
MAX_BODY_BYTES,
|
|
2291
|
+
isLoopbackHost,
|
|
2292
|
+
isTrustedRequest,
|
|
2293
|
+
statusCodeOf,
|
|
2294
|
+
isBusyError,
|
|
2295
|
+
bodyTooLarge,
|
|
2296
|
+
BJ_OFFSET_MS,
|
|
2297
|
+
WEEKEND_VALLEY_SINCE,
|
|
2298
|
+
VALLEY_FACTOR,
|
|
2299
|
+
PRICE_CHECKED_AT,
|
|
2300
|
+
PRICE_TABLE,
|
|
2301
|
+
MAX_TURN_EVENTS,
|
|
2302
|
+
MAX_CORRECTION_YUAN,
|
|
2303
|
+
DAILY_KEEP_DAYS,
|
|
2304
|
+
MAX_OBSERVE_GAP_MS,
|
|
2305
|
+
beijingParts,
|
|
2306
|
+
beijingDateKey,
|
|
2307
|
+
beijingMsOf,
|
|
2308
|
+
isValleyDay,
|
|
2309
|
+
inPeakWindow,
|
|
2310
|
+
periodInfo,
|
|
2311
|
+
periodChangeText,
|
|
2312
|
+
priceFor,
|
|
2313
|
+
turnCost,
|
|
2314
|
+
turnCostOfGroups,
|
|
2315
|
+
streamUsageOf,
|
|
2316
|
+
routeOfMessage,
|
|
2317
|
+
routeOfUsage,
|
|
2318
|
+
routingOfProvider,
|
|
2319
|
+
isDeepseekModel,
|
|
2320
|
+
isBillableRoute,
|
|
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,
|
|
2332
|
+
COST_LAYOUTS,
|
|
2333
|
+
DEFAULT_COST_LAYOUT,
|
|
2334
|
+
normalizeCostLayout,
|
|
2335
|
+
normalizeCostUsage,
|
|
2336
|
+
stepUsageOf,
|
|
2337
|
+
deriveTurnUsage,
|
|
2338
|
+
createTurnBuffer,
|
|
2339
|
+
appendTurnEvent,
|
|
2340
|
+
observeBalance,
|
|
2341
|
+
settleSpend,
|
|
2342
|
+
yuanToCents,
|
|
2343
|
+
validateCorrectionAmount,
|
|
2344
|
+
pruneDailySpend,
|
|
2345
|
+
formatCents,
|
|
2346
|
+
formatYuanCents,
|
|
2347
|
+
formatCostMicros,
|
|
2348
|
+
formatReplyCost,
|
|
2349
|
+
autoCloseAt,
|
|
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,
|
|
2366
|
+
ICONS,
|
|
2367
|
+
CSS
|
|
2368
|
+
};
|