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/lib/index.js ADDED
@@ -0,0 +1,1252 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import z from "@deepseek-ai/schemastery";
3
+ import shared from "./shared.cjs";
4
+ import store from "./store.cjs";
5
+ import http from "./http.cjs";
6
+
7
+ const {
8
+ sendJson,
9
+ drainRequest,
10
+ sendError,
11
+ sendBadRequest,
12
+ sendForbidden,
13
+ sendMethodNotAllowed,
14
+ readJsonBody
15
+ } = http;
16
+
17
+ const {
18
+ PRODUCER,
19
+ TOMBSTONE_TEXT,
20
+ planAction,
21
+ roundsOf,
22
+ createTurnLookup,
23
+ liveNodesOf,
24
+ messageIdOf,
25
+ messagesSummaryOf,
26
+ isTrustedRequest,
27
+ statusCodeOf,
28
+ isBusyError,
29
+ beijingDateKey,
30
+ periodInfo,
31
+ PRICE_TABLE,
32
+ routeOfMessage,
33
+ routeOfUsage,
34
+ routingOfProvider,
35
+ isBillableRoute,
36
+ costSwitches,
37
+ turnCostOfGroups,
38
+ deriveTurnUsage,
39
+ createTurnBuffer,
40
+ appendTurnEvent,
41
+ observeBalance,
42
+ validateCorrectionAmount,
43
+ pruneDailySpend,
44
+ yuanToCents,
45
+ foldSessionStats,
46
+ statsTimeline,
47
+ statsSessionRow,
48
+ statsSummary,
49
+ statsBudget,
50
+ settleSpend
51
+ } = shared;
52
+
53
+ const {
54
+ resolveStatePath,
55
+ loadCostState,
56
+ persistCostState,
57
+ DEFAULT_BUDGET_CENTS
58
+ } = store;
59
+
60
+ // ---------------------------------------------------------------------------
61
+ // 插件身份与依赖
62
+ // ---------------------------------------------------------------------------
63
+
64
+ const name = "dsh-message-actions";
65
+
66
+ const inject = ["webServer", "sessions", "agents"];
67
+
68
+ /**
69
+ * 宿主配置。所有字段必须 `.volatile()`,否则官方配置通道不认;
70
+ * 改 Config 需重启 DSH 生效。设置页顺序由这里的声明顺序决定。
71
+ */
72
+ const Config = z.object({
73
+ recall: z.boolean().default(true).volatile(),
74
+ share: z.boolean().default(true).volatile(),
75
+ export: z.boolean().default(true).volatile(),
76
+ delete: z.boolean().default(true).volatile(),
77
+ deleteFrom: z.boolean().default(true).volatile(),
78
+ confirm: z.boolean().default(true).volatile(),
79
+ stats: z.boolean().default(true).volatile(),
80
+ // 0.2.2 起「完成提示音」不再有独立开关:由 soundTone 的「off」表示关闭。
81
+ // 保留 sound 字段只为兼容旧配置(老配置 sound=false 视为关闭)。
82
+ sound: z.boolean().default(true).volatile(),
83
+ // 完成提示音音色:double | bell | soft | off。
84
+ soundTone: z.string().default("double").volatile(),
85
+ // 提示音音量 0–100(50 = 基准增益,0 = 静音),作用于全部音色。
86
+ soundVolume: z.number().min(0).max(100).default(50).volatile(),
87
+
88
+ // —— 费用统计(新增)——
89
+ usageStats: z.boolean().default(true).volatile(),
90
+ // 计费样式排在「单次消耗」之前;默认单行样式(compact)。
91
+ costLayout: z.string().default("compact").volatile(),
92
+ costPerTurn: z.boolean().default(true).volatile(),
93
+ costPerTurnAutoClose: z.number().min(0).max(600).default(0).volatile(),
94
+ costPeakValley: z.boolean().default(true).volatile()
95
+ });
96
+
97
+ // ---------------------------------------------------------------------------
98
+ // 信任围栏
99
+ // ---------------------------------------------------------------------------
100
+
101
+ /**
102
+ * 请求入站三重围栏。回环 Host 与 Sec-Fetch-Site/Origin 校验为纯逻辑
103
+ * (见 shared.cjs 的 isLoopbackHost / isTrustedRequest),此处仅实时解析
104
+ * webServer 同源地址。
105
+ */
106
+ function isTrusted(req, webServer) {
107
+ let expectedOrigin;
108
+ try {
109
+ expectedOrigin = webServer.getOrigin();
110
+ } catch {
111
+ expectedOrigin = undefined;
112
+ }
113
+ return isTrustedRequest({
114
+ host: req.headers.host,
115
+ secFetchSite: req.headers["sec-fetch-site"],
116
+ origin: req.headers.origin,
117
+ expectedOrigin
118
+ });
119
+ }
120
+
121
+ // ---------------------------------------------------------------------------
122
+ // 事件与随机 id
123
+ // ---------------------------------------------------------------------------
124
+
125
+ /** 由消息 id 反查表面节点的 seq;找不到返回 null。 */
126
+ function resolveSeqByMessageId(events, nodes, messageId) {
127
+ for (const seq of nodes) {
128
+ const event = events[seq];
129
+ if (event && messageIdOf(event) === messageId) return seq;
130
+ }
131
+ return null;
132
+ }
133
+
134
+ function newTombstoneId() {
135
+ try {
136
+ return `dma-${randomUUID()}`;
137
+ } catch {
138
+ return `dma-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
139
+ }
140
+ }
141
+
142
+ // ---------------------------------------------------------------------------
143
+ // 路由处理器
144
+ // ---------------------------------------------------------------------------
145
+
146
+ // ---------------------------------------------------------------------------
147
+ // 附件回读(撤回后恢复图片 / 文件)
148
+ // ---------------------------------------------------------------------------
149
+
150
+ const ATTACHMENT_ROUTE = "/dsh-message-actions/attachment";
151
+
152
+ /** 在会话事件里按 attachmentId 找回原始附件引用(只查用户消息)。 */
153
+ function attachmentRefFromEvents(events, attachmentId) {
154
+ for (const event of events) {
155
+ if (!event || event.type !== "user/message") continue;
156
+ const content = event.data && event.data.content;
157
+ if (!Array.isArray(content)) continue;
158
+ for (const block of content) {
159
+ if (!block || (block.type !== "image" && block.type !== "file")) continue;
160
+ const ref = block.attachment;
161
+ if (ref && ref.attachmentId === attachmentId) return { kind: block.type, ref: ref };
162
+ }
163
+ }
164
+ return null;
165
+ }
166
+
167
+ /**
168
+ * `/dsh-message-actions/attachment`:按 id 回读附件原字节。
169
+ * 图片走 `attachments.readImage`(宿主归一化后的字节),文件走
170
+ * `readFileStream`(原样字节);响应直接流式返回,不经过 JSON 编码。
171
+ */
172
+ function makeAttachmentHandler(ctx) {
173
+ return async function handleAttachment(req, res) {
174
+ if (req.method !== "GET") {
175
+ drainRequest(req);
176
+ sendMethodNotAllowed(res, "GET");
177
+ return;
178
+ }
179
+ if (!isTrusted(req, ctx.webServer)) {
180
+ drainRequest(req);
181
+ sendForbidden(res);
182
+ return;
183
+ }
184
+ let query;
185
+ try {
186
+ query = new URL(req.url, "http://localhost").searchParams;
187
+ } catch {
188
+ sendBadRequest(res);
189
+ return;
190
+ }
191
+ const sessionId = query.get("sessionId") || "";
192
+ const attachmentId = query.get("attachmentId") || "";
193
+ if (!sessionId || !attachmentId) {
194
+ sendBadRequest(res);
195
+ return;
196
+ }
197
+
198
+ const agent = ctx.agents.get(sessionId);
199
+ const session = agent && agent.session;
200
+ if (!session || typeof session.snapshotEvents !== "function") {
201
+ sendError(res, 409, "SESSION_NOT_LIVE");
202
+ return;
203
+ }
204
+ const found = attachmentRefFromEvents(session.snapshotEvents(), attachmentId);
205
+ if (!found) {
206
+ sendError(res, 404, "ATTACHMENT_NOT_FOUND");
207
+ return;
208
+ }
209
+ const store = ctx.get("attachments");
210
+ if (!store) {
211
+ sendError(res, 503, "ATTACHMENT_UNAVAILABLE");
212
+ return;
213
+ }
214
+
215
+ const name = (found.ref && found.ref.name) || (found.kind === "image" ? "image" : "file");
216
+ const headers = {
217
+ "content-type": (found.ref && found.ref.mediaType) || (found.kind === "image" ? "image/png" : "application/octet-stream"),
218
+ "cache-control": "no-store",
219
+ "x-content-type-options": "nosniff",
220
+ "cross-origin-resource-policy": "same-origin",
221
+ "content-disposition": "attachment; filename*=UTF-8''" + encodeURIComponent(name)
222
+ };
223
+ if (Number.isSafeInteger(found.ref.bytes)) headers["content-length"] = found.ref.bytes;
224
+
225
+ try {
226
+ if (found.kind === "image") {
227
+ if (typeof store.readImage !== "function") {
228
+ sendError(res, 503, "ATTACHMENT_UNAVAILABLE");
229
+ return;
230
+ }
231
+ const image = await store.readImage(found.ref);
232
+ // 图片可能被宿主重新编码,长度与原始 ref.bytes 不同,必须用实际字节数。
233
+ const bytes = Buffer.from(image.data);
234
+ headers["content-length"] = bytes.length;
235
+ res.writeHead(200, headers);
236
+ res.end(bytes);
237
+ return;
238
+ }
239
+ if (typeof store.readFileStream !== "function") {
240
+ sendError(res, 503, "ATTACHMENT_UNAVAILABLE");
241
+ return;
242
+ }
243
+ res.writeHead(200, headers);
244
+ for await (const chunk of store.readFileStream(found.ref)) {
245
+ res.write(chunk);
246
+ }
247
+ res.end();
248
+ } catch {
249
+ if (res.headersSent) {
250
+ try {
251
+ res.destroy();
252
+ } catch {
253
+ /* ignore */
254
+ }
255
+ return;
256
+ }
257
+ sendError(res, 500, "ATTACHMENT_READ_FAILED");
258
+ }
259
+ };
260
+ }
261
+
262
+ // ---------------------------------------------------------------------------
263
+ // 删除动作
264
+ // ---------------------------------------------------------------------------
265
+
266
+ function makeActionHandler(ctx) {
267
+ return async function handleAction(req, res) {
268
+ if (req.method !== "POST") {
269
+ drainRequest(req);
270
+ sendMethodNotAllowed(res, "POST");
271
+ return;
272
+ }
273
+ if (!isTrusted(req, ctx.webServer)) {
274
+ drainRequest(req);
275
+ sendForbidden(res);
276
+ return;
277
+ }
278
+ const contentType = (req.headers["content-type"] || "").split(";")[0].trim().toLowerCase();
279
+ if (contentType !== "application/json") {
280
+ drainRequest(req);
281
+ sendBadRequest(res);
282
+ return;
283
+ }
284
+
285
+ const body = await readJsonBody(req, res);
286
+ if (body === null) return;
287
+ if (!body || typeof body !== "object") {
288
+ sendBadRequest(res);
289
+ return;
290
+ }
291
+
292
+ const { sessionId, action, seq, messageId } = body;
293
+ if (typeof sessionId !== "string" || sessionId.length === 0) {
294
+ sendBadRequest(res);
295
+ return;
296
+ }
297
+ if (action !== "recall" && action !== "delete" && action !== "deleteFrom") {
298
+ sendBadRequest(res);
299
+ return;
300
+ }
301
+ const hasSeq = Number.isSafeInteger(seq) && seq >= 0;
302
+ const hasMessageId = typeof messageId === "string" && messageId.length > 0;
303
+ if (!hasSeq && !hasMessageId) {
304
+ sendBadRequest(res);
305
+ return;
306
+ }
307
+
308
+ const agent = ctx.agents.get(sessionId);
309
+ if (agent === undefined || agent.session === undefined) {
310
+ sendError(res, 409, "SESSION_NOT_LIVE");
311
+ return;
312
+ }
313
+ const session = agent.session;
314
+ if (agent.status === "running") {
315
+ sendError(res, 423, "AGENT_BUSY");
316
+ return;
317
+ }
318
+
319
+ const events = session.snapshotEvents();
320
+ const nodes = [...session.surface.nodes];
321
+
322
+ let targetSeq = seq;
323
+ if (!hasSeq) {
324
+ targetSeq = resolveSeqByMessageId(events, nodes, messageId);
325
+ if (targetSeq === null) {
326
+ sendError(res, 409, "TARGET_NOT_FOUND");
327
+ return;
328
+ }
329
+ }
330
+
331
+ const plan = planAction(events, nodes, { action, seq: targetSeq });
332
+ if (!plan.ok) {
333
+ sendError(res, statusCodeOf(plan.code), plan.code);
334
+ return;
335
+ }
336
+
337
+ const data = {
338
+ role: "user",
339
+ id: newTombstoneId(),
340
+ content: [{ type: "text", text: TOMBSTONE_TEXT[action] }],
341
+ source: {
342
+ kind: "user",
343
+ producer: PRODUCER,
344
+ action,
345
+ via: plan.via,
346
+ removed: plan.removed,
347
+ kinds: plan.kinds,
348
+ turn: plan.turn
349
+ }
350
+ };
351
+
352
+ try {
353
+ await agent.runMaintenance(async () => {
354
+ session.append("user/message", data, {
355
+ surfaceOp: { op: "replace", startSeq: plan.startSeq, endSeq: plan.endSeq },
356
+ sourceEventSeqs: plan.removed
357
+ });
358
+ await ctx.sessions.flush(session);
359
+ });
360
+ } catch (err) {
361
+ // 优先按结构化字段判定 busy(err.code / err.status);宿主的忙错误目前
362
+ // 没有 code,此时才回退到文案匹配。
363
+ if (isBusyError(err)) {
364
+ sendError(res, 423, "AGENT_BUSY");
365
+ return;
366
+ }
367
+ const message = err instanceof Error ? err.message : String(err);
368
+ if (typeof ctx.logger?.warn === "function") {
369
+ ctx.logger.warn(`[dsh-message-actions] ${action} failed: ${message}`);
370
+ }
371
+ sendError(res, 500, "INTERNAL");
372
+ return;
373
+ }
374
+
375
+ sendJson(res, 200, {
376
+ ok: true,
377
+ value: {
378
+ action,
379
+ seq,
380
+ via: plan.via,
381
+ removed: plan.removed,
382
+ turn: plan.turn,
383
+ step: plan.step,
384
+ refillText: plan.refillText,
385
+ attachments: plan.attachments || []
386
+ }
387
+ });
388
+ };
389
+ }
390
+
391
+ function makeMessagesHandler(ctx) {
392
+ return async function handleMessages(req, res) {
393
+ if (req.method !== "GET") {
394
+ drainRequest(req);
395
+ sendMethodNotAllowed(res, "GET");
396
+ return;
397
+ }
398
+ if (!isTrusted(req, ctx.webServer)) {
399
+ drainRequest(req);
400
+ sendForbidden(res);
401
+ return;
402
+ }
403
+ const url = new URL(req.url || "/", "http://x");
404
+ const sessionId = url.searchParams.get("sessionId");
405
+ if (!sessionId) {
406
+ sendBadRequest(res);
407
+ return;
408
+ }
409
+
410
+ const agent = ctx.agents.get(sessionId);
411
+ if (agent === undefined || agent.session === undefined) {
412
+ sendError(res, 409, "SESSION_NOT_LIVE");
413
+ return;
414
+ }
415
+ const session = agent.session;
416
+
417
+ const events = session.snapshotEvents();
418
+ const nodes = [...session.surface.nodes];
419
+
420
+ // user/message 没有 data.turn(真实日志里只有 assistant/tool 带 turn),
421
+ // 需要按 turn/start~turn/end 区间推导,否则问行按钮找不到对应 seq。
422
+ // 一次构建索引与 seq→turn 映射,供 rows / rounds / goneTurns 复用。
423
+ const turns = createTurnLookup(events);
424
+
425
+ // 全文按需接口:只给分享图 / 导出使用,普通 3s 轮询不经过这里。
426
+ if (url.searchParams.get("full") === "1") {
427
+ const turnsParam = url.searchParams.get("turns");
428
+ let turnFilter = null;
429
+ if (turnsParam !== null && turnsParam !== "") {
430
+ turnFilter = new Set(
431
+ turnsParam.split(",")
432
+ .filter((s) => s.trim() !== "")
433
+ .map((s) => Number(s))
434
+ .filter(Number.isSafeInteger)
435
+ );
436
+ }
437
+ const rounds = roundsOf(events, nodes, turns);
438
+ const liveNodes = liveNodesOf(events, nodes);
439
+ const lastSeq = liveNodes.length > 0 ? liveNodes[liveNodes.length - 1] : 0;
440
+ sendJson(res, 200, {
441
+ ok: true,
442
+ value: {
443
+ version: Number.isSafeInteger(lastSeq) ? lastSeq : 0,
444
+ nodeCount: liveNodes.length,
445
+ rounds: turnFilter === null ? rounds : rounds.filter((round) => turnFilter.has(round.turn))
446
+ }
447
+ });
448
+ return;
449
+ }
450
+
451
+ let filter = null;
452
+ const seqsParam = url.searchParams.get("seqs");
453
+ if (seqsParam !== null && seqsParam !== "") {
454
+ filter = new Set(
455
+ seqsParam.split(",")
456
+ .filter((s) => s.trim() !== "")
457
+ .map((s) => Number(s))
458
+ .filter(Number.isSafeInteger)
459
+ );
460
+ }
461
+
462
+ // 增量游标:since=<上次快照 version> 时只回新增行(不带 since 仍为全量)。
463
+ // 选择游标而非 seqs 列表:seqs 在这里是「包含列表」,且长会话已持有 seq
464
+ // 会无限增长;游标只传一个整数,语义与追加式事件日志天然吻合。
465
+ const sinceParam = url.searchParams.get("since");
466
+ let since = null;
467
+ if (sinceParam !== null && sinceParam !== "") {
468
+ const parsed = Number(sinceParam.trim());
469
+ since = Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : null;
470
+ }
471
+
472
+ // 摘要轮询:只回 preview / words / usage / callId,不回正文。
473
+ // 系统 / 开发者提示词与工具结果正文从不进入摘要(预览也只覆盖问 / 答)。
474
+ sendJson(res, 200, {
475
+ ok: true,
476
+ value: messagesSummaryOf(events, nodes, turns, { filter, since, previewLimit: 200 })
477
+ });
478
+ };
479
+ }
480
+
481
+ // ---------------------------------------------------------------------------
482
+ // 费用统计服务(余额观测 + 单次结算 + 持久化状态)
483
+ // ---------------------------------------------------------------------------
484
+
485
+ const COST_REFRESH_MIN_INTERVAL_MS = 60 * 1000;
486
+ // 结算推送:客户端长轮询最长等待时长,必须小于客户端 15s 请求超时。
487
+ const COST_SETTLE_WAIT_MS = 10 * 1000;
488
+ const COST_BALANCE_TIMEOUT_MS = 10 * 1000;
489
+ const ROUTING_TIMEOUT_MS = 3 * 1000;
490
+ const ROUTING_CACHE_MS = 5 * 1000;
491
+ const DSH_VERSION_FALLBACK = "0.2.1";
492
+
493
+ /** getBalance 的客户端元数据:时区固定北京时间,不随本机漂移。 */
494
+ function accountClientMetadata() {
495
+ const env = typeof process !== "undefined" && process.env ? process.env : {};
496
+ const version = typeof env.DSH_VERSION === "string" && env.DSH_VERSION.trim()
497
+ ? env.DSH_VERSION.trim()
498
+ : DSH_VERSION_FALLBACK;
499
+ return { version, locale: "zh-CN", timezoneOffsetSeconds: 8 * 3600 };
500
+ }
501
+
502
+ /** 事件时刻:优先数值 time,其次 ISO 字符串,最后宿主收包时刻。 */
503
+ function eventTime(event) {
504
+ if (event && typeof event === "object") {
505
+ if (typeof event.time === "number" && Number.isFinite(event.time)) return event.time;
506
+ if (typeof event.time === "string") {
507
+ const parsed = Date.parse(event.time);
508
+ if (Number.isFinite(parsed)) return parsed;
509
+ }
510
+ if (event.data && typeof event.data.at === "number" && Number.isFinite(event.data.at)) {
511
+ return event.data.at;
512
+ }
513
+ }
514
+ return Date.now();
515
+ }
516
+
517
+ /** 钱包列表按 CNY 求和(其他币种忽略,不换算)。
518
+ * 正金额按官方「账号与余额」的规则截断至分:API 原始字符串可能带三位以上小数,
519
+ * 四舍五入会把 5.999… 显示成 6.00,与官方页面的 5.99 差一分。 */
520
+ function sumCnyWallets(wallets) {
521
+ if (!Array.isArray(wallets)) return 0;
522
+ let cents = 0;
523
+ for (const wallet of wallets) {
524
+ if (!wallet || typeof wallet !== "object") continue;
525
+ if (wallet.currency !== "CNY") continue;
526
+ const value = yuanToCents(wallet.balance, "truncate");
527
+ if (value !== null) cents += value;
528
+ }
529
+ return cents;
530
+ }
531
+
532
+ function withTimeout(promise, ms) {
533
+ let timer;
534
+ const timeout = new Promise((_, reject) => {
535
+ timer = setTimeout(() => reject(new Error("balance request timed out")), ms);
536
+ });
537
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
538
+ }
539
+
540
+ function accountServiceOf(ctx) {
541
+ try {
542
+ const service = ctx.get("deepseekAccount");
543
+ if (service && typeof service.getBalance === "function") return service;
544
+ } catch {
545
+ /* 服务缺失 */
546
+ }
547
+ return null;
548
+ }
549
+
550
+ async function hasApiKey(ctx) {
551
+ try {
552
+ const credentials = ctx.get("credentials");
553
+ if (credentials && typeof credentials.resolve === "function") {
554
+ const resolved = await credentials.resolve("DEEPSEEK_API_KEY");
555
+ const value = resolved && typeof resolved === "object" ? resolved.value : resolved;
556
+ if (typeof value === "string" && value.trim().length > 0) return true;
557
+ }
558
+ } catch {
559
+ /* 凭据服务不可用,回退环境变量 */
560
+ }
561
+ const env = typeof process !== "undefined" && process.env ? process.env : {};
562
+ return typeof env.DEEPSEEK_API_KEY === "string" && env.DEEPSEEK_API_KEY.trim().length > 0;
563
+ }
564
+
565
+ /**
566
+ * 创建费用统计服务。内存状态为唯一读写源,写盘为整份原子替换。
567
+ * @param ctx Cordis 宿主上下文
568
+ * @param config 宿主 Config(volatile 对象)
569
+ */
570
+ function createCostService(ctx, config) {
571
+ const cfg = config || {};
572
+ // 运行时读取开关,默认值与旧版保持一致(未配置 = 开启)。
573
+ const switches = () => costSwitches(cfg);
574
+ const isEnabled = () => switches().enabled;
575
+
576
+ const statePath = resolveStatePath();
577
+ const loaded = loadCostState(statePath, ctx.logger);
578
+ const state = loaded.state;
579
+ const readOnly = loaded.readOnly;
580
+
581
+ if (!isEnabled()) {
582
+ // 启动时总开关关闭:丢掉上次的余额基线,重新开启后首次观测只建基线,不补记关闭期间的差额。
583
+ state.lastBalanceCents = null;
584
+ state.lastBalanceAt = 0;
585
+ }
586
+ let lastEnabled = isEnabled();
587
+
588
+ const cache = { rechargeCents: null, bonusCents: null, totalCents: null, updatedAt: 0 };
589
+ const buffers = new Map();
590
+ const MAX_BUFFERS = 200;
591
+ let lastTurn = null;
592
+ // 结算事件:客户端长轮询靠它即时唤醒,避免等下一次 5 秒轮询。
593
+ const settleWaiters = new Set();
594
+ function notifyTurnSettled() {
595
+ for (const wake of [...settleWaiters]) {
596
+ try {
597
+ wake();
598
+ } catch {
599
+ // 单个等待者出错不影响其它客户端
600
+ }
601
+ }
602
+ }
603
+ function waitTurnSettled(ms) {
604
+ return new Promise((resolve) => {
605
+ let done = false;
606
+ const finish = () => {
607
+ if (done) return;
608
+ done = true;
609
+ clearTimeout(timer);
610
+ settleWaiters.delete(finish);
611
+ resolve();
612
+ };
613
+ const timer = setTimeout(finish, ms);
614
+ settleWaiters.add(finish);
615
+ });
616
+ }
617
+ let inFlight = null;
618
+ let lastFetchFailed = false;
619
+ let lastMessageProvider;
620
+ let lastHeaderProvider;
621
+ let routingCache = { at: 0, value: null };
622
+
623
+ const warn = (message) => {
624
+ if (typeof ctx.logger?.warn === "function") ctx.logger.warn(`[dsh-message-actions] ${message}`);
625
+ };
626
+
627
+ /**
628
+ * 写盘并返回结果:`{ ok:true }` 或 `{ ok:false, error }`。
629
+ * 只读 / 写入失败不再被吞掉——调用方(余额校正路由)据此返回 500,
630
+ * 避免客户端把未落盘的写操作显示为成功。
631
+ */
632
+ function persist() {
633
+ state.updatedAt = Date.now();
634
+ state.dailySpendCents = pruneDailySpend(state.dailySpendCents, state.updatedAt, shared.DAILY_KEEP_DAYS);
635
+ return persistCostState(statePath, state, readOnly, ctx.logger);
636
+ }
637
+
638
+ async function routingInfo() {
639
+ const now = Date.now();
640
+ if (routingCache.value && now - routingCache.at < ROUTING_CACHE_MS) return routingCache.value;
641
+
642
+ const provider = lastMessageProvider || lastHeaderProvider;
643
+ const mapped = routingOfProvider(provider);
644
+ const finish = (value) => {
645
+ routingCache = { at: Date.now(), value };
646
+ return value;
647
+ };
648
+ if (mapped) return finish({ routing: mapped, provider });
649
+
650
+ let hasKey = false;
651
+ try {
652
+ hasKey = await withTimeout(Promise.resolve(hasApiKey(ctx)), ROUTING_TIMEOUT_MS);
653
+ } catch {
654
+ hasKey = false; // 凭据服务卡住时按未配置处理,继续尝试账户路由
655
+ }
656
+ if (hasKey) return finish({ routing: "api-key", provider: "deepseek-official" });
657
+
658
+ const account = accountServiceOf(ctx);
659
+ if (!account) return finish({ routing: "unavailable", provider: undefined });
660
+ try {
661
+ const snapshot = await withTimeout(Promise.resolve(account.getState()), ROUTING_TIMEOUT_MS);
662
+ const status = snapshot && typeof snapshot === "object" ? snapshot.status : undefined;
663
+ if (status === "credential-stored") return finish({ routing: "account", provider: "deepseek-account" });
664
+ return finish({ routing: "signed-out", provider: undefined });
665
+ } catch {
666
+ return finish({ routing: "unavailable", provider: undefined });
667
+ }
668
+ }
669
+
670
+ async function fetchOnce() {
671
+ const routing = (await routingInfo()).routing;
672
+ if (routing !== "account") {
673
+ lastFetchFailed = false;
674
+ return;
675
+ }
676
+ state.lastAttemptAt = Date.now();
677
+ const account = accountServiceOf(ctx);
678
+ if (!account) {
679
+ lastFetchFailed = true;
680
+ return;
681
+ }
682
+ let result;
683
+ try {
684
+ result = await withTimeout(
685
+ Promise.resolve(account.getBalance(accountClientMetadata())),
686
+ COST_BALANCE_TIMEOUT_MS
687
+ );
688
+ } catch {
689
+ lastFetchFailed = true;
690
+ return;
691
+ }
692
+ if (!result || typeof result !== "object" || (typeof result.status === "string" && result.status !== "ready")) {
693
+ lastFetchFailed = true;
694
+ return;
695
+ }
696
+ const rechargeCents = sumCnyWallets(result.value);
697
+ const bonusCents = sumCnyWallets(result.bonusWallets);
698
+ const totalCents = rechargeCents + bonusCents;
699
+ const at = Date.now();
700
+
701
+ cache.rechargeCents = rechargeCents;
702
+ cache.bonusCents = bonusCents;
703
+ cache.totalCents = totalCents;
704
+ cache.updatedAt = at;
705
+ lastFetchFailed = false;
706
+
707
+ const observed = observeBalance(state, { cents: totalCents, routing: "account", at });
708
+ Object.assign(state, observed.state);
709
+ state.lastAttemptAt = at;
710
+ persist();
711
+ }
712
+
713
+ /** 背景 / 强制刷新;单飞 + 60s 节流 + 10s 超时。 */
714
+ function refresh(force) {
715
+ const enabled = isEnabled();
716
+ if (enabled !== lastEnabled) {
717
+ lastEnabled = enabled;
718
+ if (!enabled) {
719
+ // 运行中关闭总开关:与「启动时已关闭」同路径,丢弃余额基线。
720
+ // 重新开启后首次观测只建基线,不把关闭期间的消费计入「日用」。
721
+ state.lastBalanceCents = null;
722
+ state.lastBalanceAt = 0;
723
+ persist();
724
+ }
725
+ }
726
+ if (!enabled) return Promise.resolve();
727
+ if (inFlight) return inFlight;
728
+ const now = Date.now();
729
+ if (!force && now - state.lastAttemptAt < COST_REFRESH_MIN_INTERVAL_MS) return Promise.resolve();
730
+ inFlight = fetchOnce()
731
+ .catch((err) => {
732
+ lastFetchFailed = true;
733
+ warn(`balance refresh failed: ${err instanceof Error ? err.message : String(err)}`);
734
+ })
735
+ .finally(() => {
736
+ inFlight = null;
737
+ });
738
+ return inFlight;
739
+ }
740
+
741
+ /**
742
+ * 保存预算(分)。落盘失败时回滚内存值:
743
+ * 不把未落盘的设置伪装成成功。
744
+ */
745
+ function applyBudget(cents) {
746
+ const previous = state.budgetCents;
747
+ state.budgetCents = Math.max(0, Math.round(Number.isFinite(cents) ? cents : 0));
748
+ const saved = persist();
749
+ if (!saved.ok) state.budgetCents = previous;
750
+ return saved;
751
+ }
752
+
753
+ /** 当前预算(分);旧状态文件缺字段时回落到默认 ¥5。 */
754
+ function budgetCents() {
755
+ return Number.isFinite(state.budgetCents) && state.budgetCents >= 0
756
+ ? Math.round(state.budgetCents)
757
+ : DEFAULT_BUDGET_CENTS;
758
+ }
759
+
760
+ async function stateValue() {
761
+ const now = Date.now();
762
+ const routing = (await routingInfo()).routing;
763
+ let status;
764
+ if (routing === "signed-out") status = "signed-out";
765
+ else if (routing === "api-key") status = "api-key";
766
+ else if (routing === "unavailable") status = "unavailable";
767
+ else if (routing === "local") status = "local";
768
+ else status = cache.updatedAt > 0 && !lastFetchFailed ? "ready" : "stale";
769
+
770
+ const period = periodInfo(now);
771
+ return {
772
+ status,
773
+ billing: routing,
774
+ balance: {
775
+ rechargeCents: cache.rechargeCents,
776
+ bonusCents: cache.bonusCents,
777
+ totalCents: cache.totalCents,
778
+ updatedAt: cache.updatedAt,
779
+ refreshing: inFlight !== null
780
+ },
781
+ dailyCents: state.dailySpendCents[beijingDateKey(now)] || 0,
782
+ observedSpendCents: state.observedSpendTotalCents,
783
+ period: period.period,
784
+ nextChangeAt: period.nextChangeAt,
785
+ lastTurn: switches().perTurn ? lastTurn : null
786
+ };
787
+ }
788
+
789
+ /** 会话事件:跟踪最近模型路由,并在 turn/end 时结算本轮。 */
790
+ function onSessionEvent(session, event) {
791
+ if (!isEnabled()) return;
792
+ if (!event || typeof event !== "object") return;
793
+ const sessionId = session && typeof session.id === "string" ? session.id : undefined;
794
+ if (!sessionId) return;
795
+ const type = event.type;
796
+ const data = event.data || {};
797
+
798
+ if (type === "assistant/message") {
799
+ const route = routeOfUsage(data.usage) || routeOfMessage(data.message);
800
+ if (route) {
801
+ lastMessageProvider = route.provider;
802
+ routingCache = { at: 0, value: null };
803
+ }
804
+ } else if (type === "request/header") {
805
+ const provider = data.header && data.header.config ? data.header.config.provider : undefined;
806
+ if (typeof provider === "string" && provider.length > 0) {
807
+ lastHeaderProvider = provider;
808
+ routingCache = { at: 0, value: null };
809
+ }
810
+ }
811
+
812
+ if (!switches().perTurn) {
813
+ // 运行中关闭「单次」后不再保留旧的 lastTurn,避免重新开启时闪回过期金额;
814
+ // 但当日用量仍按结算累加(统计表与费用卡片共用这一份数字)。
815
+ lastTurn = null;
816
+ }
817
+ if (type === "turn/start") {
818
+ // 防御性上限:会话中途异常结束(没有 turn/end)时不让缓冲无限增长。
819
+ if (buffers.size >= MAX_BUFFERS && !buffers.has(sessionId)) {
820
+ const oldest = buffers.keys().next();
821
+ if (!oldest.done) buffers.delete(oldest.value);
822
+ }
823
+ buffers.set(sessionId, createTurnBuffer(
824
+ Number.isSafeInteger(data.turn) ? data.turn : undefined,
825
+ eventTime(event)
826
+ ));
827
+ return;
828
+ }
829
+
830
+ const buffer = buffers.get(sessionId);
831
+ if (!buffer) return; // 未见 turn/start:不回放历史
832
+ appendTurnEvent(buffer, event);
833
+ if (type !== "turn/end") return;
834
+
835
+ buffers.delete(sessionId);
836
+ if (buffer.overflow) return;
837
+ const usage = deriveTurnUsage(buffer.events);
838
+ if (!usage) return;
839
+ const at = Number.isFinite(usage.at) ? usage.at : buffer.at;
840
+ const period = periodInfo(at).period;
841
+ const endedAt = Number.isFinite(usage.endedAt) ? usage.endedAt : eventTime(event);
842
+ // 只对 DeepSeek 官方路由结算金额;本地模型的 token 仍然计数,但不进「日用」。
843
+ const billableGroups = usage.groups.filter((group) => group && isBillableRoute(group.provider, group.model));
844
+ const costMicros = turnCostOfGroups(billableGroups, period, PRICE_TABLE);
845
+ const turn = Number.isSafeInteger(usage.turn) ? usage.turn : buffer.turn;
846
+
847
+ // 结算即累加:当日用量与「单次」同一时刻更新,余额观测随后只补差额。
848
+ const settled = settleSpend(state, {
849
+ micros: costMicros,
850
+ at: endedAt,
851
+ key: `${sessionId}:${turn == null ? "" : turn}:${endedAt}`
852
+ });
853
+ if (settled.applied) {
854
+ Object.assign(state, settled.state);
855
+ persist();
856
+ }
857
+
858
+ if (!switches().perTurn) return;
859
+ lastTurn = {
860
+ at,
861
+ endedAt,
862
+ provider: usage.provider,
863
+ models: usage.models,
864
+ tokens: usage.tokens,
865
+ costMicros,
866
+ turn
867
+ };
868
+ notifyTurnSettled();
869
+ }
870
+
871
+ function dispose() {
872
+ buffers.clear();
873
+ inFlight = null;
874
+ }
875
+
876
+ return {
877
+ isEnabled,
878
+ isPerTurn: () => switches().perTurn,
879
+ lastTurnAt: () => (lastTurn && Number.isFinite(lastTurn.at) ? lastTurn.at : null),
880
+ waitTurnSettled,
881
+ refresh,
882
+ stateValue,
883
+ applyBudget,
884
+ budgetCents,
885
+ onSessionEvent,
886
+ dispose,
887
+ state,
888
+ readOnly
889
+ };
890
+ }
891
+
892
+ // ---------------------------------------------------------------------------
893
+ // 费用统计路由
894
+ // ---------------------------------------------------------------------------
895
+
896
+ function makeCostStateHandler(ctx, service) {
897
+ return async function handleCostState(req, res) {
898
+ if (req.method !== "GET") {
899
+ drainRequest(req);
900
+ sendMethodNotAllowed(res, "GET");
901
+ return;
902
+ }
903
+ if (!isTrusted(req, ctx.webServer)) {
904
+ drainRequest(req);
905
+ sendForbidden(res);
906
+ return;
907
+ }
908
+ try {
909
+ const url = new URL(req.url || "/", "http://x");
910
+ const force = url.searchParams.get("refresh") === "1";
911
+ // wait=<lastTurn.at>:长轮询挂起,结算完成立即返回(上限 10s,短于客户端 15s 超时)。
912
+ const waitRaw = url.searchParams.get("wait");
913
+ const waitAt = waitRaw === null || waitRaw === "" ? null : Number(waitRaw);
914
+ if (service.isEnabled()) {
915
+ if (force) await service.refresh(true);
916
+ else service.refresh(false).catch(() => {});
917
+ }
918
+ if (!force && Number.isFinite(waitAt) && service.isPerTurn()) {
919
+ const lastAt = service.lastTurnAt();
920
+ if (lastAt === null || lastAt === waitAt) await service.waitTurnSettled(COST_SETTLE_WAIT_MS);
921
+ }
922
+ if (res.destroyed) return;
923
+ sendJson(res, 200, { ok: true, value: await service.stateValue() });
924
+ } catch (err) {
925
+ if (typeof ctx.logger?.warn === "function") {
926
+ ctx.logger.warn(`[dsh-message-actions] cost state failed: ${err instanceof Error ? err.message : String(err)}`);
927
+ }
928
+ sendError(res, 500, "INTERNAL");
929
+ }
930
+ };
931
+ }
932
+
933
+ // ---------------------------------------------------------------------------
934
+ // 会话统计:读真实会话日志(复用官方 sessionQuery,不新建采集器)
935
+ // ---------------------------------------------------------------------------
936
+
937
+ const STATS_ROUTE = "/dsh-message-actions/stats";
938
+ const STATS_BUDGET_ROUTE = "/dsh-message-actions/stats/budget";
939
+ /** 同一会话日志的折叠结果缓存 4s,避免每次刷新都重读大文件。 */
940
+ const STATS_FOLD_TTL_MS = 4000;
941
+ /** 会话表最多返回 100 行,避免大型工作区一次传输过多数据。 */
942
+ const STATS_SESSION_ROWS = 100;
943
+ /** 折叠缓存上限:超出后丢弃最早插入的一项。 */
944
+ const STATS_FOLD_CACHE_MAX = 300;
945
+
946
+ function sessionQueryOf(ctx) {
947
+ try {
948
+ const service = ctx.get("sessionQuery");
949
+ if (service && typeof service.listSessions === "function" && typeof service.readSession === "function") {
950
+ return service;
951
+ }
952
+ } catch {
953
+ /* 宿主未提供该服务 */
954
+ }
955
+ return null;
956
+ }
957
+
958
+ /**
959
+ * 会话统计服务:枚举会话、按 revision 折叠日志,产出与费用卡片同一价目口径的
960
+ * token / 成本 / 时间线 / 会话表。数据源只有官方日志,不另建采集器。
961
+ */
962
+ function createStatsService(ctx, cost, config) {
963
+ const folds = new Map();
964
+ const warn = (message) => {
965
+ if (typeof ctx.logger?.warn === "function") ctx.logger.warn(`[dsh-message-actions] ${message}`);
966
+ };
967
+
968
+ async function revisionOf(sessionId) {
969
+ try {
970
+ const store = ctx.get("sessionPersistence");
971
+ if (!store || typeof store.stat !== "function") return undefined;
972
+ const snapshot = await store.stat(sessionId);
973
+ if (snapshot === undefined) return "missing";
974
+ return String(snapshot.revision ?? `${snapshot.eventCount ?? ""}:${snapshot.sizeBytes ?? ""}`);
975
+ } catch {
976
+ return undefined;
977
+ }
978
+ }
979
+
980
+ async function foldFor(record) {
981
+ const id = record && record.header && typeof record.header.id === "string" ? record.header.id : "";
982
+ if (!id) return null;
983
+ const query = sessionQueryOf(ctx);
984
+ if (!query) return null;
985
+ const cached = folds.get(id);
986
+ const now = Date.now();
987
+ if (cached !== undefined && now - cached.at < STATS_FOLD_TTL_MS) return cached.fold;
988
+ const revision = await revisionOf(id);
989
+ if (cached !== undefined && revision !== undefined && cached.revision === revision) {
990
+ cached.at = now;
991
+ return cached.fold;
992
+ }
993
+ let snapshot;
994
+ try {
995
+ snapshot = await query.readSession(id);
996
+ } catch (err) {
997
+ warn(`could not read session "${id}": ${err instanceof Error ? err.message : String(err)}`);
998
+ return cached !== undefined ? cached.fold : null;
999
+ }
1000
+ const fold = foldSessionStats(Array.isArray(snapshot && snapshot.events) ? snapshot.events : []);
1001
+ if (folds.size >= STATS_FOLD_CACHE_MAX && !folds.has(id)) {
1002
+ const oldest = folds.keys().next();
1003
+ if (!oldest.done) folds.delete(oldest.value);
1004
+ }
1005
+ folds.set(id, { revision, at: now, fold });
1006
+ return fold;
1007
+ }
1008
+
1009
+ function runningSet() {
1010
+ const running = new Set();
1011
+ try {
1012
+ const agents = ctx.get("agents");
1013
+ if (agents && typeof agents.list === "function") {
1014
+ for (const agent of agents.list()) {
1015
+ if (!agent || agent.status !== "running") continue;
1016
+ const id = agent.session && typeof agent.session.id === "string" ? agent.session.id : agent.id;
1017
+ if (typeof id === "string") running.add(id);
1018
+ }
1019
+ }
1020
+ } catch {
1021
+ /* 运行状态只是装饰列 */
1022
+ }
1023
+ return running;
1024
+ }
1025
+
1026
+ async function buildPayload() {
1027
+ const now = Date.now();
1028
+ const query = sessionQueryOf(ctx);
1029
+ let records = [];
1030
+ if (query) {
1031
+ try {
1032
+ records = await query.listSessions();
1033
+ } catch (err) {
1034
+ warn(`session list failed: ${err instanceof Error ? err.message : String(err)}`);
1035
+ }
1036
+ }
1037
+ const running = runningSet();
1038
+ const rows = [];
1039
+ const points = [];
1040
+ for (const record of Array.isArray(records) ? records : []) {
1041
+ const fold = await foldFor(record);
1042
+ if (fold === null) continue;
1043
+ const id = record && record.header && typeof record.header.id === "string" ? record.header.id : "";
1044
+ rows.push(statsSessionRow(record && record.header, fold, {
1045
+ running: running.has(id),
1046
+ live: record && record.live === true
1047
+ }));
1048
+ for (const point of fold.points) points.push(point);
1049
+ }
1050
+ rows.sort((left, right) => right.tokens.total - left.tokens.total || right.lastActiveAt - left.lastActiveAt);
1051
+ const summary = statsSummary(rows);
1052
+ const budget = statsBudget(summary.costMicros, cost.budgetCents());
1053
+ // 余额口径(费用卡片):只作对照,不参与估算成本与预算。
1054
+ let ledger = null;
1055
+ try {
1056
+ const value = await cost.stateValue();
1057
+ const b = (value.balance && typeof value.balance === "object") ? value.balance : {};
1058
+ const rechargeCents = Number.isFinite(b.rechargeCents) ? b.rechargeCents : null;
1059
+ const bonusCents = Number.isFinite(b.bonusCents) ? b.bonusCents : null;
1060
+ const totalCents = Number.isFinite(b.totalCents) ? b.totalCents : null;
1061
+ // 与侧边栏费用卡片完全同一口径:直接展示官方「充值余额」(不含赠金)。
1062
+ const balanceCents = rechargeCents !== null ? rechargeCents : totalCents;
1063
+ ledger = {
1064
+ balanceCents,
1065
+ rechargeCents,
1066
+ bonusCents,
1067
+ totalCents,
1068
+ dailyCents: Number.isFinite(value.dailyCents) ? value.dailyCents : 0,
1069
+ observedSpendCents: Number.isFinite(value.observedSpendCents) ? value.observedSpendCents : 0,
1070
+ lastTurnMicros: value.lastTurn && Number.isFinite(value.lastTurn.costMicros) ? value.lastTurn.costMicros : null
1071
+ };
1072
+ } catch {
1073
+ ledger = null;
1074
+ }
1075
+ return {
1076
+ available: query !== null,
1077
+ generatedAt: now,
1078
+ currency: "CNY",
1079
+ currencySymbol: "¥",
1080
+ budget,
1081
+ totals: { ...summary, costCents: Math.round(summary.costMicros / 10000) },
1082
+ series: statsTimeline(points, now),
1083
+ sessions: rows.slice(0, STATS_SESSION_ROWS),
1084
+ sessionsTotal: rows.length,
1085
+ truncated: rows.length > STATS_SESSION_ROWS,
1086
+ ledger
1087
+ };
1088
+ }
1089
+
1090
+ /** 同一时刻只跑一次折叠:刷新按钮与定时轮询撞车时复用同一个 Promise。 */
1091
+ let inflight = null;
1092
+ function payload() {
1093
+ if (inflight !== null) return inflight;
1094
+ const task = buildPayload();
1095
+ inflight = task;
1096
+ task
1097
+ .finally(() => {
1098
+ if (inflight === task) inflight = null;
1099
+ })
1100
+ .catch(() => {});
1101
+ return task;
1102
+ }
1103
+
1104
+ return { payload };
1105
+ }
1106
+
1107
+ function makeStatsHandler(ctx, service) {
1108
+ return async function handleStats(req, res) {
1109
+ if (req.method !== "GET") {
1110
+ drainRequest(req);
1111
+ sendMethodNotAllowed(res, "GET");
1112
+ return;
1113
+ }
1114
+ if (!isTrusted(req, ctx.webServer)) {
1115
+ drainRequest(req);
1116
+ sendForbidden(res);
1117
+ return;
1118
+ }
1119
+ try {
1120
+ sendJson(res, 200, { ok: true, value: await service.payload() });
1121
+ } catch (err) {
1122
+ if (typeof ctx.logger?.warn === "function") {
1123
+ ctx.logger.warn(`[dsh-message-actions] stats failed: ${err instanceof Error ? err.message : String(err)}`);
1124
+ }
1125
+ sendError(res, 500, "INTERNAL");
1126
+ }
1127
+ };
1128
+ }
1129
+
1130
+ function makeStatsBudgetHandler(ctx, cost) {
1131
+ return async function handleStatsBudget(req, res) {
1132
+ if (req.method !== "POST") {
1133
+ drainRequest(req);
1134
+ sendMethodNotAllowed(res, "POST");
1135
+ return;
1136
+ }
1137
+ if (!isTrusted(req, ctx.webServer)) {
1138
+ drainRequest(req);
1139
+ sendForbidden(res);
1140
+ return;
1141
+ }
1142
+ const contentType = (req.headers["content-type"] || "").split(";")[0].trim().toLowerCase();
1143
+ if (contentType !== "application/json") {
1144
+ drainRequest(req);
1145
+ sendBadRequest(res);
1146
+ return;
1147
+ }
1148
+ const body = await readJsonBody(req, res);
1149
+ if (body === null) return;
1150
+ if (!body || typeof body !== "object") {
1151
+ sendBadRequest(res);
1152
+ return;
1153
+ }
1154
+ const amount = validateCorrectionAmount(body.budgetYuan);
1155
+ if (!amount.ok) {
1156
+ sendError(res, 400, "INVALID_AMOUNT");
1157
+ return;
1158
+ }
1159
+ try {
1160
+ const saved = cost.applyBudget(amount.cents);
1161
+ if (!saved.ok) {
1162
+ sendError(res, 500, saved.error);
1163
+ return;
1164
+ }
1165
+ sendJson(res, 200, { ok: true, value: { budgetCents: cost.budgetCents() } });
1166
+ } catch (err) {
1167
+ if (typeof ctx.logger?.warn === "function") {
1168
+ ctx.logger.warn(`[dsh-message-actions] budget save failed: ${err instanceof Error ? err.message : String(err)}`);
1169
+ }
1170
+ sendError(res, 500, "INTERNAL");
1171
+ }
1172
+ };
1173
+ }
1174
+
1175
+ // ---------------------------------------------------------------------------
1176
+ // 插件主体
1177
+ // ---------------------------------------------------------------------------
1178
+
1179
+ function apply(ctx, config) {
1180
+ ctx.effect(
1181
+ () => ctx.webServer.register({
1182
+ kind: "exact",
1183
+ path: "/dsh-message-actions",
1184
+ handler: makeActionHandler(ctx)
1185
+ }),
1186
+ "dsh-message-actions: write route"
1187
+ );
1188
+ ctx.effect(
1189
+ () => ctx.webServer.register({
1190
+ kind: "exact",
1191
+ path: "/dsh-message-actions/messages",
1192
+ handler: makeMessagesHandler(ctx)
1193
+ }),
1194
+ "dsh-message-actions: read route"
1195
+ );
1196
+ ctx.effect(
1197
+ () => ctx.webServer.register({
1198
+ kind: "exact",
1199
+ path: ATTACHMENT_ROUTE,
1200
+ handler: makeAttachmentHandler(ctx)
1201
+ }),
1202
+ "dsh-message-actions: attachment route"
1203
+ );
1204
+
1205
+ // —— 费用统计 ——
1206
+ const cost = createCostService(ctx, config);
1207
+ const stats = createStatsService(ctx, cost, config);
1208
+
1209
+ ctx.effect(
1210
+ () => ctx.webServer.register({
1211
+ kind: "exact",
1212
+ path: "/dsh-message-actions/cost/state",
1213
+ handler: makeCostStateHandler(ctx, cost)
1214
+ }),
1215
+ "dsh-message-actions: cost state route"
1216
+ );
1217
+ // —— 会话统计(数据来自官方会话日志)——
1218
+ ctx.effect(
1219
+ () => ctx.webServer.register({
1220
+ kind: "exact",
1221
+ path: STATS_ROUTE,
1222
+ handler: makeStatsHandler(ctx, stats)
1223
+ }),
1224
+ "dsh-message-actions: session stats route"
1225
+ );
1226
+ ctx.effect(
1227
+ () => ctx.webServer.register({
1228
+ kind: "exact",
1229
+ path: STATS_BUDGET_ROUTE,
1230
+ handler: makeStatsBudgetHandler(ctx, cost)
1231
+ }),
1232
+ "dsh-message-actions: stats budget route"
1233
+ );
1234
+
1235
+ ctx.effect(() => {
1236
+ const offEvent = ctx.on("session/event", (session, event) => cost.onSessionEvent(session, event));
1237
+ // 始终创建定时器,但每次触发都重新读开关:运行中关闭后不再取数,
1238
+ // 重新打开后也无需重启即可恢复(默认开启时行为与旧版一致)。
1239
+ const timer = setInterval(() => {
1240
+ if (!cost.isEnabled()) return;
1241
+ cost.refresh(false).catch(() => {});
1242
+ }, COST_REFRESH_MIN_INTERVAL_MS);
1243
+ if (typeof timer.unref === "function") timer.unref();
1244
+ return () => {
1245
+ if (typeof offEvent === "function") offEvent();
1246
+ clearInterval(timer);
1247
+ cost.dispose();
1248
+ };
1249
+ }, "dsh-message-actions: cost service");
1250
+ }
1251
+
1252
+ export { Config, apply, inject, name };