@morgan9668/dsh-llm-gateway 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,315 @@
1
+ /**
2
+ * 通知调度器:把「什么时候发」和「怎么发」从 apply() 里拿出来。
3
+ *
4
+ * 这一层只做三件事:
5
+ * 1. 决定该不该发(总开关、结局白名单、触发源开关);
6
+ * 2. 网关请求的**静默窗口聚合**——一个任务连发几十个请求只发一条;
7
+ * 3. 交给渠道层发送、把闪动推给页面,失败只写日志。
8
+ *
9
+ * 硬约束:**任何路径都不许抛给调用方**。通知是旁路,它没有资格让一个
10
+ * 正在正常工作的网关请求失败。
11
+ */
12
+
13
+ import { isChannelReady, sendToChannel } from './channels.js';
14
+ import {
15
+ flashPeriodMs,
16
+ normalizeInApp,
17
+ normalizeNotify,
18
+ shouldNotify,
19
+ } from './config.js';
20
+ import {
21
+ renderGatewayNotification,
22
+ renderSessionNotification,
23
+ statusBadge,
24
+ } from './render.js';
25
+
26
+ const CHANNEL_KINDS = ['wecom', 'feishu', 'dingtalk', 'wechat'];
27
+
28
+ /** 当前真正可发送的渠道列表。 */
29
+ export function readyChannels(config) {
30
+ return CHANNEL_KINDS.filter((kind) => isChannelReady(config.channels[kind], kind));
31
+ }
32
+
33
+ /** 一条闪动事件的内容。设置页的预览与真实触发走同一个函数,效果不会分叉。 */
34
+ function flashPayload(inApp, extra = {}) {
35
+ const { flashes, durationSeconds, color } = inApp;
36
+ return {
37
+ // 每条带自己的 id:页面据此去重,EventSource 断线重连会重发最后一帧。
38
+ id: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
39
+ flashes,
40
+ durationSeconds,
41
+ color,
42
+ periodMs: flashPeriodMs(durationSeconds, flashes),
43
+ reasonKind: '',
44
+ title: '',
45
+ badge: '',
46
+ at: Date.now(),
47
+ ...extra,
48
+ };
49
+ }
50
+
51
+ /**
52
+ * 建一个通知调度器。
53
+ *
54
+ * @param {object} options
55
+ * @param {() => object} options.readConfig 每次现读配置(设置页改完要立刻生效)
56
+ * @param {(message: string) => void} options.log
57
+ * @param {object} options.hub 事件流中枢(见 hub.js)
58
+ */
59
+ export function createNotifier({ readConfig, log, hub }) {
60
+ const currentConfig = () => normalizeNotify(readConfig());
61
+
62
+ /**
63
+ * 网关请求的聚合槽。
64
+ *
65
+ * 为什么需要它:Codex 跑一个任务会为每次工具调用发一个请求,一个 40 步的
66
+ * 任务就是 40 条群消息。用户要的是「这个任务做完了」,不是「第 23 个请求
67
+ * 完成了」。所以把窗口内所有请求压成一条:耗时取首尾、token 累加、正文与
68
+ * 结局取最后一条(最后一步才是结论)。
69
+ */
70
+ let pending = null;
71
+ let settleTimer;
72
+
73
+ const clearPending = () => {
74
+ if (settleTimer !== undefined) {
75
+ clearTimeout(settleTimer);
76
+ settleTimer = undefined;
77
+ }
78
+ pending = null;
79
+ };
80
+
81
+ /** 把一条已渲染的消息发到当前所有可用渠道。 */
82
+ async function deliver(rendered) {
83
+ const config = currentConfig();
84
+ if (!config.enabled) return [];
85
+ const ready = readyChannels(config);
86
+ if (ready.length === 0) return [];
87
+
88
+ const results = await Promise.all(
89
+ ready.map((kind) =>
90
+ sendToChannel(config.channels[kind], kind, rendered, {
91
+ timeoutMs: config.timeoutMs,
92
+ log,
93
+ }),
94
+ ),
95
+ );
96
+ for (const result of results) {
97
+ if (result.ok) log(`通知已送达:${result.channel}`);
98
+ else log(`通知未送达:${result.channel} — ${result.detail ?? '未知原因'}`);
99
+ }
100
+ return results;
101
+ }
102
+
103
+ /**
104
+ * 把一条闪动事件推给所有打开的页面。
105
+ *
106
+ * 返回送达的页面数:设置页的「闪一下试试」直接用它,一个页面都没连着时
107
+ * 用户看到的是 0,而不是一个假装成功的提示。
108
+ */
109
+ function emitFlash({ reasonKind, title, inApp } = {}) {
110
+ const config = currentConfig();
111
+ if (!config.enabled) return 0;
112
+ const settings = normalizeInApp(inApp ?? config.inApp);
113
+ if (settings.enabled !== true) return 0;
114
+ return hub.emit('flash', flashPayload(settings, {
115
+ reasonKind: reasonKind ?? '',
116
+ title: typeof title === 'string' ? title : '',
117
+ badge: statusBadge(reasonKind),
118
+ }));
119
+ }
120
+
121
+ /** 把一条渲染好的通知发出去:先闪屏,再发群。 */
122
+ async function dispatch(rendered, reasonKind) {
123
+ // 闪屏是本机的,不该等网络。deliver 最长要等 timeoutMs(默认 8 秒),
124
+ // 排在它后面会让界面延迟到那时才闪,而那时用户早就切走看别的了。
125
+ emitFlash({ reasonKind, title: rendered.title });
126
+ await deliver(rendered);
127
+ }
128
+
129
+ /**
130
+ * 发掉一个聚合槽。
131
+ *
132
+ * 这里是网关请求唯一的出口:无论是窗口到期、还是插件卸载时被动冲刷,
133
+ * 都走这一条,避免「到期发了、冲刷又发一遍」。
134
+ */
135
+ async function flushGateway() {
136
+ const task = pending;
137
+ pending = null;
138
+ if (settleTimer !== undefined) {
139
+ clearTimeout(settleTimer);
140
+ settleTimer = undefined;
141
+ }
142
+ if (task === null) return;
143
+
144
+ const config = currentConfig();
145
+ if (!config.enabled || config.sources.gateway !== true) return;
146
+ if (!shouldNotify(config, task.reasonKind)) return;
147
+
148
+ const rendered = renderGatewayNotification({
149
+ reasonKind: task.reasonKind,
150
+ durationMs: task.lastAt - task.startedAt,
151
+ modelLabel: task.modelLabel,
152
+ clientLabel: config.gateway.showClient ? task.clientLabel : '',
153
+ protocol: task.protocol,
154
+ requestCount: task.requests,
155
+ reply: task.reply,
156
+ toolCallCount: task.toolCallCount,
157
+ usage: task.usage,
158
+ maxExcerptChars: config.maxExcerptChars,
159
+ failureMessage: task.failureMessage,
160
+ });
161
+ await dispatch(rendered, task.reasonKind);
162
+ }
163
+
164
+ /**
165
+ * 记一次网关请求。
166
+ *
167
+ * 不 await、不抛错:调用方(HTTP 处理器)只管记录,通知自己在后台完成。
168
+ * 工具调用步(`tool-calls`)也记进来——它是任务的一部分,只是不发通知;
169
+ * 它的耗时与 token 会累进最终那条。
170
+ */
171
+ function recordGatewayRequest(info) {
172
+ try {
173
+ const config = currentConfig();
174
+ if (!config.enabled || config.sources.gateway !== true) return;
175
+
176
+ const now = Date.now();
177
+ if (pending === null) {
178
+ // 起点用调用方给的「请求进网关的时刻」,没有才退回 now。
179
+ // 用 now 会让单请求任务的耗时恒为 0:这个函数在请求收尾时才被调用,
180
+ // 那时起点与终点是同一个瞬间。
181
+ const startedAt = Number.isFinite(info?.startedAt) ? info.startedAt : now;
182
+ pending = {
183
+ startedAt: Math.min(startedAt, now),
184
+ lastAt: now,
185
+ requests: 0,
186
+ usage: undefined,
187
+ reply: '',
188
+ toolCallCount: 0,
189
+ reasonKind: 'completed',
190
+ modelLabel: info?.modelLabel ?? '',
191
+ clientLabel: info?.clientLabel ?? '',
192
+ protocol: info?.protocol ?? '',
193
+ failureMessage: '',
194
+ };
195
+ }
196
+ pending.requests += 1;
197
+ pending.lastAt = now;
198
+ // 模型/客户端取最新一条:中途换模型是罕见但合法的事,报最新的更准。
199
+ if (typeof info?.modelLabel === 'string' && info.modelLabel !== '') pending.modelLabel = info.modelLabel;
200
+ if (typeof info?.clientLabel === 'string' && info.clientLabel !== '') pending.clientLabel = info.clientLabel;
201
+ if (typeof info?.protocol === 'string' && info.protocol !== '') pending.protocol = info.protocol;
202
+
203
+ const usage = info?.usage;
204
+ if (usage !== undefined && usage !== null) {
205
+ pending.usage = pending.usage === undefined
206
+ ? { ...usage, missing: [...(usage.missing ?? [])] }
207
+ : {
208
+ inputTokens: pending.usage.inputTokens + (usage.inputTokens ?? 0),
209
+ outputTokens: pending.usage.outputTokens + (usage.outputTokens ?? 0),
210
+ totalTokens: pending.usage.totalTokens + (usage.totalTokens ?? 0),
211
+ cachedReadTokens: pending.usage.cachedReadTokens + (usage.cachedReadTokens ?? 0),
212
+ available: true,
213
+ missing: [...new Set([...(pending.usage.missing ?? []), ...(usage.missing ?? [])])],
214
+ };
215
+ }
216
+ if (typeof info?.reply === 'string' && info.reply.trim() !== '') pending.reply = info.reply;
217
+ if (Number.isFinite(info?.toolCallCount)) pending.toolCallCount += info.toolCallCount;
218
+
219
+ // 结局以最后一步为准;但一个中间步成功不该把前面看到的失败抹掉。
220
+ const kind = typeof info?.reasonKind === 'string' && info.reasonKind !== ''
221
+ ? info.reasonKind
222
+ : 'completed';
223
+ if (kind !== 'tool-calls') {
224
+ pending.reasonKind = kind;
225
+ pending.failureMessage = typeof info?.failureMessage === 'string' ? info.failureMessage : '';
226
+ }
227
+
228
+ const settle = config.gateway.settleSeconds;
229
+ if (settle > 0) {
230
+ // 每个请求都把窗口往后推:窗口表示「安静了这么久就算任务结束」。
231
+ if (settleTimer !== undefined) clearTimeout(settleTimer);
232
+ settleTimer = setTimeout(() => {
233
+ settleTimer = undefined;
234
+ void flushGateway().catch((error) => log(`网关通知发送失败:${error?.message ?? error}`));
235
+ }, settle * 1000);
236
+ // 通知不该把进程钉住:宿主退出时它不能成为最后一个活句柄。
237
+ settleTimer.unref?.();
238
+ } else {
239
+ // 窗口关掉就是「每个请求都发」,此时不聚合。
240
+ void flushGateway().catch((error) => log(`网关通知发送失败:${error?.message ?? error}`));
241
+ }
242
+ } catch (error) {
243
+ log(`记录网关请求失败:${error?.message ?? error}`);
244
+ }
245
+ }
246
+
247
+ /**
248
+ * 发一条 DSH 会话回合的通知。
249
+ *
250
+ * 数据全部来自已提交的会话事件,不做任何推测。
251
+ */
252
+ async function notifySession({ session, events, reasonKind, durationMs, turn, modelLabel }) {
253
+ const config = currentConfig();
254
+ if (!config.enabled || config.sources.session !== true) return;
255
+ if (!shouldNotify(config, reasonKind)) return;
256
+
257
+ const rendered = renderSessionNotification({
258
+ reasonKind,
259
+ durationMs,
260
+ events,
261
+ turn,
262
+ maxExcerptChars: config.maxExcerptChars,
263
+ modelLabel: modelLabel ?? '',
264
+ });
265
+ await dispatch(rendered, reasonKind);
266
+ void session;
267
+ }
268
+
269
+ /** 设置页「发送测试」:发一条内容固定的样例,验证 webhook 通不通。 */
270
+ async function sendTest() {
271
+ const results = await deliver({
272
+ title: 'LLM 网关 · 任务通知测试',
273
+ body: [
274
+ '**✅ 这是一条测试通知**',
275
+ '',
276
+ '**📋 任务概要**',
277
+ '> 收到这条消息,说明渠道配置正确。',
278
+ '',
279
+ '**⏱️ 耗时**',
280
+ '> 3分12秒',
281
+ '',
282
+ '**🔢 token 消耗**',
283
+ '> 输入 12,340 输出 2,891',
284
+ '> 合计 **15,231**',
285
+ ].join('\n'),
286
+ });
287
+ return results;
288
+ }
289
+
290
+ return {
291
+ currentConfig,
292
+ readyChannels: () => readyChannels(currentConfig()),
293
+ deliver,
294
+ emitFlash,
295
+ recordGatewayRequest,
296
+ notifySession,
297
+ sendTest,
298
+ /** 主动闪一下(宿主侧),返回送达页面数。 */
299
+ flash() {
300
+ return emitFlash({});
301
+ },
302
+ /** 冲刷未到期的聚合槽。插件卸载、进程收尾时调。 */
303
+ async flush() {
304
+ await flushGateway();
305
+ },
306
+ /** 卸掉定时器。不调的话窗口定时器会拖住下一次 reconcile 的判断。 */
307
+ dispose() {
308
+ clearPending();
309
+ },
310
+ /** 当前有几个页面连着事件流。 */
311
+ get viewers() {
312
+ return hub.size;
313
+ },
314
+ };
315
+ }
@@ -0,0 +1,342 @@
1
+ /**
2
+ * 通知内容渲染。
3
+ *
4
+ * 两个触发源共用同一套排版(徽标、耗时、token),因为它们最终落在同一个
5
+ * 群聊里,格式不一致只会让人以为是两个插件在说话:
6
+ *
7
+ * renderGatewayNotification —— 外部客户端(Codex / SDK / 脚本)打完一个任务;
8
+ * renderSessionNotification —— DSH 自己的会话回合结束。
9
+ *
10
+ * 数据只取确定存在的字段:上游没给 usage 就写「未提供」,绝不补一个 0 出来。
11
+ * 一条编出来的数字比一条「不知道」坏得多——后者能被发现,前者会被当真。
12
+ */
13
+
14
+ /** 回合结局的中文说法;未收录的原样返回英文,不硬翻。 */
15
+ const REASON_LABELS = {
16
+ completed: '已完成',
17
+ error: '出错',
18
+ blocked: '被阻塞',
19
+ 'max-tokens': '超出输出上限',
20
+ aborted: '已中止',
21
+ interrupted: '已中断',
22
+ };
23
+
24
+ export function reasonLabel(kind) {
25
+ return REASON_LABELS[kind] ?? String(kind ?? '未知');
26
+ }
27
+
28
+ /** 里程碑文案:不同结局给不同的首要提示,避免「出错」也显示 ✅。 */
29
+ export function statusBadge(kind) {
30
+ if (kind === 'completed') return '✅ 任务完成';
31
+ if (kind === 'error') return '❌ 任务出错';
32
+ if (kind === 'blocked') return '⏸️ 任务待处理';
33
+ if (kind === 'max-tokens') return '⚠️ 输出被截断';
34
+ if (kind === 'aborted' || kind === 'interrupted') return '⏹️ 任务已中止';
35
+ return 'ℹ️ 回合结束';
36
+ }
37
+
38
+ /** 毫秒 → 「3分12秒」/「1小时02分」/「840毫秒」。 */
39
+ export function formatDuration(ms) {
40
+ if (!Number.isFinite(ms) || ms < 0) return '未知';
41
+ if (ms < 1000) return `${Math.round(ms)}毫秒`;
42
+ const totalSeconds = Math.round(ms / 1000);
43
+ const hours = Math.floor(totalSeconds / 3600);
44
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
45
+ const seconds = totalSeconds % 60;
46
+ if (hours > 0) return `${hours}小时${String(minutes).padStart(2, '0')}分`;
47
+ if (minutes > 0) return `${minutes}分${String(seconds).padStart(2, '0')}秒`;
48
+ return `${seconds}秒`;
49
+ }
50
+
51
+ /** 数字加千分位。 */
52
+ export function formatNumber(value) {
53
+ if (!Number.isFinite(value)) return '—';
54
+ return Math.round(value).toLocaleString('en-US');
55
+ }
56
+
57
+ /**
58
+ * 把上游 finish.reason 翻译成通知用的「结局种类」。
59
+ *
60
+ * 网关内部用的是 DSH 的 reason 形状(`{kind:'stop'|'tool-calls'|'max-tokens'|
61
+ * 'error'|'aborted'}`,失败时还带 failure),通知只需要一个粗粒度的词。
62
+ *
63
+ * `tool-calls` 单独返回:它意味着「这个请求只是整条任务的一步」,
64
+ * 不该被当成任务完成——由调用方决定跳过还是聚合(见 settle 窗口)。
65
+ */
66
+ export function reasonKindOf(finish) {
67
+ const kind = finish?.kind;
68
+ if (kind === 'error') return 'error';
69
+ if (kind === 'aborted') return 'aborted';
70
+ if (kind === 'max-tokens') return 'max-tokens';
71
+ if (kind === 'tool-calls') return 'tool-calls';
72
+ return 'completed';
73
+ }
74
+
75
+ /* ------------------------------------------------------------------ *
76
+ * 会话事件渲染(DSH 自己的回合)
77
+ * ------------------------------------------------------------------ */
78
+
79
+ /**
80
+ * 从事件流里汇总本轮的 token 用量。
81
+ *
82
+ * DSH 的 usage 挂在 assistant/message 上,一个回合可能有多条(多步推理),
83
+ * 所以要累加而不是取最后一条。字段缺失时记进 missing,让渲染层能显示
84
+ * 「未提供」而不是伪造一个 0。
85
+ *
86
+ * **缓存字段名是 `cacheReadTokens`,不是 `cachedReadTokens`。** 这是实测
87
+ * 出来的:从会话日志里读到的真实 usage 只有
88
+ * `{ inputTokens, outputTokens, totalTokens, cacheReadTokens }` 四个字段。
89
+ * 读错名字不会报错,只会让缓存数恒为 0——而 DSH 的 `totalTokens` 是
90
+ * **含缓存命中**的(实测 1409 + 138 + 12544 = 14091),于是通知里的
91
+ * 「合计」比「输入 + 输出」大出一大截,看起来像算错了。
92
+ *
93
+ * 两个拼写都认,是为了兼容其它适配器可能用的 OpenAI 式名字。
94
+ */
95
+ export function sumUsage(events, turn) {
96
+ const totals = {
97
+ inputTokens: 0,
98
+ outputTokens: 0,
99
+ totalTokens: 0,
100
+ cachedReadTokens: 0,
101
+ seen: false,
102
+ missing: [],
103
+ };
104
+
105
+ for (const event of events) {
106
+ if (event?.type !== 'assistant/message') continue;
107
+ if (turn !== undefined && event?.data?.turn !== undefined && event.data.turn !== turn) continue;
108
+ const usage = event?.data?.usage;
109
+ if (!usage || typeof usage !== 'object') continue;
110
+ totals.seen = true;
111
+
112
+ const input = Number(usage.inputTokens);
113
+ const output = Number(usage.outputTokens);
114
+ const total = Number(usage.totalTokens);
115
+ const cached = Number(
116
+ usage.cacheReadTokens ?? usage.cachedReadTokens ?? usage.cached_tokens,
117
+ );
118
+
119
+ if (Number.isFinite(input)) totals.inputTokens += input;
120
+ else if (!totals.missing.includes('输入')) totals.missing.push('输入');
121
+ if (Number.isFinite(output)) totals.outputTokens += output;
122
+ else if (!totals.missing.includes('输出')) totals.missing.push('输出');
123
+ if (Number.isFinite(total)) totals.totalTokens += total;
124
+ if (Number.isFinite(cached)) totals.cachedReadTokens += cached;
125
+ }
126
+
127
+ if (!totals.seen) return { ...totals, available: false };
128
+ if (totals.totalTokens === 0) {
129
+ // 上游没给合计时自己加:缓存命中已经含在输入里,不再重复相加。
130
+ totals.totalTokens = totals.inputTokens + totals.outputTokens;
131
+ }
132
+ return { ...totals, available: true };
133
+ }
134
+
135
+ /**
136
+ * 从事件流里取出最后一条 assistant 回复的纯文本,并裁到 maxChars。
137
+ * 只取 text 块;reasoning 不进通知正文。
138
+ */
139
+ export function lastReplyText(events, maxChars = 400) {
140
+ for (let i = events.length - 1; i >= 0; i -= 1) {
141
+ const event = events[i];
142
+ if (event?.type !== 'assistant/message') continue;
143
+ const content = event?.data?.message?.content;
144
+ if (!Array.isArray(content)) continue;
145
+ const text = content
146
+ .filter((block) => block?.type === 'text' && typeof block.text === 'string')
147
+ .map((block) => block.text)
148
+ .join('\n')
149
+ .trim();
150
+ if (text === '') continue;
151
+ return clampExcerpt(text, maxChars);
152
+ }
153
+ return '';
154
+ }
155
+
156
+ /** 截断一段正文,保留换行结构(调用方按行加引用前缀)。 */
157
+ export function clampExcerpt(text, maxChars) {
158
+ const value = typeof text === 'string' ? text.trim() : '';
159
+ if (value === '') return '';
160
+ if (!Number.isFinite(maxChars) || maxChars <= 0) return value;
161
+ if (value.length <= maxChars) return value;
162
+ return `${value.slice(0, maxChars).trimEnd()}…`;
163
+ }
164
+
165
+ /** 统计本轮工具调用次数与名称分布。 */
166
+ export function toolSummary(events, turn) {
167
+ const counts = new Map();
168
+ for (const event of events) {
169
+ if (event?.type !== 'tool/call') continue;
170
+ if (turn !== undefined && event?.data?.turn !== undefined && event.data.turn !== turn) continue;
171
+ const name = event?.data?.name;
172
+ if (typeof name !== 'string' || name === '') continue;
173
+ counts.set(name, (counts.get(name) ?? 0) + 1);
174
+ }
175
+ const total = [...counts.values()].reduce((a, b) => a + b, 0);
176
+ const top = [...counts.entries()]
177
+ .sort((a, b) => b[1] - a[1])
178
+ .slice(0, 4)
179
+ .map(([name, count]) => `${name}×${count}`)
180
+ .join('、');
181
+ return { total, top };
182
+ }
183
+
184
+ /** 从事件流里找最近的会话标题。 */
185
+ export function sessionTitle(events, fallback = 'DSH 任务') {
186
+ for (let i = events.length - 1; i >= 0; i -= 1) {
187
+ const event = events[i];
188
+ if (event?.type !== 'session/title') continue;
189
+ const title = event?.data?.title;
190
+ if (typeof title === 'string' && title.trim() !== '') return title.trim();
191
+ }
192
+ return fallback;
193
+ }
194
+
195
+ /** 正文里的三块内容:概要 / 耗时 / token。两个触发源共用。 */
196
+ function bodyLines({ reply, tools, durationMs, usage }) {
197
+ const lines = [];
198
+
199
+ lines.push('**📋 任务概要**');
200
+ if (reply !== '') {
201
+ for (const line of reply.split('\n').slice(0, 6)) {
202
+ const trimmed = line.trim();
203
+ if (trimmed !== '') lines.push(`> ${trimmed}`);
204
+ }
205
+ } else {
206
+ lines.push('> 本轮没有文字回复');
207
+ }
208
+ if (tools !== undefined && tools.total > 0) {
209
+ lines.push('', `工具调用:${tools.total} 次${tools.top ? `(${tools.top})` : ''}`);
210
+ }
211
+
212
+ lines.push('', '**⏱️ 耗时**', `> ${formatDuration(durationMs)}`);
213
+
214
+ lines.push('', '**🔢 token 消耗**');
215
+ if (usage === undefined || usage.available === false) {
216
+ lines.push('> 本轮未提供用量数据');
217
+ } else {
218
+ lines.push(
219
+ `> 输入 ${formatNumber(usage.inputTokens)} 输出 ${formatNumber(usage.outputTokens)}`,
220
+ `> 合计 **${formatNumber(usage.totalTokens)}**`
221
+ + `${usage.cachedReadTokens > 0 ? `(含缓存命中 ${formatNumber(usage.cachedReadTokens)})` : ''}`,
222
+ );
223
+ if (Array.isArray(usage.missing) && usage.missing.length > 0) {
224
+ lines.push(`> 注:上游未提供 ${usage.missing.join('、')} token 数`);
225
+ }
226
+ }
227
+ return lines;
228
+ }
229
+
230
+ /**
231
+ * 渲染 DSH 会话回合的通知。
232
+ *
233
+ * 与上一版(task-notify)的正文完全一致:用户已经习惯这个格式,
234
+ * 换插件没必要连排版一起换。
235
+ */
236
+ export function renderSessionNotification(input) {
237
+ const {
238
+ reasonKind,
239
+ durationMs,
240
+ events = [],
241
+ turn,
242
+ maxExcerptChars = 400,
243
+ modelLabel = '',
244
+ } = input;
245
+
246
+ const usage = sumUsage(events, turn);
247
+ const reply = lastReplyText(events, maxExcerptChars);
248
+ const tools = toolSummary(events, turn);
249
+ const title = sessionTitle(events);
250
+
251
+ const lines = [`**${statusBadge(reasonKind)}** ${reasonLabel(reasonKind)}`, ''];
252
+ lines.push(...bodyLines({ reply, tools, durationMs, usage }));
253
+
254
+ const titleLine = modelLabel ? `${title} · ${modelLabel}` : title;
255
+ return { title: titleLine, body: lines.join('\n') };
256
+ }
257
+
258
+ /* ------------------------------------------------------------------ *
259
+ * 网关请求渲染(外部客户端)
260
+ * ------------------------------------------------------------------ */
261
+
262
+ /**
263
+ * 把网关侧的 usage(OpenAI 字段名)换算成渲染层用的形状。
264
+ *
265
+ * 网关内部已经统一成 `usageToOpenAI()` 的产物,这里只做字段改名,
266
+ * 不再重新推导——否则两条路径的 token 数字会对不上。
267
+ */
268
+ export function usageFromWire(usage) {
269
+ if (usage === undefined || usage === null || typeof usage !== 'object') return undefined;
270
+ const input = Number(usage.prompt_tokens);
271
+ const output = Number(usage.completion_tokens);
272
+ const total = Number(usage.total_tokens);
273
+ const cached = Number(
274
+ usage.prompt_tokens_details?.cached_tokens ?? usage.prompt_cache_hit_tokens ?? 0,
275
+ );
276
+ const missing = [];
277
+ if (!Number.isFinite(input)) missing.push('输入');
278
+ if (!Number.isFinite(output)) missing.push('输出');
279
+ return {
280
+ available: true,
281
+ inputTokens: Number.isFinite(input) ? input : 0,
282
+ outputTokens: Number.isFinite(output) ? output : 0,
283
+ totalTokens: Number.isFinite(total) ? total : (Number.isFinite(input) ? input : 0) + (Number.isFinite(output) ? output : 0),
284
+ cachedReadTokens: Number.isFinite(cached) ? cached : 0,
285
+ missing,
286
+ };
287
+ }
288
+
289
+ /**
290
+ * 渲染一条网关请求的通知。
291
+ *
292
+ * 标题带客户端与模型:同一个群聊里可能同时有 Codex、一个脚本和别人的 SDK,
293
+ * 「哪来的、用的哪个模型」是这条消息最该先说清的两件事。
294
+ */
295
+ export function renderGatewayNotification(input) {
296
+ const {
297
+ reasonKind,
298
+ durationMs,
299
+ modelLabel = '',
300
+ clientLabel = '',
301
+ protocol = '',
302
+ requestCount = 1,
303
+ reply = '',
304
+ toolCallCount = 0,
305
+ usage,
306
+ maxExcerptChars = 400,
307
+ failureMessage = '',
308
+ } = input;
309
+
310
+ const lines = [`**${statusBadge(reasonKind)}** ${reasonLabel(reasonKind)}`, ''];
311
+ if (reasonKind === 'error' && failureMessage !== '') {
312
+ lines.push('**失败原因**', `> ${failureMessage}`, '');
313
+ }
314
+ lines.push(...bodyLines({
315
+ reply: clampExcerpt(reply, maxExcerptChars),
316
+ tools: toolCallCount > 0 ? { total: toolCallCount, top: '' } : undefined,
317
+ durationMs,
318
+ usage,
319
+ }));
320
+
321
+ if (protocol !== '' || requestCount > 1) {
322
+ lines.push('', '**🔌 请求**', `> ${[
323
+ protocol !== '' ? protocol : '网关',
324
+ requestCount > 1 ? `${requestCount} 次请求` : '',
325
+ ].filter(Boolean).join(' · ')}`);
326
+ }
327
+
328
+ const suffix = [clientLabel, modelLabel].filter((part) => part !== '').join(' · ');
329
+ const title = suffix !== '' ? `网关任务 · ${suffix}` : '网关任务';
330
+ return { title, body: lines.join('\n') };
331
+ }
332
+
333
+ /** 网关的只读状态文本,设置页顶部用它告诉用户「网关现在是什么样」。 */
334
+ export function formatGatewayStatus(status) {
335
+ if (status === undefined || status === null) return { ok: false, text: '网关状态未知' };
336
+ const where = `${status.host}:${status.port}`;
337
+ if (status.listening === false) {
338
+ return { ok: false, text: `未监听(${where});绑定失败时日志里有原因` };
339
+ }
340
+ const auth = status.auth === true ? '需 Bearer 认证' : '免认证(仅回环)';
341
+ return { ok: true, text: `监听 ${where} · ${status.models} 个模型 · ${auth}` };
342
+ }