dsh-message-actions 0.2.1 → 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/client.js +1933 -232
- package/lib/index.js +445 -55
- package/lib/shared.cjs +613 -26
- package/lib/store.cjs +13 -8
- package/package.json +1 -1
- package/LICENSE +0 -21
- package/README.cn.md +0 -250
- package/README.md +0 -250
package/lib/index.js
CHANGED
|
@@ -32,22 +32,29 @@ const {
|
|
|
32
32
|
routeOfMessage,
|
|
33
33
|
routeOfUsage,
|
|
34
34
|
routingOfProvider,
|
|
35
|
+
isBillableRoute,
|
|
35
36
|
costSwitches,
|
|
36
37
|
turnCostOfGroups,
|
|
37
38
|
deriveTurnUsage,
|
|
38
39
|
createTurnBuffer,
|
|
39
40
|
appendTurnEvent,
|
|
40
41
|
observeBalance,
|
|
41
|
-
correctedBalanceCents,
|
|
42
42
|
validateCorrectionAmount,
|
|
43
43
|
pruneDailySpend,
|
|
44
|
-
yuanToCents
|
|
44
|
+
yuanToCents,
|
|
45
|
+
foldSessionStats,
|
|
46
|
+
statsTimeline,
|
|
47
|
+
statsSessionRow,
|
|
48
|
+
statsSummary,
|
|
49
|
+
statsBudget,
|
|
50
|
+
settleSpend
|
|
45
51
|
} = shared;
|
|
46
52
|
|
|
47
53
|
const {
|
|
48
54
|
resolveStatePath,
|
|
49
55
|
loadCostState,
|
|
50
|
-
persistCostState
|
|
56
|
+
persistCostState,
|
|
57
|
+
DEFAULT_BUDGET_CENTS
|
|
51
58
|
} = store;
|
|
52
59
|
|
|
53
60
|
// ---------------------------------------------------------------------------
|
|
@@ -70,6 +77,13 @@ const Config = z.object({
|
|
|
70
77
|
deleteFrom: z.boolean().default(true).volatile(),
|
|
71
78
|
confirm: z.boolean().default(true).volatile(),
|
|
72
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(),
|
|
73
87
|
|
|
74
88
|
// —— 费用统计(新增)——
|
|
75
89
|
usageStats: z.boolean().default(true).volatile(),
|
|
@@ -129,6 +143,126 @@ function newTombstoneId() {
|
|
|
129
143
|
// 路由处理器
|
|
130
144
|
// ---------------------------------------------------------------------------
|
|
131
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
|
+
|
|
132
266
|
function makeActionHandler(ctx) {
|
|
133
267
|
return async function handleAction(req, res) {
|
|
134
268
|
if (req.method !== "POST") {
|
|
@@ -247,7 +381,8 @@ function makeActionHandler(ctx) {
|
|
|
247
381
|
removed: plan.removed,
|
|
248
382
|
turn: plan.turn,
|
|
249
383
|
step: plan.step,
|
|
250
|
-
refillText: plan.refillText
|
|
384
|
+
refillText: plan.refillText,
|
|
385
|
+
attachments: plan.attachments || []
|
|
251
386
|
}
|
|
252
387
|
});
|
|
253
388
|
};
|
|
@@ -348,6 +483,8 @@ function makeMessagesHandler(ctx) {
|
|
|
348
483
|
// ---------------------------------------------------------------------------
|
|
349
484
|
|
|
350
485
|
const COST_REFRESH_MIN_INTERVAL_MS = 60 * 1000;
|
|
486
|
+
// 结算推送:客户端长轮询最长等待时长,必须小于客户端 15s 请求超时。
|
|
487
|
+
const COST_SETTLE_WAIT_MS = 10 * 1000;
|
|
351
488
|
const COST_BALANCE_TIMEOUT_MS = 10 * 1000;
|
|
352
489
|
const ROUTING_TIMEOUT_MS = 3 * 1000;
|
|
353
490
|
const ROUTING_CACHE_MS = 5 * 1000;
|
|
@@ -377,14 +514,16 @@ function eventTime(event) {
|
|
|
377
514
|
return Date.now();
|
|
378
515
|
}
|
|
379
516
|
|
|
380
|
-
/** 钱包列表按 CNY 求和(其他币种忽略,不换算)。
|
|
517
|
+
/** 钱包列表按 CNY 求和(其他币种忽略,不换算)。
|
|
518
|
+
* 正金额按官方「账号与余额」的规则截断至分:API 原始字符串可能带三位以上小数,
|
|
519
|
+
* 四舍五入会把 5.999… 显示成 6.00,与官方页面的 5.99 差一分。 */
|
|
381
520
|
function sumCnyWallets(wallets) {
|
|
382
521
|
if (!Array.isArray(wallets)) return 0;
|
|
383
522
|
let cents = 0;
|
|
384
523
|
for (const wallet of wallets) {
|
|
385
524
|
if (!wallet || typeof wallet !== "object") continue;
|
|
386
525
|
if (wallet.currency !== "CNY") continue;
|
|
387
|
-
const value = yuanToCents(wallet.balance);
|
|
526
|
+
const value = yuanToCents(wallet.balance, "truncate");
|
|
388
527
|
if (value !== null) cents += value;
|
|
389
528
|
}
|
|
390
529
|
return cents;
|
|
@@ -450,6 +589,31 @@ function createCostService(ctx, config) {
|
|
|
450
589
|
const buffers = new Map();
|
|
451
590
|
const MAX_BUFFERS = 200;
|
|
452
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
|
+
}
|
|
453
617
|
let inFlight = null;
|
|
454
618
|
let lastFetchFailed = false;
|
|
455
619
|
let lastMessageProvider;
|
|
@@ -575,30 +739,24 @@ function createCostService(ctx, config) {
|
|
|
575
739
|
}
|
|
576
740
|
|
|
577
741
|
/**
|
|
578
|
-
*
|
|
579
|
-
*
|
|
742
|
+
* 保存预算(分)。落盘失败时回滚内存值:
|
|
743
|
+
* 不把未落盘的设置伪装成成功。
|
|
580
744
|
*/
|
|
581
|
-
function
|
|
582
|
-
const previous =
|
|
583
|
-
|
|
584
|
-
debit: state.correctionDebitCents,
|
|
585
|
-
pending: state.pendingAdjustmentCents,
|
|
586
|
-
pendingAt: state.pendingAdjustmentAt
|
|
587
|
-
};
|
|
588
|
-
state.correctionCreditCents = creditCents;
|
|
589
|
-
state.correctionDebitCents = debitCents;
|
|
590
|
-
state.pendingAdjustmentCents = 0;
|
|
591
|
-
state.pendingAdjustmentAt = 0;
|
|
745
|
+
function applyBudget(cents) {
|
|
746
|
+
const previous = state.budgetCents;
|
|
747
|
+
state.budgetCents = Math.max(0, Math.round(Number.isFinite(cents) ? cents : 0));
|
|
592
748
|
const saved = persist();
|
|
593
|
-
if (!saved.ok)
|
|
594
|
-
state.correctionCreditCents = previous.credit;
|
|
595
|
-
state.correctionDebitCents = previous.debit;
|
|
596
|
-
state.pendingAdjustmentCents = previous.pending;
|
|
597
|
-
state.pendingAdjustmentAt = previous.pendingAt;
|
|
598
|
-
}
|
|
749
|
+
if (!saved.ok) state.budgetCents = previous;
|
|
599
750
|
return saved;
|
|
600
751
|
}
|
|
601
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
|
+
|
|
602
760
|
async function stateValue() {
|
|
603
761
|
const now = Date.now();
|
|
604
762
|
const routing = (await routingInfo()).routing;
|
|
@@ -621,19 +779,7 @@ function createCostService(ctx, config) {
|
|
|
621
779
|
refreshing: inFlight !== null
|
|
622
780
|
},
|
|
623
781
|
dailyCents: state.dailySpendCents[beijingDateKey(now)] || 0,
|
|
624
|
-
|
|
625
|
-
account: {
|
|
626
|
-
baselineCents: state.baselineBalanceCents,
|
|
627
|
-
observedSpendCents: state.observedSpendTotalCents,
|
|
628
|
-
creditCents: state.correctionCreditCents,
|
|
629
|
-
debitCents: state.correctionDebitCents,
|
|
630
|
-
correctedBalanceCents: correctedBalanceCents({
|
|
631
|
-
baselineCents: state.baselineBalanceCents,
|
|
632
|
-
observedSpendCents: state.observedSpendTotalCents,
|
|
633
|
-
creditCents: state.correctionCreditCents,
|
|
634
|
-
debitCents: state.correctionDebitCents
|
|
635
|
-
})
|
|
636
|
-
},
|
|
782
|
+
observedSpendCents: state.observedSpendTotalCents,
|
|
637
783
|
period: period.period,
|
|
638
784
|
nextChangeAt: period.nextChangeAt,
|
|
639
785
|
lastTurn: switches().perTurn ? lastTurn : null
|
|
@@ -664,9 +810,9 @@ function createCostService(ctx, config) {
|
|
|
664
810
|
}
|
|
665
811
|
|
|
666
812
|
if (!switches().perTurn) {
|
|
667
|
-
// 运行中关闭「单次」后不再保留旧的 lastTurn
|
|
813
|
+
// 运行中关闭「单次」后不再保留旧的 lastTurn,避免重新开启时闪回过期金额;
|
|
814
|
+
// 但当日用量仍按结算累加(统计表与费用卡片共用这一份数字)。
|
|
668
815
|
lastTurn = null;
|
|
669
|
-
return;
|
|
670
816
|
}
|
|
671
817
|
if (type === "turn/start") {
|
|
672
818
|
// 防御性上限:会话中途异常结束(没有 turn/end)时不让缓冲无限增长。
|
|
@@ -692,15 +838,34 @@ function createCostService(ctx, config) {
|
|
|
692
838
|
if (!usage) return;
|
|
693
839
|
const at = Number.isFinite(usage.at) ? usage.at : buffer.at;
|
|
694
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;
|
|
695
859
|
lastTurn = {
|
|
696
860
|
at,
|
|
697
|
-
endedAt
|
|
861
|
+
endedAt,
|
|
698
862
|
provider: usage.provider,
|
|
699
863
|
models: usage.models,
|
|
700
864
|
tokens: usage.tokens,
|
|
701
|
-
costMicros
|
|
702
|
-
turn
|
|
865
|
+
costMicros,
|
|
866
|
+
turn
|
|
703
867
|
};
|
|
868
|
+
notifyTurnSettled();
|
|
704
869
|
}
|
|
705
870
|
|
|
706
871
|
function dispose() {
|
|
@@ -711,9 +876,12 @@ function createCostService(ctx, config) {
|
|
|
711
876
|
return {
|
|
712
877
|
isEnabled,
|
|
713
878
|
isPerTurn: () => switches().perTurn,
|
|
879
|
+
lastTurnAt: () => (lastTurn && Number.isFinite(lastTurn.at) ? lastTurn.at : null),
|
|
880
|
+
waitTurnSettled,
|
|
714
881
|
refresh,
|
|
715
882
|
stateValue,
|
|
716
|
-
|
|
883
|
+
applyBudget,
|
|
884
|
+
budgetCents,
|
|
717
885
|
onSessionEvent,
|
|
718
886
|
dispose,
|
|
719
887
|
state,
|
|
@@ -740,10 +908,18 @@ function makeCostStateHandler(ctx, service) {
|
|
|
740
908
|
try {
|
|
741
909
|
const url = new URL(req.url || "/", "http://x");
|
|
742
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);
|
|
743
914
|
if (service.isEnabled()) {
|
|
744
915
|
if (force) await service.refresh(true);
|
|
745
916
|
else service.refresh(false).catch(() => {});
|
|
746
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;
|
|
747
923
|
sendJson(res, 200, { ok: true, value: await service.stateValue() });
|
|
748
924
|
} catch (err) {
|
|
749
925
|
if (typeof ctx.logger?.warn === "function") {
|
|
@@ -754,8 +930,205 @@ function makeCostStateHandler(ctx, service) {
|
|
|
754
930
|
};
|
|
755
931
|
}
|
|
756
932
|
|
|
757
|
-
|
|
758
|
-
|
|
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) {
|
|
759
1132
|
if (req.method !== "POST") {
|
|
760
1133
|
drainRequest(req);
|
|
761
1134
|
sendMethodNotAllowed(res, "POST");
|
|
@@ -778,22 +1151,21 @@ function makeCostCorrectionHandler(ctx, service) {
|
|
|
778
1151
|
sendBadRequest(res);
|
|
779
1152
|
return;
|
|
780
1153
|
}
|
|
781
|
-
const
|
|
782
|
-
|
|
783
|
-
if (!credit.ok || !debit.ok) {
|
|
1154
|
+
const amount = validateCorrectionAmount(body.budgetYuan);
|
|
1155
|
+
if (!amount.ok) {
|
|
784
1156
|
sendError(res, 400, "INVALID_AMOUNT");
|
|
785
1157
|
return;
|
|
786
1158
|
}
|
|
787
1159
|
try {
|
|
788
|
-
const saved =
|
|
1160
|
+
const saved = cost.applyBudget(amount.cents);
|
|
789
1161
|
if (!saved.ok) {
|
|
790
1162
|
sendError(res, 500, saved.error);
|
|
791
1163
|
return;
|
|
792
1164
|
}
|
|
793
|
-
sendJson(res, 200, { ok: true, value:
|
|
1165
|
+
sendJson(res, 200, { ok: true, value: { budgetCents: cost.budgetCents() } });
|
|
794
1166
|
} catch (err) {
|
|
795
1167
|
if (typeof ctx.logger?.warn === "function") {
|
|
796
|
-
ctx.logger.warn(`[dsh-message-actions]
|
|
1168
|
+
ctx.logger.warn(`[dsh-message-actions] budget save failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
797
1169
|
}
|
|
798
1170
|
sendError(res, 500, "INTERNAL");
|
|
799
1171
|
}
|
|
@@ -821,9 +1193,18 @@ function apply(ctx, config) {
|
|
|
821
1193
|
}),
|
|
822
1194
|
"dsh-message-actions: read route"
|
|
823
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
|
+
);
|
|
824
1204
|
|
|
825
1205
|
// —— 费用统计 ——
|
|
826
1206
|
const cost = createCostService(ctx, config);
|
|
1207
|
+
const stats = createStatsService(ctx, cost, config);
|
|
827
1208
|
|
|
828
1209
|
ctx.effect(
|
|
829
1210
|
() => ctx.webServer.register({
|
|
@@ -833,13 +1214,22 @@ function apply(ctx, config) {
|
|
|
833
1214
|
}),
|
|
834
1215
|
"dsh-message-actions: cost state route"
|
|
835
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
|
+
);
|
|
836
1226
|
ctx.effect(
|
|
837
1227
|
() => ctx.webServer.register({
|
|
838
1228
|
kind: "exact",
|
|
839
|
-
path:
|
|
840
|
-
handler:
|
|
1229
|
+
path: STATS_BUDGET_ROUTE,
|
|
1230
|
+
handler: makeStatsBudgetHandler(ctx, cost)
|
|
841
1231
|
}),
|
|
842
|
-
"dsh-message-actions:
|
|
1232
|
+
"dsh-message-actions: stats budget route"
|
|
843
1233
|
);
|
|
844
1234
|
|
|
845
1235
|
ctx.effect(() => {
|