dsh-message-actions 0.2.3 → 0.2.8
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/README.md +104 -244
- package/icon.svg +6 -1
- package/lib/client.js +7307 -4483
- package/lib/http.cjs +37 -1
- package/lib/index.js +625 -83
- package/lib/session-manager.mjs +1164 -0
- package/lib/sessions.cjs +210 -0
- package/lib/shared.cjs +2873 -2357
- package/lib/store.cjs +288 -265
- package/locale/en.json +2 -2
- package/locale/zh.json +2 -2
- package/package.json +5 -2
- package/README.cn.md +0 -289
package/lib/index.js
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
|
-
import { randomUUID } from "node:crypto";
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
2
3
|
import z from "@deepseek-ai/schemastery";
|
|
3
4
|
import shared from "./shared.cjs";
|
|
4
5
|
import store from "./store.cjs";
|
|
5
6
|
import http from "./http.cjs";
|
|
7
|
+
import sessionsPure from "./sessions.cjs";
|
|
8
|
+
import { createSessionManager } from "./session-manager.mjs";
|
|
6
9
|
|
|
7
10
|
const {
|
|
8
11
|
sendJson,
|
|
@@ -11,7 +14,8 @@ const {
|
|
|
11
14
|
sendBadRequest,
|
|
12
15
|
sendForbidden,
|
|
13
16
|
sendMethodNotAllowed,
|
|
14
|
-
readJsonBody
|
|
17
|
+
readJsonBody,
|
|
18
|
+
guardedHandler
|
|
15
19
|
} = http;
|
|
16
20
|
|
|
17
21
|
const {
|
|
@@ -24,6 +28,7 @@ const {
|
|
|
24
28
|
messageIdOf,
|
|
25
29
|
messagesSummaryOf,
|
|
26
30
|
isTrustedRequest,
|
|
31
|
+
attachmentMediaType,
|
|
27
32
|
statusCodeOf,
|
|
28
33
|
isBusyError,
|
|
29
34
|
beijingDateKey,
|
|
@@ -32,9 +37,13 @@ const {
|
|
|
32
37
|
routeOfMessage,
|
|
33
38
|
routeOfUsage,
|
|
34
39
|
routingOfProvider,
|
|
35
|
-
|
|
40
|
+
classifyRoute,
|
|
41
|
+
priceEntryFor,
|
|
42
|
+
costOfGroups,
|
|
43
|
+
normalizeBillingOverrides,
|
|
44
|
+
normalizePriceConfig,
|
|
45
|
+
hostOfBaseUrl,
|
|
36
46
|
costSwitches,
|
|
37
|
-
turnCostOfGroups,
|
|
38
47
|
deriveTurnUsage,
|
|
39
48
|
createTurnBuffer,
|
|
40
49
|
appendTurnEvent,
|
|
@@ -63,6 +72,9 @@ const {
|
|
|
63
72
|
|
|
64
73
|
const name = "dsh-message-actions";
|
|
65
74
|
|
|
75
|
+
/** 解析相对请求 URL 的占位基址;只用于 new URL,不发起任何网络请求。 */
|
|
76
|
+
const URL_PARSE_BASE = "http://localhost";
|
|
77
|
+
|
|
66
78
|
const inject = ["webServer", "sessions", "agents"];
|
|
67
79
|
|
|
68
80
|
/**
|
|
@@ -75,6 +87,8 @@ const Config = z.object({
|
|
|
75
87
|
export: z.boolean().default(true).volatile(),
|
|
76
88
|
delete: z.boolean().default(true).volatile(),
|
|
77
89
|
deleteFrom: z.boolean().default(true).volatile(),
|
|
90
|
+
// 会话管理里的「删除会话」(删除到回收站 / 彻底清理)总开关。
|
|
91
|
+
sessionsDelete: z.boolean().default(true).volatile(),
|
|
78
92
|
confirm: z.boolean().default(true).volatile(),
|
|
79
93
|
stats: z.boolean().default(true).volatile(),
|
|
80
94
|
// 0.2.2 起「完成提示音」不再有独立开关:由 soundTone 的「off」表示关闭。
|
|
@@ -183,7 +197,7 @@ function makeAttachmentHandler(ctx) {
|
|
|
183
197
|
}
|
|
184
198
|
let query;
|
|
185
199
|
try {
|
|
186
|
-
query = new URL(req.url,
|
|
200
|
+
query = new URL(req.url, URL_PARSE_BASE).searchParams;
|
|
187
201
|
} catch {
|
|
188
202
|
sendBadRequest(res);
|
|
189
203
|
return;
|
|
@@ -214,13 +228,12 @@ function makeAttachmentHandler(ctx) {
|
|
|
214
228
|
|
|
215
229
|
const name = (found.ref && found.ref.name) || (found.kind === "image" ? "image" : "file");
|
|
216
230
|
const headers = {
|
|
217
|
-
"content-type": (found.ref && found.ref.mediaType
|
|
231
|
+
"content-type": attachmentMediaType(found.ref && found.ref.mediaType, found.kind),
|
|
218
232
|
"cache-control": "no-store",
|
|
219
233
|
"x-content-type-options": "nosniff",
|
|
220
234
|
"cross-origin-resource-policy": "same-origin",
|
|
221
235
|
"content-disposition": "attachment; filename*=UTF-8''" + encodeURIComponent(name)
|
|
222
236
|
};
|
|
223
|
-
if (Number.isSafeInteger(found.ref.bytes)) headers["content-length"] = found.ref.bytes;
|
|
224
237
|
|
|
225
238
|
try {
|
|
226
239
|
if (found.kind === "image") {
|
|
@@ -388,7 +401,7 @@ function makeActionHandler(ctx) {
|
|
|
388
401
|
};
|
|
389
402
|
}
|
|
390
403
|
|
|
391
|
-
function makeMessagesHandler(ctx) {
|
|
404
|
+
function makeMessagesHandler(ctx, cost) {
|
|
392
405
|
return async function handleMessages(req, res) {
|
|
393
406
|
if (req.method !== "GET") {
|
|
394
407
|
drainRequest(req);
|
|
@@ -400,7 +413,7 @@ function makeMessagesHandler(ctx) {
|
|
|
400
413
|
sendForbidden(res);
|
|
401
414
|
return;
|
|
402
415
|
}
|
|
403
|
-
const url = new URL(req.url || "/",
|
|
416
|
+
const url = new URL(req.url || "/", URL_PARSE_BASE);
|
|
404
417
|
const sessionId = url.searchParams.get("sessionId");
|
|
405
418
|
if (!sessionId) {
|
|
406
419
|
sendBadRequest(res);
|
|
@@ -473,7 +486,10 @@ function makeMessagesHandler(ctx) {
|
|
|
473
486
|
// 系统 / 开发者提示词与工具结果正文从不进入摘要(预览也只覆盖问 / 答)。
|
|
474
487
|
sendJson(res, 200, {
|
|
475
488
|
ok: true,
|
|
476
|
-
value: messagesSummaryOf(events, nodes, turns,
|
|
489
|
+
value: messagesSummaryOf(events, nodes, turns, Object.assign(
|
|
490
|
+
{ filter, since, previewLimit: 200 },
|
|
491
|
+
cost && typeof cost.classifyOptions === "function" ? cost.classifyOptions() : {}
|
|
492
|
+
))
|
|
477
493
|
});
|
|
478
494
|
};
|
|
479
495
|
}
|
|
@@ -488,15 +504,20 @@ const COST_SETTLE_WAIT_MS = 10 * 1000;
|
|
|
488
504
|
const COST_BALANCE_TIMEOUT_MS = 10 * 1000;
|
|
489
505
|
const ROUTING_TIMEOUT_MS = 3 * 1000;
|
|
490
506
|
const ROUTING_CACHE_MS = 5 * 1000;
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
507
|
+
// provider → baseURL 探测:缓存 60s;探测失败只用旧缓存,不阻塞事件结算。
|
|
508
|
+
const ENDPOINT_CACHE_MS = 60 * 1000;
|
|
509
|
+
const ENDPOINT_TIMEOUT_MS = 2 * 1000;
|
|
510
|
+
/** getBalance 的客户端元数据:时区固定北京时间,不随本机漂移。
|
|
511
|
+
* version 只作为遥测字段,宿主没注入时宁可不传,也不写死一个过期版本号。 */
|
|
494
512
|
function accountClientMetadata() {
|
|
495
513
|
const env = typeof process !== "undefined" && process.env ? process.env : {};
|
|
496
|
-
const
|
|
497
|
-
? env.DSH_VERSION
|
|
498
|
-
:
|
|
499
|
-
|
|
514
|
+
const raw = typeof env.DSH_VERSION === "string"
|
|
515
|
+
? env.DSH_VERSION
|
|
516
|
+
: (typeof env.DSH_APP_VERSION === "string" ? env.DSH_APP_VERSION : "");
|
|
517
|
+
const metadata = { locale: "zh-CN", timezoneOffsetSeconds: 8 * 3600 };
|
|
518
|
+
const version = raw.trim();
|
|
519
|
+
if (version !== "") metadata.version = version;
|
|
520
|
+
return metadata;
|
|
500
521
|
}
|
|
501
522
|
|
|
502
523
|
/** 事件时刻:优先数值 time,其次 ISO 字符串,最后宿主收包时刻。 */
|
|
@@ -562,6 +583,64 @@ async function hasApiKey(ctx) {
|
|
|
562
583
|
return typeof env.DEEPSEEK_API_KEY === "string" && env.DEEPSEEK_API_KEY.trim().length > 0;
|
|
563
584
|
}
|
|
564
585
|
|
|
586
|
+
/**
|
|
587
|
+
* 递归收集配置里 `providers.<id>.baseURL`(configEditor 返回的
|
|
588
|
+
* `{ entry, inherited, override }[]`;也兼容其他嵌套形状)。
|
|
589
|
+
*/
|
|
590
|
+
function collectEndpointsFromConfig(node, keyHint, map, depth) {
|
|
591
|
+
if (!node || typeof node !== "object" || depth > 8) return;
|
|
592
|
+
if (Array.isArray(node)) {
|
|
593
|
+
for (const item of node) collectEndpointsFromConfig(item, keyHint, map, depth + 1);
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
596
|
+
const baseUrl = node.baseURL || node.baseUrl;
|
|
597
|
+
if (typeof baseUrl === "string" && baseUrl.trim()) {
|
|
598
|
+
const id = keyHint || node.id || node.name || node.provider;
|
|
599
|
+
if (typeof id === "string" && id.trim()) map.set(id.trim().toLowerCase(), baseUrl.trim());
|
|
600
|
+
}
|
|
601
|
+
for (const [key, value] of Object.entries(node)) {
|
|
602
|
+
collectEndpointsFromConfig(value, key, map, depth + 1);
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/** 从 profile patch YAML 里粗略提取 `providers.<id>.baseURL`(configEditor 不可用时的兜底)。 */
|
|
607
|
+
function collectEndpointsFromPatch(text, map) {
|
|
608
|
+
const lines = String(text || "").split(/\r?\n/);
|
|
609
|
+
let inProviders = false;
|
|
610
|
+
let providersIndent = -1;
|
|
611
|
+
let current = null;
|
|
612
|
+
let providerIndent = -1;
|
|
613
|
+
for (const line of lines) {
|
|
614
|
+
if (!line.trim() || line.trim().startsWith("#")) continue;
|
|
615
|
+
const indent = line.match(/^\s*/)[0].length;
|
|
616
|
+
const content = line.trim();
|
|
617
|
+
if (/^providers:\s*$/.test(content)) {
|
|
618
|
+
inProviders = true;
|
|
619
|
+
providersIndent = indent;
|
|
620
|
+
current = null;
|
|
621
|
+
providerIndent = -1;
|
|
622
|
+
continue;
|
|
623
|
+
}
|
|
624
|
+
if (inProviders && indent <= providersIndent) {
|
|
625
|
+
inProviders = false;
|
|
626
|
+
current = null;
|
|
627
|
+
continue;
|
|
628
|
+
}
|
|
629
|
+
if (!inProviders) continue;
|
|
630
|
+
const keyMatch = /^['"]?([\w.@-]+)['"]?:\s*$/.exec(content);
|
|
631
|
+
if (keyMatch && indent > providersIndent) {
|
|
632
|
+
if (providerIndent === -1) providerIndent = indent;
|
|
633
|
+
if (indent === providerIndent) current = keyMatch[1];
|
|
634
|
+
continue;
|
|
635
|
+
}
|
|
636
|
+
const baseMatch = /^baseURL:\s*(.+?)\s*$/.exec(content);
|
|
637
|
+
if (baseMatch && current) {
|
|
638
|
+
const value = baseMatch[1].replace(/^["']|["']$/g, "");
|
|
639
|
+
if (value) map.set(current.toLowerCase(), value);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
565
644
|
/**
|
|
566
645
|
* 创建费用统计服务。内存状态为唯一读写源,写盘为整份原子替换。
|
|
567
646
|
* @param ctx Cordis 宿主上下文
|
|
@@ -617,8 +696,16 @@ function createCostService(ctx, config) {
|
|
|
617
696
|
let inFlight = null;
|
|
618
697
|
let lastFetchFailed = false;
|
|
619
698
|
let lastMessageProvider;
|
|
699
|
+
let lastMessageModel;
|
|
620
700
|
let lastHeaderProvider;
|
|
701
|
+
let lastHeaderModel;
|
|
621
702
|
let routingCache = { at: 0, value: null };
|
|
703
|
+
// provider → baseURL:只缓存成功探测结果;失败时保留旧值并等待下次重试。
|
|
704
|
+
const endpointCache = { at: 0, lastAttempt: 0, map: new Map(), source: "none", pending: null };
|
|
705
|
+
// 价格表 / 覆盖清单变更时递增,统计折叠缓存据此失效并重算历史。
|
|
706
|
+
let billingRevision = 0;
|
|
707
|
+
// provider → baseURL 变化时递增,避免历史统计沿用旧的本地 / 第三方判定。
|
|
708
|
+
let endpointRevision = 0;
|
|
622
709
|
|
|
623
710
|
const warn = (message) => {
|
|
624
711
|
if (typeof ctx.logger?.warn === "function") ctx.logger.warn(`[dsh-message-actions] ${message}`);
|
|
@@ -635,6 +722,194 @@ function createCostService(ctx, config) {
|
|
|
635
722
|
return persistCostState(statePath, state, readOnly, ctx.logger);
|
|
636
723
|
}
|
|
637
724
|
|
|
725
|
+
/**
|
|
726
|
+
* 探测 provider → baseURL。三级来源(新版优先,逐级回退):
|
|
727
|
+
* 1. `llm.listProviders()`(返回 baseUrl);
|
|
728
|
+
* 2. `configEditor.configuration()`(providers.<id>.baseURL);
|
|
729
|
+
* 3. profile patch YAML 文本(粗解析)。
|
|
730
|
+
* 探测失败不会清空旧缓存,也不会影响按钮注入。
|
|
731
|
+
*/
|
|
732
|
+
async function refreshEndpoints(force) {
|
|
733
|
+
const now = Date.now();
|
|
734
|
+
if (!force && endpointCache.at > 0 && now - endpointCache.at < ENDPOINT_CACHE_MS) {
|
|
735
|
+
return endpointCache;
|
|
736
|
+
}
|
|
737
|
+
let map = new Map();
|
|
738
|
+
let source = "none";
|
|
739
|
+
|
|
740
|
+
try {
|
|
741
|
+
const llm = ctx.get("llm");
|
|
742
|
+
if (llm && typeof llm.listProviders === "function") {
|
|
743
|
+
const list = await withTimeout(Promise.resolve(llm.listProviders()), ENDPOINT_TIMEOUT_MS);
|
|
744
|
+
for (const provider of Array.isArray(list) ? list : []) {
|
|
745
|
+
if (!provider || typeof provider !== "object") continue;
|
|
746
|
+
const id = provider.id || provider.name || provider.provider;
|
|
747
|
+
const baseUrl = provider.baseUrl || provider.baseURL;
|
|
748
|
+
if (typeof id === "string" && typeof baseUrl === "string" && baseUrl.trim()) {
|
|
749
|
+
map.set(id.trim().toLowerCase(), baseUrl.trim());
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
if (map.size > 0) source = "llm";
|
|
753
|
+
}
|
|
754
|
+
} catch {
|
|
755
|
+
/* 旧宿主没有 llm 服务或接口不同:继续下一级 */
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
// 第二级:配置编辑器(补齐 llm 没给出的 provider,不覆盖 llm 的结果)。
|
|
759
|
+
{
|
|
760
|
+
try {
|
|
761
|
+
const editor = ctx.get("configEditor");
|
|
762
|
+
if (editor && typeof editor.configuration === "function") {
|
|
763
|
+
const rows = await withTimeout(Promise.resolve(editor.configuration()), ENDPOINT_TIMEOUT_MS);
|
|
764
|
+
const collected = new Map();
|
|
765
|
+
for (const row of Array.isArray(rows) ? rows : []) {
|
|
766
|
+
collectEndpointsFromConfig(row && row.inherited, "", collected, 0);
|
|
767
|
+
collectEndpointsFromConfig(row && row.override, "", collected, 0);
|
|
768
|
+
}
|
|
769
|
+
let added = 0;
|
|
770
|
+
for (const [key, value] of collected) {
|
|
771
|
+
if (!map.has(key)) {
|
|
772
|
+
map.set(key, value);
|
|
773
|
+
added += 1;
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
if (added > 0) source = source === "none" ? "config-editor" : "llm+config-editor";
|
|
777
|
+
}
|
|
778
|
+
} catch {
|
|
779
|
+
/* 配置服务不可用:继续兜底 */
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
// 第三级:profile patch 文本(最后兜底,同样只补缺失项)。
|
|
784
|
+
{
|
|
785
|
+
try {
|
|
786
|
+
const profile = ctx.get("profileContext");
|
|
787
|
+
const patchPath = profile && typeof profile.patchPath === "string" ? profile.patchPath : "";
|
|
788
|
+
if (patchPath) {
|
|
789
|
+
const text = await fs.promises.readFile(patchPath, "utf8");
|
|
790
|
+
const collected = new Map();
|
|
791
|
+
collectEndpointsFromPatch(text, collected);
|
|
792
|
+
let added = 0;
|
|
793
|
+
for (const [key, value] of collected) {
|
|
794
|
+
if (!map.has(key)) {
|
|
795
|
+
map.set(key, value);
|
|
796
|
+
added += 1;
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
if (added > 0) source = source === "none" ? "profile-patch" : source + "+profile-patch";
|
|
800
|
+
}
|
|
801
|
+
} catch {
|
|
802
|
+
/* 文件读取失败:保持旧缓存 */
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
endpointCache.lastAttempt = Date.now();
|
|
807
|
+
if (map.size === 0) {
|
|
808
|
+
// 上一轮什么都没探测到:不缓存空结果,下次调用立即重试。
|
|
809
|
+
endpointCache.at = 0;
|
|
810
|
+
} else {
|
|
811
|
+
const changed = map.size !== endpointCache.map.size ||
|
|
812
|
+
[...map.entries()].some(([key, value]) => endpointCache.map.get(key) !== value);
|
|
813
|
+
if (changed) endpointRevision += 1;
|
|
814
|
+
endpointCache.at = Date.now();
|
|
815
|
+
endpointCache.map = map;
|
|
816
|
+
endpointCache.source = source;
|
|
817
|
+
}
|
|
818
|
+
return endpointCache;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
/** 非阻塞探测:同一时刻只跑一次;15s 内不重复敲宿主。 */
|
|
822
|
+
function scheduleEndpointRefresh() {
|
|
823
|
+
if (endpointCache.pending) return endpointCache.pending;
|
|
824
|
+
if (endpointCache.lastAttempt > 0 && Date.now() - endpointCache.lastAttempt < 15 * 1000) {
|
|
825
|
+
return Promise.resolve(endpointCache);
|
|
826
|
+
}
|
|
827
|
+
endpointCache.pending = refreshEndpoints(true)
|
|
828
|
+
.catch(() => {})
|
|
829
|
+
.finally(() => {
|
|
830
|
+
endpointCache.pending = null;
|
|
831
|
+
});
|
|
832
|
+
return endpointCache.pending;
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
/** 当前计费配置(覆盖清单 + 第三方价格表)。 */
|
|
836
|
+
function billingConfig() {
|
|
837
|
+
if (!state.billing || typeof state.billing !== "object") {
|
|
838
|
+
state.billing = { overrides: {}, prices: normalizePriceConfig(null), updatedAt: 0 };
|
|
839
|
+
}
|
|
840
|
+
return state.billing;
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
/** 传给 classifyRoute / priceEntryFor 的统一口径。 */
|
|
844
|
+
function classifyOptions() {
|
|
845
|
+
const billing = billingConfig();
|
|
846
|
+
return {
|
|
847
|
+
endpoints: Object.fromEntries(endpointCache.map),
|
|
848
|
+
overrides: normalizeBillingOverrides(billing.overrides),
|
|
849
|
+
prices: normalizePriceConfig(billing.prices)
|
|
850
|
+
};
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
/** 单条路由的分类 + 价目(供费用卡片 / 统计诊断使用)。 */
|
|
854
|
+
function classifyRouteInfo(provider, model) {
|
|
855
|
+
const options = classifyOptions();
|
|
856
|
+
const classification = classifyRoute({ provider, model }, options);
|
|
857
|
+
if (!classification.confirmed) scheduleEndpointRefresh();
|
|
858
|
+
const pricing = priceEntryFor({ provider, model }, Object.assign({}, options, { classification }));
|
|
859
|
+
return {
|
|
860
|
+
kind: classification.kind,
|
|
861
|
+
billable: classification.billable,
|
|
862
|
+
local: classification.local,
|
|
863
|
+
confirmed: classification.confirmed,
|
|
864
|
+
official: classification.official,
|
|
865
|
+
source: classification.source,
|
|
866
|
+
reason: classification.reason,
|
|
867
|
+
baseUrl: classification.baseUrl,
|
|
868
|
+
host: classification.host,
|
|
869
|
+
provider: provider || "",
|
|
870
|
+
model: model || "",
|
|
871
|
+
priceSource: pricing.source,
|
|
872
|
+
priceMatched: pricing.matched
|
|
873
|
+
};
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
/** 保存计费配置(覆盖清单 / 价格表),失败回滚。 */
|
|
877
|
+
function applyBilling(input) {
|
|
878
|
+
const previous = billingConfig();
|
|
879
|
+
const next = {
|
|
880
|
+
overrides: normalizeBillingOverrides(input && input.overrides !== undefined ? input.overrides : previous.overrides),
|
|
881
|
+
prices: normalizePriceConfig(input && input.prices !== undefined ? input.prices : previous.prices),
|
|
882
|
+
updatedAt: Date.now()
|
|
883
|
+
};
|
|
884
|
+
state.billing = next;
|
|
885
|
+
const saved = persist();
|
|
886
|
+
if (!saved.ok) {
|
|
887
|
+
state.billing = previous;
|
|
888
|
+
return saved;
|
|
889
|
+
}
|
|
890
|
+
billingRevision += 1;
|
|
891
|
+
return { ok: true, value: next };
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
/** 诊断信息:当前探测到的 provider → baseURL(不回传凭据)。 */
|
|
895
|
+
function endpointDiagnostics() {
|
|
896
|
+
const options = classifyOptions();
|
|
897
|
+
return [...endpointCache.map.entries()].map(([provider, baseUrl]) => {
|
|
898
|
+
const host = hostOfBaseUrl(baseUrl);
|
|
899
|
+
const classification = classifyRoute({ provider, model: "" }, options);
|
|
900
|
+
const pricing = priceEntryFor({ provider, model: "" }, Object.assign({}, options, { classification }));
|
|
901
|
+
return {
|
|
902
|
+
provider,
|
|
903
|
+
baseUrl,
|
|
904
|
+
host,
|
|
905
|
+
kind: classification.kind,
|
|
906
|
+
local: classification.local,
|
|
907
|
+
billable: classification.billable,
|
|
908
|
+
priceSource: pricing.source
|
|
909
|
+
};
|
|
910
|
+
});
|
|
911
|
+
}
|
|
912
|
+
|
|
638
913
|
async function routingInfo() {
|
|
639
914
|
const now = Date.now();
|
|
640
915
|
if (routingCache.value && now - routingCache.at < ROUTING_CACHE_MS) return routingCache.value;
|
|
@@ -645,7 +920,9 @@ function createCostService(ctx, config) {
|
|
|
645
920
|
routingCache = { at: Date.now(), value };
|
|
646
921
|
return value;
|
|
647
922
|
};
|
|
648
|
-
|
|
923
|
+
// 余额轮询只跟 DeepSeek 账户有关;第三方 / 本地明确不查余额。
|
|
924
|
+
if (mapped === "account" || mapped === "api-key") return finish({ routing: mapped, provider });
|
|
925
|
+
if (mapped === "other") return finish({ routing: "third-party", provider });
|
|
649
926
|
|
|
650
927
|
let hasKey = false;
|
|
651
928
|
try {
|
|
@@ -760,17 +1037,22 @@ function createCostService(ctx, config) {
|
|
|
760
1037
|
async function stateValue() {
|
|
761
1038
|
const now = Date.now();
|
|
762
1039
|
const routing = (await routingInfo()).routing;
|
|
1040
|
+
const provider = lastMessageProvider || lastHeaderProvider;
|
|
1041
|
+
const model = lastMessageModel || lastHeaderModel;
|
|
1042
|
+
// 还没有任何 provider 时不做「第三方 / 来源未确认」判定,避免启动瞬间误报。
|
|
1043
|
+
const route = provider ? classifyRouteInfo(provider, model) : null;
|
|
763
1044
|
let status;
|
|
764
|
-
if (routing === "
|
|
1045
|
+
if (routing === "third-party") status = route && route.local ? "local" : "third-party";
|
|
1046
|
+
else if (routing === "signed-out") status = "signed-out";
|
|
765
1047
|
else if (routing === "api-key") status = "api-key";
|
|
766
1048
|
else if (routing === "unavailable") status = "unavailable";
|
|
767
|
-
else if (routing === "local") status = "local";
|
|
768
1049
|
else status = cache.updatedAt > 0 && !lastFetchFailed ? "ready" : "stale";
|
|
769
1050
|
|
|
770
1051
|
const period = periodInfo(now);
|
|
771
1052
|
return {
|
|
772
1053
|
status,
|
|
773
1054
|
billing: routing,
|
|
1055
|
+
route,
|
|
774
1056
|
balance: {
|
|
775
1057
|
rechargeCents: cache.rechargeCents,
|
|
776
1058
|
bonusCents: cache.bonusCents,
|
|
@@ -799,13 +1081,18 @@ function createCostService(ctx, config) {
|
|
|
799
1081
|
const route = routeOfUsage(data.usage) || routeOfMessage(data.message);
|
|
800
1082
|
if (route) {
|
|
801
1083
|
lastMessageProvider = route.provider;
|
|
1084
|
+
lastMessageModel = route.model;
|
|
802
1085
|
routingCache = { at: 0, value: null };
|
|
1086
|
+
if (!endpointCache.map.has(route.provider.trim().toLowerCase())) scheduleEndpointRefresh();
|
|
803
1087
|
}
|
|
804
1088
|
} else if (type === "request/header") {
|
|
805
|
-
const
|
|
1089
|
+
const config = data.header && data.header.config;
|
|
1090
|
+
const provider = config ? config.provider : undefined;
|
|
806
1091
|
if (typeof provider === "string" && provider.length > 0) {
|
|
807
1092
|
lastHeaderProvider = provider;
|
|
1093
|
+
if (config && typeof config.model === "string" && config.model) lastHeaderModel = config.model;
|
|
808
1094
|
routingCache = { at: 0, value: null };
|
|
1095
|
+
if (!endpointCache.map.has(provider.trim().toLowerCase())) scheduleEndpointRefresh();
|
|
809
1096
|
}
|
|
810
1097
|
}
|
|
811
1098
|
|
|
@@ -839,9 +1126,9 @@ function createCostService(ctx, config) {
|
|
|
839
1126
|
const at = Number.isFinite(usage.at) ? usage.at : buffer.at;
|
|
840
1127
|
const period = periodInfo(at).period;
|
|
841
1128
|
const endedAt = Number.isFinite(usage.endedAt) ? usage.endedAt : eventTime(event);
|
|
842
|
-
//
|
|
843
|
-
const
|
|
844
|
-
const costMicros =
|
|
1129
|
+
// 默认计费,只有确认为本地才免;第三方未配置价格时 token 仍计数、金额不进「日用」。
|
|
1130
|
+
const billing = costOfGroups(usage.groups, period, classifyOptions());
|
|
1131
|
+
const costMicros = billing.micros;
|
|
845
1132
|
const turn = Number.isSafeInteger(usage.turn) ? usage.turn : buffer.turn;
|
|
846
1133
|
|
|
847
1134
|
// 结算即累加:当日用量与「单次」同一时刻更新,余额观测随后只补差额。
|
|
@@ -863,6 +1150,11 @@ function createCostService(ctx, config) {
|
|
|
863
1150
|
models: usage.models,
|
|
864
1151
|
tokens: usage.tokens,
|
|
865
1152
|
costMicros,
|
|
1153
|
+
billableTokens: billing.billableTokens,
|
|
1154
|
+
localTokens: billing.localTokens,
|
|
1155
|
+
unpricedTokens: billing.unpricedTokens,
|
|
1156
|
+
hasUnpriced: billing.hasUnpriced,
|
|
1157
|
+
priceSources: billing.sources,
|
|
866
1158
|
turn
|
|
867
1159
|
};
|
|
868
1160
|
notifyTurnSettled();
|
|
@@ -885,7 +1177,15 @@ function createCostService(ctx, config) {
|
|
|
885
1177
|
onSessionEvent,
|
|
886
1178
|
dispose,
|
|
887
1179
|
state,
|
|
888
|
-
readOnly
|
|
1180
|
+
readOnly,
|
|
1181
|
+
refreshEndpoints,
|
|
1182
|
+
classifyOptions,
|
|
1183
|
+
classifyRouteInfo,
|
|
1184
|
+
billingRevision: () => billingRevision,
|
|
1185
|
+
endpointRevision: () => endpointRevision,
|
|
1186
|
+
applyBilling,
|
|
1187
|
+
endpointDiagnostics,
|
|
1188
|
+
endpointSource: () => endpointCache.source
|
|
889
1189
|
};
|
|
890
1190
|
}
|
|
891
1191
|
|
|
@@ -906,7 +1206,7 @@ function makeCostStateHandler(ctx, service) {
|
|
|
906
1206
|
return;
|
|
907
1207
|
}
|
|
908
1208
|
try {
|
|
909
|
-
const url = new URL(req.url || "/",
|
|
1209
|
+
const url = new URL(req.url || "/", URL_PARSE_BASE);
|
|
910
1210
|
const force = url.searchParams.get("refresh") === "1";
|
|
911
1211
|
// wait=<lastTurn.at>:长轮询挂起,结算完成立即返回(上限 10s,短于客户端 15s 超时)。
|
|
912
1212
|
const waitRaw = url.searchParams.get("wait");
|
|
@@ -936,6 +1236,7 @@ function makeCostStateHandler(ctx, service) {
|
|
|
936
1236
|
|
|
937
1237
|
const STATS_ROUTE = "/dsh-message-actions/stats";
|
|
938
1238
|
const STATS_BUDGET_ROUTE = "/dsh-message-actions/stats/budget";
|
|
1239
|
+
const BILLING_ROUTE = "/dsh-message-actions/billing";
|
|
939
1240
|
/** 同一会话日志的折叠结果缓存 4s,避免每次刷新都重读大文件。 */
|
|
940
1241
|
const STATS_FOLD_TTL_MS = 4000;
|
|
941
1242
|
/** 会话表最多返回 100 行,避免大型工作区一次传输过多数据。 */
|
|
@@ -984,9 +1285,15 @@ function createStatsService(ctx, cost, config) {
|
|
|
984
1285
|
if (!query) return null;
|
|
985
1286
|
const cached = folds.get(id);
|
|
986
1287
|
const now = Date.now();
|
|
987
|
-
|
|
1288
|
+
const billingRevision = cost.billingRevision();
|
|
1289
|
+
const endpointRevision = cost.endpointRevision();
|
|
1290
|
+
const sameBilling = cached !== undefined &&
|
|
1291
|
+
cached.billingRevision === billingRevision && cached.endpointRevision === endpointRevision;
|
|
1292
|
+
if (sameBilling && now - cached.at < STATS_FOLD_TTL_MS) {
|
|
1293
|
+
return cached.fold;
|
|
1294
|
+
}
|
|
988
1295
|
const revision = await revisionOf(id);
|
|
989
|
-
if (
|
|
1296
|
+
if (sameBilling && revision !== undefined && cached.revision === revision) {
|
|
990
1297
|
cached.at = now;
|
|
991
1298
|
return cached.fold;
|
|
992
1299
|
}
|
|
@@ -997,12 +1304,16 @@ function createStatsService(ctx, cost, config) {
|
|
|
997
1304
|
warn(`could not read session "${id}": ${err instanceof Error ? err.message : String(err)}`);
|
|
998
1305
|
return cached !== undefined ? cached.fold : null;
|
|
999
1306
|
}
|
|
1000
|
-
|
|
1307
|
+
// 价格表 / 覆盖清单一变,历史按新口径重算(billingRevision 参与缓存键)。
|
|
1308
|
+
const fold = foldSessionStats(
|
|
1309
|
+
Array.isArray(snapshot && snapshot.events) ? snapshot.events : [],
|
|
1310
|
+
cost.classifyOptions()
|
|
1311
|
+
);
|
|
1001
1312
|
if (folds.size >= STATS_FOLD_CACHE_MAX && !folds.has(id)) {
|
|
1002
1313
|
const oldest = folds.keys().next();
|
|
1003
1314
|
if (!oldest.done) folds.delete(oldest.value);
|
|
1004
1315
|
}
|
|
1005
|
-
folds.set(id, { revision, at: now, fold });
|
|
1316
|
+
folds.set(id, { revision, at: now, fold, billingRevision, endpointRevision });
|
|
1006
1317
|
return fold;
|
|
1007
1318
|
}
|
|
1008
1319
|
|
|
@@ -1025,6 +1336,8 @@ function createStatsService(ctx, cost, config) {
|
|
|
1025
1336
|
|
|
1026
1337
|
async function buildPayload() {
|
|
1027
1338
|
const now = Date.now();
|
|
1339
|
+
// 先刷新 provider → baseURL(失败沿用旧缓存),再折叠历史,避免用空映射误判。
|
|
1340
|
+
await cost.refreshEndpoints(false).catch(() => {});
|
|
1028
1341
|
const query = sessionQueryOf(ctx);
|
|
1029
1342
|
let records = [];
|
|
1030
1343
|
if (query) {
|
|
@@ -1072,6 +1385,7 @@ function createStatsService(ctx, cost, config) {
|
|
|
1072
1385
|
} catch {
|
|
1073
1386
|
ledger = null;
|
|
1074
1387
|
}
|
|
1388
|
+
const billingOptions = cost.classifyOptions();
|
|
1075
1389
|
return {
|
|
1076
1390
|
available: query !== null,
|
|
1077
1391
|
generatedAt: now,
|
|
@@ -1083,7 +1397,33 @@ function createStatsService(ctx, cost, config) {
|
|
|
1083
1397
|
sessions: rows.slice(0, STATS_SESSION_ROWS),
|
|
1084
1398
|
sessionsTotal: rows.length,
|
|
1085
1399
|
truncated: rows.length > STATS_SESSION_ROWS,
|
|
1086
|
-
ledger
|
|
1400
|
+
ledger,
|
|
1401
|
+
billing: {
|
|
1402
|
+
revision: cost.billingRevision(),
|
|
1403
|
+
endpointSource: cost.endpointSource(),
|
|
1404
|
+
endpoints: cost.endpointDiagnostics(),
|
|
1405
|
+
overrides: billingOptions.overrides,
|
|
1406
|
+
prices: billingOptions.prices,
|
|
1407
|
+
officialPrices: Object.keys(PRICE_TABLE).filter((key) => key !== "default")
|
|
1408
|
+
}
|
|
1409
|
+
};
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
/**
|
|
1413
|
+
* 会话列表用的轻量元数据:复用同一份折叠缓存与 revision 判断,
|
|
1414
|
+
* 避免「打开会话管理」再解压一遍全部日志。
|
|
1415
|
+
*/
|
|
1416
|
+
async function sessionMeta(record) {
|
|
1417
|
+
const fold = await foldFor(record);
|
|
1418
|
+
if (!fold) return null;
|
|
1419
|
+
return {
|
|
1420
|
+
model: typeof fold.model === "string" ? fold.model : "",
|
|
1421
|
+
provider: typeof fold.provider === "string" ? fold.provider : "",
|
|
1422
|
+
title: typeof fold.title === "string" ? fold.title : "",
|
|
1423
|
+
messages: Number.isFinite(fold.messages) ? fold.messages : 0,
|
|
1424
|
+
turns: Number.isFinite(fold.turns) ? fold.turns : 0,
|
|
1425
|
+
tokens: fold.tokens && Number.isFinite(fold.tokens.total) ? fold.tokens.total : 0,
|
|
1426
|
+
lastActiveAt: Number.isFinite(fold.lastActiveAt) ? fold.lastActiveAt : 0
|
|
1087
1427
|
};
|
|
1088
1428
|
}
|
|
1089
1429
|
|
|
@@ -1101,7 +1441,7 @@ function createStatsService(ctx, cost, config) {
|
|
|
1101
1441
|
return task;
|
|
1102
1442
|
}
|
|
1103
1443
|
|
|
1104
|
-
return { payload };
|
|
1444
|
+
return { payload, sessionMeta };
|
|
1105
1445
|
}
|
|
1106
1446
|
|
|
1107
1447
|
function makeStatsHandler(ctx, service) {
|
|
@@ -1172,65 +1512,266 @@ function makeStatsBudgetHandler(ctx, cost) {
|
|
|
1172
1512
|
};
|
|
1173
1513
|
}
|
|
1174
1514
|
|
|
1515
|
+
/**
|
|
1516
|
+
* `/dsh-message-actions/billing`:读取 / 保存计费覆盖清单与第三方价格表。
|
|
1517
|
+
* GET 返回 `{ overrides, prices, endpoints, endpointSource, officialPrices }`
|
|
1518
|
+
* POST 接受 `{ overrides?, prices? }`(对象或文本),保存后历史统计立即按新价重算。
|
|
1519
|
+
*/
|
|
1520
|
+
function makeBillingHandler(ctx, cost) {
|
|
1521
|
+
return async function handleBilling(req, res) {
|
|
1522
|
+
if (req.method !== "GET" && req.method !== "POST") {
|
|
1523
|
+
drainRequest(req);
|
|
1524
|
+
sendMethodNotAllowed(res, "GET, POST");
|
|
1525
|
+
return;
|
|
1526
|
+
}
|
|
1527
|
+
if (!isTrusted(req, ctx.webServer)) {
|
|
1528
|
+
drainRequest(req);
|
|
1529
|
+
sendForbidden(res);
|
|
1530
|
+
return;
|
|
1531
|
+
}
|
|
1532
|
+
if (req.method === "GET") {
|
|
1533
|
+
try {
|
|
1534
|
+
await cost.refreshEndpoints(false).catch(() => {});
|
|
1535
|
+
const options = cost.classifyOptions();
|
|
1536
|
+
sendJson(res, 200, {
|
|
1537
|
+
ok: true,
|
|
1538
|
+
value: {
|
|
1539
|
+
overrides: options.overrides,
|
|
1540
|
+
prices: options.prices,
|
|
1541
|
+
endpoints: cost.endpointDiagnostics(),
|
|
1542
|
+
endpointSource: cost.endpointSource(),
|
|
1543
|
+
officialPrices: Object.keys(PRICE_TABLE).filter((key) => key !== "default"),
|
|
1544
|
+
officialTable: PRICE_TABLE
|
|
1545
|
+
}
|
|
1546
|
+
});
|
|
1547
|
+
} catch (err) {
|
|
1548
|
+
if (typeof ctx.logger?.warn === "function") {
|
|
1549
|
+
ctx.logger.warn(`[dsh-message-actions] billing read failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1550
|
+
}
|
|
1551
|
+
sendError(res, 500, "INTERNAL");
|
|
1552
|
+
}
|
|
1553
|
+
return;
|
|
1554
|
+
}
|
|
1555
|
+
const contentType = (req.headers["content-type"] || "").split(";")[0].trim().toLowerCase();
|
|
1556
|
+
if (contentType !== "application/json") {
|
|
1557
|
+
drainRequest(req);
|
|
1558
|
+
sendBadRequest(res);
|
|
1559
|
+
return;
|
|
1560
|
+
}
|
|
1561
|
+
const body = await readJsonBody(req, res);
|
|
1562
|
+
if (body === null) return;
|
|
1563
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
|
1564
|
+
sendBadRequest(res);
|
|
1565
|
+
return;
|
|
1566
|
+
}
|
|
1567
|
+
try {
|
|
1568
|
+
const saved = cost.applyBilling({ overrides: body.overrides, prices: body.prices });
|
|
1569
|
+
if (!saved.ok) {
|
|
1570
|
+
sendError(res, 500, saved.error);
|
|
1571
|
+
return;
|
|
1572
|
+
}
|
|
1573
|
+
const options = cost.classifyOptions();
|
|
1574
|
+
sendJson(res, 200, {
|
|
1575
|
+
ok: true,
|
|
1576
|
+
value: {
|
|
1577
|
+
overrides: options.overrides,
|
|
1578
|
+
prices: options.prices,
|
|
1579
|
+
revision: cost.billingRevision()
|
|
1580
|
+
}
|
|
1581
|
+
});
|
|
1582
|
+
} catch (err) {
|
|
1583
|
+
if (typeof ctx.logger?.warn === "function") {
|
|
1584
|
+
ctx.logger.warn(`[dsh-message-actions] billing save failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1585
|
+
}
|
|
1586
|
+
sendError(res, 500, "INTERNAL");
|
|
1587
|
+
}
|
|
1588
|
+
};
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
// ---------------------------------------------------------------------------
|
|
1592
|
+
// 会话管理路由
|
|
1593
|
+
// ---------------------------------------------------------------------------
|
|
1594
|
+
|
|
1595
|
+
const SESSIONS_ROUTE = "/dsh-message-actions/sessions";
|
|
1596
|
+
const MAX_SESSION_BATCH = 50;
|
|
1597
|
+
/** 彻底清理(不可恢复)的确认口令:输入 OK(大小写不敏感、忽略首尾空格)。 */
|
|
1598
|
+
const SESSION_CONFIRM_CODE = "OK";
|
|
1599
|
+
|
|
1600
|
+
function isSessionConfirm(value) {
|
|
1601
|
+
return typeof value === "string" && value.trim().toUpperCase() === SESSION_CONFIRM_CODE;
|
|
1602
|
+
}
|
|
1603
|
+
|
|
1604
|
+
/** 「删除会话」开关:关闭时宿主拒绝一切删除 / 彻底清理请求。 */
|
|
1605
|
+
function sessionsDeleteEnabled(config) {
|
|
1606
|
+
return !(config && config.sessionsDelete === false);
|
|
1607
|
+
}
|
|
1608
|
+
|
|
1609
|
+
/** 解析去重后的 id 数组;数量、类型或重复项不合法都返回 null。 */
|
|
1610
|
+
function readIdList(body, key) {
|
|
1611
|
+
const list = body ? body[key] : null;
|
|
1612
|
+
if (!Array.isArray(list) || list.length === 0 || list.length > MAX_SESSION_BATCH) return null;
|
|
1613
|
+
const out = [];
|
|
1614
|
+
const seen = new Set();
|
|
1615
|
+
for (const value of list) {
|
|
1616
|
+
if (typeof value !== "string" || value === "" || seen.has(value)) return null;
|
|
1617
|
+
seen.add(value);
|
|
1618
|
+
out.push(value);
|
|
1619
|
+
}
|
|
1620
|
+
return out;
|
|
1621
|
+
}
|
|
1622
|
+
|
|
1623
|
+
function makeSessionsHandler(ctx, sessions, config) {
|
|
1624
|
+
return async function handleSessions(req, res) {
|
|
1625
|
+
if (req.method !== "GET" && req.method !== "POST") {
|
|
1626
|
+
drainRequest(req);
|
|
1627
|
+
sendMethodNotAllowed(res, "GET, POST");
|
|
1628
|
+
return;
|
|
1629
|
+
}
|
|
1630
|
+
if (!isTrusted(req, ctx.webServer)) {
|
|
1631
|
+
drainRequest(req);
|
|
1632
|
+
sendForbidden(res);
|
|
1633
|
+
return;
|
|
1634
|
+
}
|
|
1635
|
+
if (req.method === "GET") {
|
|
1636
|
+
let lean = false;
|
|
1637
|
+
let hiddenOnly = false;
|
|
1638
|
+
try {
|
|
1639
|
+
const query = new URL(req.url || SESSIONS_ROUTE, URL_PARSE_BASE).searchParams;
|
|
1640
|
+
lean = query.get("lean") === "1";
|
|
1641
|
+
// 侧边栏隐藏行只需要 trashedIds / purgedIds,避免轮询时枚举全部日志。
|
|
1642
|
+
hiddenOnly = query.get("hidden") === "1";
|
|
1643
|
+
} catch {
|
|
1644
|
+
lean = false;
|
|
1645
|
+
hiddenOnly = false;
|
|
1646
|
+
}
|
|
1647
|
+
try {
|
|
1648
|
+
sendJson(res, 200, { ok: true, value: await sessions.payload({ lean, hiddenOnly }) });
|
|
1649
|
+
} catch (err) {
|
|
1650
|
+
ctx.logger?.warn?.(`[dsh-message-actions] session list failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1651
|
+
sendError(res, 500, "INTERNAL");
|
|
1652
|
+
}
|
|
1653
|
+
return;
|
|
1654
|
+
}
|
|
1655
|
+
|
|
1656
|
+
const contentType = (req.headers["content-type"] || "").split(";")[0].trim().toLowerCase();
|
|
1657
|
+
if (contentType !== "application/json") {
|
|
1658
|
+
drainRequest(req);
|
|
1659
|
+
sendBadRequest(res);
|
|
1660
|
+
return;
|
|
1661
|
+
}
|
|
1662
|
+
const body = await readJsonBody(req, res);
|
|
1663
|
+
if (body === null) return;
|
|
1664
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
|
1665
|
+
sendBadRequest(res);
|
|
1666
|
+
return;
|
|
1667
|
+
}
|
|
1668
|
+
|
|
1669
|
+
try {
|
|
1670
|
+
// 「删除会话」关闭时,删除到回收站与彻底清理一律拒绝(恢复 / 归档不受影响)。
|
|
1671
|
+
if ((body.action === "delete" || body.action === "purge") && !sessionsDeleteEnabled(config)) {
|
|
1672
|
+
sendError(res, 403, "SESSIONS_DELETE_DISABLED");
|
|
1673
|
+
return;
|
|
1674
|
+
}
|
|
1675
|
+
if (body.action === "delete") {
|
|
1676
|
+
const ids = readIdList(body, "sessionIds");
|
|
1677
|
+
if (!ids || !ids.every(sessionsPure.isSessionId)) {
|
|
1678
|
+
sendBadRequest(res);
|
|
1679
|
+
return;
|
|
1680
|
+
}
|
|
1681
|
+
// 删除到回收站是可恢复操作:单条与批量都直接执行,不需要输入口令。
|
|
1682
|
+
sendJson(res, 200, { ok: true, value: { results: await sessions.removeToTrash(ids) } });
|
|
1683
|
+
return;
|
|
1684
|
+
}
|
|
1685
|
+
if (body.action === "restore") {
|
|
1686
|
+
const ids = readIdList(body, "trashIds");
|
|
1687
|
+
if (!ids || !ids.every(sessionsPure.isTrashId)) {
|
|
1688
|
+
sendBadRequest(res);
|
|
1689
|
+
return;
|
|
1690
|
+
}
|
|
1691
|
+
sendJson(res, 200, { ok: true, value: { results: await sessions.restore(ids) } });
|
|
1692
|
+
return;
|
|
1693
|
+
}
|
|
1694
|
+
if (body.action === "purge") {
|
|
1695
|
+
if (body.all === true) {
|
|
1696
|
+
// 清空回收站需要显式口令(输入 OK),避免误触或伪造请求直接清空。
|
|
1697
|
+
if (!isSessionConfirm(body.confirm)) {
|
|
1698
|
+
sendError(res, 400, "CONFIRM_REQUIRED");
|
|
1699
|
+
return;
|
|
1700
|
+
}
|
|
1701
|
+
sendJson(res, 200, { ok: true, value: await sessions.purge([], true) });
|
|
1702
|
+
return;
|
|
1703
|
+
}
|
|
1704
|
+
const ids = readIdList(body, "trashIds");
|
|
1705
|
+
if (!ids || !ids.every(sessionsPure.isTrashId)) {
|
|
1706
|
+
sendBadRequest(res);
|
|
1707
|
+
return;
|
|
1708
|
+
}
|
|
1709
|
+
// 批量彻底清理不可恢复,需要 OK;单条彻底清理沿用轻量确认按钮。
|
|
1710
|
+
if (ids.length > 1 && !isSessionConfirm(body.confirm)) {
|
|
1711
|
+
sendError(res, 400, "CONFIRM_REQUIRED");
|
|
1712
|
+
return;
|
|
1713
|
+
}
|
|
1714
|
+
sendJson(res, 200, { ok: true, value: await sessions.purge(ids, false) });
|
|
1715
|
+
return;
|
|
1716
|
+
}
|
|
1717
|
+
if (body.action === "archive") {
|
|
1718
|
+
const ids = readIdList(body, "sessionIds");
|
|
1719
|
+
if (!ids || !ids.every(sessionsPure.isSessionId)) {
|
|
1720
|
+
sendBadRequest(res);
|
|
1721
|
+
return;
|
|
1722
|
+
}
|
|
1723
|
+
sendJson(res, 200, { ok: true, value: await sessions.archive(ids) });
|
|
1724
|
+
return;
|
|
1725
|
+
}
|
|
1726
|
+
sendBadRequest(res);
|
|
1727
|
+
} catch (err) {
|
|
1728
|
+
ctx.logger?.warn?.(`[dsh-message-actions] session action failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1729
|
+
sendError(res, 500, "INTERNAL");
|
|
1730
|
+
}
|
|
1731
|
+
};
|
|
1732
|
+
}
|
|
1733
|
+
|
|
1175
1734
|
// ---------------------------------------------------------------------------
|
|
1176
1735
|
// 插件主体
|
|
1177
1736
|
// ---------------------------------------------------------------------------
|
|
1178
1737
|
|
|
1179
1738
|
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
1739
|
// —— 费用统计 ——
|
|
1206
1740
|
const cost = createCostService(ctx, config);
|
|
1207
1741
|
const stats = createStatsService(ctx, cost, config);
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
)
|
|
1742
|
+
const sessions = createSessionManager(ctx, { sessionMeta: (record) => stats.sessionMeta(record) });
|
|
1743
|
+
// 清理上次崩溃留下的暂存目录(只动一小时前的)。
|
|
1744
|
+
sessions.sweepStaging().catch(() => {});
|
|
1745
|
+
// 启动即探测一次 provider → baseURL;失败静默,不影响任何路由注册。
|
|
1746
|
+
cost.refreshEndpoints(false).catch(() => {});
|
|
1747
|
+
|
|
1748
|
+
// 所有路由统一包一层兜底:handler 内部漏掉的异常只会变成 500 JSON,
|
|
1749
|
+
// 不会以未处理 rejection 的形式穿透到宿主(宿主界面也就不会弹自己的报错)。
|
|
1750
|
+
const route = (path, handler, label) =>
|
|
1751
|
+
ctx.effect(
|
|
1752
|
+
() => ctx.webServer.register({
|
|
1753
|
+
kind: "exact",
|
|
1754
|
+
path,
|
|
1755
|
+
handler: guardedHandler(handler, {
|
|
1756
|
+
label,
|
|
1757
|
+
log: (message) => {
|
|
1758
|
+
if (typeof ctx.logger?.warn === "function") ctx.logger.warn(message);
|
|
1759
|
+
}
|
|
1760
|
+
})
|
|
1761
|
+
}),
|
|
1762
|
+
`dsh-message-actions: ${label}`
|
|
1763
|
+
);
|
|
1764
|
+
|
|
1765
|
+
route("/dsh-message-actions", makeActionHandler(ctx), "write route");
|
|
1766
|
+
route("/dsh-message-actions/messages", makeMessagesHandler(ctx, cost), "read route");
|
|
1767
|
+
route(ATTACHMENT_ROUTE, makeAttachmentHandler(ctx), "attachment route");
|
|
1768
|
+
route("/dsh-message-actions/cost/state", makeCostStateHandler(ctx, cost), "cost state route");
|
|
1217
1769
|
// —— 会话统计(数据来自官方会话日志)——
|
|
1218
|
-
ctx
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
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
|
-
);
|
|
1770
|
+
route(STATS_ROUTE, makeStatsHandler(ctx, stats), "session stats route");
|
|
1771
|
+
route(STATS_BUDGET_ROUTE, makeStatsBudgetHandler(ctx, cost), "stats budget route");
|
|
1772
|
+
route(BILLING_ROUTE, makeBillingHandler(ctx, cost), "billing route");
|
|
1773
|
+
// —— 会话管理(删除到回收站 / 恢复 / 彻底清理 / 归档)——
|
|
1774
|
+
route(SESSIONS_ROUTE, makeSessionsHandler(ctx, sessions, config), "sessions route");
|
|
1234
1775
|
|
|
1235
1776
|
ctx.effect(() => {
|
|
1236
1777
|
const offEvent = ctx.on("session/event", (session, event) => cost.onSessionEvent(session, event));
|
|
@@ -1249,4 +1790,5 @@ function apply(ctx, config) {
|
|
|
1249
1790
|
}, "dsh-message-actions: cost service");
|
|
1250
1791
|
}
|
|
1251
1792
|
|
|
1252
|
-
|
|
1793
|
+
// makeSessionsHandler 仅供端到端测试直接驱动会话路由(真实文件系统 + 真实处理器)。
|
|
1794
|
+
export { Config, apply, inject, name, makeSessionsHandler };
|