@morgan9668/dsh-task-notify 0.0.0-stage → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +126 -2
- package/__tests__/client.mjs +274 -0
- package/__tests__/e2e.mjs +192 -0
- package/__tests__/settings.mjs +455 -0
- package/__tests__/unit.mjs +432 -0
- package/client.js +402 -0
- package/cordis.patch.yml +63 -0
- package/docs/DETAIL.md +76 -0
- package/index.js +450 -0
- package/locale/en.json +10 -0
- package/locale/zh.json +10 -0
- package/package.json +56 -4
- package/src/channels.js +239 -0
- package/src/render.js +207 -0
package/src/channels.js
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 渠道适配层:把一条结构化通知渲染成各平台自己的消息形状并发送。
|
|
3
|
+
*
|
|
4
|
+
* 四个渠道的差异集中在这里,上层(index.js)只负责收集数据与调度:
|
|
5
|
+
*
|
|
6
|
+
* 企业微信 群机器人 webhook,POST {"msgtype":"markdown","markdown":{"content":...}}
|
|
7
|
+
* 飞书 群机器人 webhook,POST {"msg_type":"interactive",...},可选签名
|
|
8
|
+
* 钉钉 群机器人 webhook,POST {"msgtype":"markdown",...},加签必填
|
|
9
|
+
* 微信 预留(Server酱 / WxPusher 两种凭据形态)
|
|
10
|
+
*
|
|
11
|
+
* 所有发送都是 fire-and-forget:失败只写日志,永不向上抛,绝不阻塞 agent 主循环。
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { createHmac, createHash } from 'node:crypto';
|
|
15
|
+
|
|
16
|
+
/** 各渠道对单条正文的安全上限;超长先截断再发,避免整条被拒。 */
|
|
17
|
+
export const BODY_LIMITS = {
|
|
18
|
+
wecom: 3800,
|
|
19
|
+
feishu: 3800,
|
|
20
|
+
dingtalk: 4800,
|
|
21
|
+
wechat: 3000,
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 钉钉加签:HmacSHA256(timestamp + "\n" + secret, secret) 再 base64。
|
|
26
|
+
* 签名必须放在 query 上,且 timestamp 与签名的组合有效期只有 1 小时。
|
|
27
|
+
*/
|
|
28
|
+
export function dingtalkSignature(timestamp, secret) {
|
|
29
|
+
const stringToSign = `${timestamp}\n${secret}`;
|
|
30
|
+
return createHmac('sha256', secret).update(stringToSign, 'utf8').digest('base64');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** 飞书加签:HmacSHA256(key = timestamp + "\n" + secret, data = ""),结果 base64。 */
|
|
34
|
+
export function feishuSignature(timestamp, secret) {
|
|
35
|
+
const key = `${timestamp}\n${secret}`;
|
|
36
|
+
return createHmac('sha256', key).update('', 'utf8').digest('base64');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 拼接带签名的钉钉地址;未配 secret 时原样返回(钉钉会拒绝,如实报错)。 */
|
|
40
|
+
export function signedDingtalkUrl(webhook, secret, now = Date.now()) {
|
|
41
|
+
if (!secret) return webhook;
|
|
42
|
+
const timestamp = String(now);
|
|
43
|
+
const sign = dingtalkSignature(timestamp, secret);
|
|
44
|
+
const url = new URL(webhook);
|
|
45
|
+
url.searchParams.set('timestamp', timestamp);
|
|
46
|
+
url.searchParams.set('sign', sign);
|
|
47
|
+
return url.toString();
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 把任意 Markdown 裁到渠道上限,附加一行截断说明。 */
|
|
51
|
+
export function clampBody(text, limit) {
|
|
52
|
+
if (typeof text !== 'string') return '';
|
|
53
|
+
if (text.length <= limit) return text;
|
|
54
|
+
const note = '\n\n> 内容过长,已截断';
|
|
55
|
+
return `${text.slice(0, Math.max(0, limit - note.length)).trimEnd()}${note}`;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** 飞书的富文本卡片体:比纯 Markdown 更能保证中文换行与层级。 */
|
|
59
|
+
function feishuCard(title, body) {
|
|
60
|
+
return {
|
|
61
|
+
msg_type: 'interactive',
|
|
62
|
+
card: {
|
|
63
|
+
config: { wide_screen_mode: true },
|
|
64
|
+
header: {
|
|
65
|
+
title: { tag: 'plain_text', content: title },
|
|
66
|
+
template: 'green',
|
|
67
|
+
},
|
|
68
|
+
elements: [
|
|
69
|
+
{
|
|
70
|
+
tag: 'div',
|
|
71
|
+
text: { tag: 'lark_md', content: body },
|
|
72
|
+
},
|
|
73
|
+
],
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* 渲染并发送一条通知。
|
|
80
|
+
*
|
|
81
|
+
* @param {object} channel - 该渠道的配置片段(含 enabled / webhook / secret …)
|
|
82
|
+
* @param {'wecom'|'feishu'|'dingtalk'|'wechat'} kind - 渠道种类
|
|
83
|
+
* @param {{title: string, body: string}} message - 已渲染好的标题与正文
|
|
84
|
+
* @param {{timeoutMs: number, log: (msg: string) => void, fetchImpl?: Function}} runtime
|
|
85
|
+
* @returns {Promise<{ok: boolean, channel: string, detail?: string}>}
|
|
86
|
+
*/
|
|
87
|
+
export async function sendToChannel(channel, kind, message, runtime) {
|
|
88
|
+
const { timeoutMs, log } = runtime;
|
|
89
|
+
const doFetch = runtime.fetchImpl ?? globalThis.fetch;
|
|
90
|
+
const limit = BODY_LIMITS[kind] ?? 3800;
|
|
91
|
+
const body = clampBody(message.body, limit);
|
|
92
|
+
const title = message.title;
|
|
93
|
+
|
|
94
|
+
try {
|
|
95
|
+
if (kind === 'wechat') {
|
|
96
|
+
// 预留通道:两种凭据都支持,但当前不内置自建服务号。
|
|
97
|
+
const sendKey = channel?.serverchanSendKey ?? '';
|
|
98
|
+
const appToken = channel?.wxpusherAppToken ?? '';
|
|
99
|
+
if (sendKey) {
|
|
100
|
+
const url = sendKey.startsWith('sctp')
|
|
101
|
+
? `https://${sendKey.slice(4).match(/^\d+/)?.[0] ?? ''}.push.ft07.com/send/${sendKey}.send`
|
|
102
|
+
: `https://sctapi.ftqq.com/${sendKey}.send`;
|
|
103
|
+
const response = await doFetch(url, {
|
|
104
|
+
method: 'POST',
|
|
105
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
106
|
+
body: new URLSearchParams({ title, desp: body }),
|
|
107
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
108
|
+
});
|
|
109
|
+
return await judge(response, kind, log);
|
|
110
|
+
}
|
|
111
|
+
if (appToken) {
|
|
112
|
+
const response = await doFetch('https://wxpusher.zjiecode.com/api/send/message', {
|
|
113
|
+
method: 'POST',
|
|
114
|
+
headers: { 'content-type': 'application/json' },
|
|
115
|
+
body: JSON.stringify({
|
|
116
|
+
appToken,
|
|
117
|
+
content: body,
|
|
118
|
+
summary: title.slice(0, 20),
|
|
119
|
+
contentType: 3,
|
|
120
|
+
}),
|
|
121
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
122
|
+
});
|
|
123
|
+
return await judge(response, kind, log);
|
|
124
|
+
}
|
|
125
|
+
return { ok: false, channel: kind, detail: '微信通道未配置凭据' };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (kind === 'wecom') {
|
|
129
|
+
if (!channel?.webhook) return { ok: false, channel: kind, detail: '未配置 Webhook' };
|
|
130
|
+
const response = await doFetch(channel.webhook, {
|
|
131
|
+
method: 'POST',
|
|
132
|
+
headers: { 'content-type': 'application/json' },
|
|
133
|
+
body: JSON.stringify({
|
|
134
|
+
msgtype: 'markdown',
|
|
135
|
+
markdown: { content: `${title}\n${body}` },
|
|
136
|
+
}),
|
|
137
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
138
|
+
});
|
|
139
|
+
return await judge(response, kind, log);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
if (kind === 'feishu') {
|
|
143
|
+
if (!channel?.webhook) return { ok: false, channel: kind, detail: '未配置 Webhook' };
|
|
144
|
+
const payload = feishuCard(title, body);
|
|
145
|
+
if (channel.secret) {
|
|
146
|
+
const timestamp = String(Math.floor(Date.now() / 1000));
|
|
147
|
+
payload.timestamp = timestamp;
|
|
148
|
+
payload.sign = feishuSignature(timestamp, channel.secret);
|
|
149
|
+
}
|
|
150
|
+
const response = await doFetch(channel.webhook, {
|
|
151
|
+
method: 'POST',
|
|
152
|
+
headers: { 'content-type': 'application/json' },
|
|
153
|
+
body: JSON.stringify(payload),
|
|
154
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
155
|
+
});
|
|
156
|
+
return await judge(response, kind, log);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
if (kind === 'dingtalk') {
|
|
160
|
+
if (!channel?.webhook) return { ok: false, channel: kind, detail: '未配置 Webhook' };
|
|
161
|
+
const url = signedDingtalkUrl(channel.webhook, channel.secret);
|
|
162
|
+
const response = await doFetch(url, {
|
|
163
|
+
method: 'POST',
|
|
164
|
+
headers: { 'content-type': 'application/json' },
|
|
165
|
+
body: JSON.stringify({
|
|
166
|
+
msgtype: 'markdown',
|
|
167
|
+
markdown: { title, text: `${title}\n${body}` },
|
|
168
|
+
}),
|
|
169
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
170
|
+
});
|
|
171
|
+
return await judge(response, kind, log);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
return { ok: false, channel: kind, detail: `未知渠道 ${kind}` };
|
|
175
|
+
} catch (error) {
|
|
176
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
177
|
+
log(`task-notify: ${kind} 发送失败 — ${detail}`);
|
|
178
|
+
return { ok: false, channel: kind, detail };
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* 判定一次响应是否真的成功。
|
|
184
|
+
*
|
|
185
|
+
* 这三个平台都会用 HTTP 200 + 业务错误码回话,只看 status 会把「webhook
|
|
186
|
+
* 已失效」当成成功,所以必须读错误码:
|
|
187
|
+
* 企业微信 errcode === 0
|
|
188
|
+
* 钉钉 errcode === 0
|
|
189
|
+
* 飞书 code === 0(旧版 StatusCode === 0)
|
|
190
|
+
*/
|
|
191
|
+
async function judge(response, kind, log) {
|
|
192
|
+
let text = '';
|
|
193
|
+
try {
|
|
194
|
+
text = await response.text();
|
|
195
|
+
} catch {
|
|
196
|
+
text = '';
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
if (!response.ok) {
|
|
200
|
+
const detail = `HTTP ${response.status} ${text.slice(0, 200)}`;
|
|
201
|
+
log(`task-notify: ${kind} 发送失败 — ${detail}`);
|
|
202
|
+
return { ok: false, channel: kind, detail };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
let payload;
|
|
206
|
+
try {
|
|
207
|
+
payload = text === '' ? {} : JSON.parse(text);
|
|
208
|
+
} catch {
|
|
209
|
+
// 200 但正文不是 JSON:如实记为「已送出不可确认」,不冒充成功。
|
|
210
|
+
return { ok: true, channel: kind, detail: '已送出,响应非 JSON,结果不可确认' };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const code = payload?.errcode ?? payload?.code ?? payload?.StatusCode;
|
|
214
|
+
if (code === undefined) return { ok: true, channel: kind, detail: '已送出' };
|
|
215
|
+
if (Number(code) === 0) return { ok: true, channel: kind };
|
|
216
|
+
|
|
217
|
+
const message = payload?.errmsg ?? payload?.msg ?? payload?.StatusMessage ?? '';
|
|
218
|
+
const detail = `业务错误码 ${code}${message ? `:${message}` : ''}`;
|
|
219
|
+
log(`task-notify: ${kind} 发送失败 — ${detail}`);
|
|
220
|
+
return { ok: false, channel: kind, detail };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** 渠道是否具备发送条件(用于「有没有可用渠道」的判断,不发请求)。 */
|
|
224
|
+
export function isChannelReady(channel, kind) {
|
|
225
|
+
if (!channel || channel.enabled !== true) return false;
|
|
226
|
+
if (kind === 'wechat') {
|
|
227
|
+
return Boolean(channel.serverchanSendKey) || Boolean(channel.wxpusherAppToken);
|
|
228
|
+
}
|
|
229
|
+
if (!channel.webhook) return false;
|
|
230
|
+
return true;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** 稳定标识,用于日志去重与「同一事件只发一次」。 */
|
|
234
|
+
export function eventFingerprint(sessionId, turn, reason) {
|
|
235
|
+
return createHash('sha256')
|
|
236
|
+
.update(`${sessionId}\u0000${turn ?? ''}\u0000${reason ?? ''}`)
|
|
237
|
+
.digest('hex')
|
|
238
|
+
.slice(0, 16);
|
|
239
|
+
}
|
package/src/render.js
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 通知内容渲染:把事件流里的原始数据整理成一条给人看的中文通知。
|
|
3
|
+
*
|
|
4
|
+
* 数据来源(均为 DSH 已提交的会话事件,不猜、不补):
|
|
5
|
+
* assistant/message 带 data.usage(本轮 token)与 data.message(回复正文)
|
|
6
|
+
* tool/call 带 data.name(用于统计「调用了几次工具」)
|
|
7
|
+
* turn/start 带 data.turn,用来配对并计算耗时
|
|
8
|
+
* turn/end 带 data.reason.kind(回合结局)
|
|
9
|
+
* session/title 对话标题
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** 回合结局的中文说法;未收录的原样返回英文,不硬翻。 */
|
|
13
|
+
const REASON_LABELS = {
|
|
14
|
+
completed: '已完成',
|
|
15
|
+
error: '出错',
|
|
16
|
+
blocked: '被阻塞',
|
|
17
|
+
'max-tokens': '超出输出上限',
|
|
18
|
+
aborted: '已中止',
|
|
19
|
+
interrupted: '已中断',
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export function reasonLabel(kind) {
|
|
23
|
+
return REASON_LABELS[kind] ?? String(kind ?? '未知');
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** 里程碑文案:不同结局给出不同的首要提示,避免「出错」也显示 ✅。 */
|
|
27
|
+
export function statusBadge(kind) {
|
|
28
|
+
if (kind === 'completed') return '✅ 任务完成';
|
|
29
|
+
if (kind === 'error') return '❌ 任务出错';
|
|
30
|
+
if (kind === 'blocked') return '⏸️ 任务待处理';
|
|
31
|
+
if (kind === 'max-tokens') return '⚠️ 输出被截断';
|
|
32
|
+
if (kind === 'aborted' || kind === 'interrupted') return '⏹️ 任务已中止';
|
|
33
|
+
return 'ℹ️ 回合结束';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 毫秒 → 「3分12秒」/「1小时02分」/「840毫秒」。 */
|
|
37
|
+
export function formatDuration(ms) {
|
|
38
|
+
if (!Number.isFinite(ms) || ms < 0) return '未知';
|
|
39
|
+
if (ms < 1000) return `${Math.round(ms)}毫秒`;
|
|
40
|
+
const totalSeconds = Math.round(ms / 1000);
|
|
41
|
+
const hours = Math.floor(totalSeconds / 3600);
|
|
42
|
+
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
|
43
|
+
const seconds = totalSeconds % 60;
|
|
44
|
+
if (hours > 0) return `${hours}小时${String(minutes).padStart(2, '0')}分`;
|
|
45
|
+
if (minutes > 0) return `${minutes}分${String(seconds).padStart(2, '0')}秒`;
|
|
46
|
+
return `${seconds}秒`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 数字加千分位,中文习惯用半角逗号。 */
|
|
50
|
+
export function formatNumber(value) {
|
|
51
|
+
if (!Number.isFinite(value)) return '—';
|
|
52
|
+
return Math.round(value).toLocaleString('en-US');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* 从事件流里汇总本轮的 token 用量。
|
|
57
|
+
*
|
|
58
|
+
* DSH 的 usage 挂在 assistant/message 上,一次回合可能有多条(多步推理),
|
|
59
|
+
* 所以要累加而不是取最后一条;字段缺失时按 0 计,并在返回值里标出缺项,
|
|
60
|
+
* 让渲染层能显示「未提供」而不是伪造一个 0。
|
|
61
|
+
*/
|
|
62
|
+
export function sumUsage(events, turn) {
|
|
63
|
+
const totals = {
|
|
64
|
+
inputTokens: 0,
|
|
65
|
+
outputTokens: 0,
|
|
66
|
+
totalTokens: 0,
|
|
67
|
+
cachedReadTokens: 0,
|
|
68
|
+
seen: false,
|
|
69
|
+
missing: [],
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
for (const event of events) {
|
|
73
|
+
if (event?.type !== 'assistant/message') continue;
|
|
74
|
+
if (turn !== undefined && event?.data?.turn !== undefined && event.data.turn !== turn) continue;
|
|
75
|
+
const usage = event?.data?.usage;
|
|
76
|
+
if (!usage || typeof usage !== 'object') continue;
|
|
77
|
+
totals.seen = true;
|
|
78
|
+
|
|
79
|
+
const input = Number(usage.inputTokens);
|
|
80
|
+
const output = Number(usage.outputTokens);
|
|
81
|
+
const total = Number(usage.totalTokens);
|
|
82
|
+
const cached = Number(usage.cachedReadTokens);
|
|
83
|
+
|
|
84
|
+
if (Number.isFinite(input)) totals.inputTokens += input;
|
|
85
|
+
else if (!totals.missing.includes('输入')) totals.missing.push('输入');
|
|
86
|
+
if (Number.isFinite(output)) totals.outputTokens += output;
|
|
87
|
+
else if (!totals.missing.includes('输出')) totals.missing.push('输出');
|
|
88
|
+
if (Number.isFinite(total)) totals.totalTokens += total;
|
|
89
|
+
if (Number.isFinite(cached)) totals.cachedReadTokens += cached;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (!totals.seen) return { ...totals, available: false };
|
|
93
|
+
if (totals.totalTokens === 0) {
|
|
94
|
+
totals.totalTokens = totals.inputTokens + totals.outputTokens;
|
|
95
|
+
}
|
|
96
|
+
return { ...totals, available: true };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* 从事件流里取出最后一条 assistant 回复的纯文本,并裁到 maxChars。
|
|
101
|
+
* 只取 text 块;reasoning 不入通知正文。
|
|
102
|
+
*/
|
|
103
|
+
export function lastReplyText(events, maxChars = 400) {
|
|
104
|
+
for (let i = events.length - 1; i >= 0; i--) {
|
|
105
|
+
const event = events[i];
|
|
106
|
+
if (event?.type !== 'assistant/message') continue;
|
|
107
|
+
const content = event?.data?.message?.content;
|
|
108
|
+
if (!Array.isArray(content)) continue;
|
|
109
|
+
const text = content
|
|
110
|
+
.filter((block) => block?.type === 'text' && typeof block.text === 'string')
|
|
111
|
+
.map((block) => block.text)
|
|
112
|
+
.join('\n')
|
|
113
|
+
.trim();
|
|
114
|
+
if (text === '') continue;
|
|
115
|
+
if (text.length <= maxChars) return text;
|
|
116
|
+
return `${text.slice(0, maxChars).trimEnd()}…`;
|
|
117
|
+
}
|
|
118
|
+
return '';
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** 统计本轮工具调用次数与名称分布。 */
|
|
122
|
+
export function toolSummary(events, turn) {
|
|
123
|
+
const counts = new Map();
|
|
124
|
+
for (const event of events) {
|
|
125
|
+
if (event?.type !== 'tool/call') continue;
|
|
126
|
+
if (turn !== undefined && event?.data?.turn !== undefined && event.data.turn !== turn) continue;
|
|
127
|
+
const name = event?.data?.name;
|
|
128
|
+
if (typeof name !== 'string' || name === '') continue;
|
|
129
|
+
counts.set(name, (counts.get(name) ?? 0) + 1);
|
|
130
|
+
}
|
|
131
|
+
const total = [...counts.values()].reduce((a, b) => a + b, 0);
|
|
132
|
+
const top = [...counts.entries()]
|
|
133
|
+
.sort((a, b) => b[1] - a[1])
|
|
134
|
+
.slice(0, 4)
|
|
135
|
+
.map(([name, count]) => `${name}×${count}`)
|
|
136
|
+
.join('、');
|
|
137
|
+
return { total, top };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** 从事件流里找最近的会话标题。 */
|
|
141
|
+
export function sessionTitle(events, fallback = 'DeepSeek Harness 任务') {
|
|
142
|
+
for (let i = events.length - 1; i >= 0; i--) {
|
|
143
|
+
const event = events[i];
|
|
144
|
+
if (event?.type !== 'session/title') continue;
|
|
145
|
+
const title = event?.data?.title;
|
|
146
|
+
if (typeof title === 'string' && title.trim() !== '') return title.trim();
|
|
147
|
+
}
|
|
148
|
+
return fallback;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* 渲染完整通知。
|
|
153
|
+
*
|
|
154
|
+
* 你要求的内容只有三块:概要、耗时、token 消耗。这里就只渲染这三块,
|
|
155
|
+
* 外加一行的标题与结局,不夹带会话 ID / git 分支这类噪音。
|
|
156
|
+
*/
|
|
157
|
+
export function renderNotification(input) {
|
|
158
|
+
const {
|
|
159
|
+
reasonKind,
|
|
160
|
+
durationMs,
|
|
161
|
+
events = [],
|
|
162
|
+
turn,
|
|
163
|
+
maxExcerptChars = 400,
|
|
164
|
+
modelLabel = '',
|
|
165
|
+
} = input;
|
|
166
|
+
|
|
167
|
+
const usage = sumUsage(events, turn);
|
|
168
|
+
const reply = lastReplyText(events, maxExcerptChars);
|
|
169
|
+
const tools = toolSummary(events, turn);
|
|
170
|
+
const title = sessionTitle(events);
|
|
171
|
+
|
|
172
|
+
const lines = [`**${statusBadge(reasonKind)}** ${reasonLabel(reasonKind)}`, ''];
|
|
173
|
+
|
|
174
|
+
// 概要
|
|
175
|
+
lines.push('**📋 任务概要**');
|
|
176
|
+
if (reply !== '') {
|
|
177
|
+
for (const line of reply.split('\n').slice(0, 6)) {
|
|
178
|
+
const trimmed = line.trim();
|
|
179
|
+
if (trimmed !== '') lines.push(`> ${trimmed}`);
|
|
180
|
+
}
|
|
181
|
+
} else {
|
|
182
|
+
lines.push('> 本轮没有文字回复');
|
|
183
|
+
}
|
|
184
|
+
if (tools.total > 0) {
|
|
185
|
+
lines.push('', `工具调用:${tools.total} 次${tools.top ? `(${tools.top})` : ''}`);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// 耗时
|
|
189
|
+
lines.push('', '**⏱️ 耗时**', `> ${formatDuration(durationMs)}`);
|
|
190
|
+
|
|
191
|
+
// token
|
|
192
|
+
lines.push('', '**🔢 token 消耗**');
|
|
193
|
+
if (!usage.available) {
|
|
194
|
+
lines.push('> 本轮未提供用量数据');
|
|
195
|
+
} else {
|
|
196
|
+
lines.push(
|
|
197
|
+
`> 输入 ${formatNumber(usage.inputTokens)} 输出 ${formatNumber(usage.outputTokens)}`,
|
|
198
|
+
`> 合计 **${formatNumber(usage.totalTokens)}**${usage.cachedReadTokens > 0 ? `(含缓存命中 ${formatNumber(usage.cachedReadTokens)})` : ''}`,
|
|
199
|
+
);
|
|
200
|
+
if (usage.missing.length > 0) {
|
|
201
|
+
lines.push(`> 注:上游未提供 ${usage.missing.join('、')} token 数`);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const titleLine = modelLabel ? `${title} · ${modelLabel}` : title;
|
|
206
|
+
return { title: titleLine, body: lines.join('\n') };
|
|
207
|
+
}
|