dsh-message-actions 0.0.0-stage → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.cn.md +250 -0
- package/README.md +249 -2
- package/cordis.patch.yml +3 -0
- package/icon.svg +5 -0
- package/lib/client.js +4293 -0
- package/lib/http.cjs +131 -0
- package/lib/index.js +862 -0
- package/lib/shared.cjs +1781 -0
- package/lib/store.cjs +261 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +56 -3
package/lib/index.js
ADDED
|
@@ -0,0 +1,862 @@
|
|
|
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
|
+
costSwitches,
|
|
36
|
+
turnCostOfGroups,
|
|
37
|
+
deriveTurnUsage,
|
|
38
|
+
createTurnBuffer,
|
|
39
|
+
appendTurnEvent,
|
|
40
|
+
observeBalance,
|
|
41
|
+
correctedBalanceCents,
|
|
42
|
+
validateCorrectionAmount,
|
|
43
|
+
pruneDailySpend,
|
|
44
|
+
yuanToCents
|
|
45
|
+
} = shared;
|
|
46
|
+
|
|
47
|
+
const {
|
|
48
|
+
resolveStatePath,
|
|
49
|
+
loadCostState,
|
|
50
|
+
persistCostState
|
|
51
|
+
} = store;
|
|
52
|
+
|
|
53
|
+
// ---------------------------------------------------------------------------
|
|
54
|
+
// 插件身份与依赖
|
|
55
|
+
// ---------------------------------------------------------------------------
|
|
56
|
+
|
|
57
|
+
const name = "dsh-message-actions";
|
|
58
|
+
|
|
59
|
+
const inject = ["webServer", "sessions", "agents"];
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 宿主配置。所有字段必须 `.volatile()`,否则官方配置通道不认;
|
|
63
|
+
* 改 Config 需重启 DSH 生效。设置页顺序由这里的声明顺序决定。
|
|
64
|
+
*/
|
|
65
|
+
const Config = z.object({
|
|
66
|
+
recall: z.boolean().default(true).volatile(),
|
|
67
|
+
share: z.boolean().default(true).volatile(),
|
|
68
|
+
export: z.boolean().default(true).volatile(),
|
|
69
|
+
delete: z.boolean().default(true).volatile(),
|
|
70
|
+
deleteFrom: z.boolean().default(true).volatile(),
|
|
71
|
+
confirm: z.boolean().default(true).volatile(),
|
|
72
|
+
stats: z.boolean().default(true).volatile(),
|
|
73
|
+
|
|
74
|
+
// —— 费用统计(新增)——
|
|
75
|
+
usageStats: z.boolean().default(true).volatile(),
|
|
76
|
+
// 计费样式排在「单次消耗」之前;默认单行样式(compact)。
|
|
77
|
+
costLayout: z.string().default("compact").volatile(),
|
|
78
|
+
costPerTurn: z.boolean().default(true).volatile(),
|
|
79
|
+
costPerTurnAutoClose: z.number().min(0).max(600).default(0).volatile(),
|
|
80
|
+
costPeakValley: z.boolean().default(true).volatile()
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
// ---------------------------------------------------------------------------
|
|
84
|
+
// 信任围栏
|
|
85
|
+
// ---------------------------------------------------------------------------
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* 请求入站三重围栏。回环 Host 与 Sec-Fetch-Site/Origin 校验为纯逻辑
|
|
89
|
+
* (见 shared.cjs 的 isLoopbackHost / isTrustedRequest),此处仅实时解析
|
|
90
|
+
* webServer 同源地址。
|
|
91
|
+
*/
|
|
92
|
+
function isTrusted(req, webServer) {
|
|
93
|
+
let expectedOrigin;
|
|
94
|
+
try {
|
|
95
|
+
expectedOrigin = webServer.getOrigin();
|
|
96
|
+
} catch {
|
|
97
|
+
expectedOrigin = undefined;
|
|
98
|
+
}
|
|
99
|
+
return isTrustedRequest({
|
|
100
|
+
host: req.headers.host,
|
|
101
|
+
secFetchSite: req.headers["sec-fetch-site"],
|
|
102
|
+
origin: req.headers.origin,
|
|
103
|
+
expectedOrigin
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// ---------------------------------------------------------------------------
|
|
108
|
+
// 事件与随机 id
|
|
109
|
+
// ---------------------------------------------------------------------------
|
|
110
|
+
|
|
111
|
+
/** 由消息 id 反查表面节点的 seq;找不到返回 null。 */
|
|
112
|
+
function resolveSeqByMessageId(events, nodes, messageId) {
|
|
113
|
+
for (const seq of nodes) {
|
|
114
|
+
const event = events[seq];
|
|
115
|
+
if (event && messageIdOf(event) === messageId) return seq;
|
|
116
|
+
}
|
|
117
|
+
return null;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function newTombstoneId() {
|
|
121
|
+
try {
|
|
122
|
+
return `dma-${randomUUID()}`;
|
|
123
|
+
} catch {
|
|
124
|
+
return `dma-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// ---------------------------------------------------------------------------
|
|
129
|
+
// 路由处理器
|
|
130
|
+
// ---------------------------------------------------------------------------
|
|
131
|
+
|
|
132
|
+
function makeActionHandler(ctx) {
|
|
133
|
+
return async function handleAction(req, res) {
|
|
134
|
+
if (req.method !== "POST") {
|
|
135
|
+
drainRequest(req);
|
|
136
|
+
sendMethodNotAllowed(res, "POST");
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
if (!isTrusted(req, ctx.webServer)) {
|
|
140
|
+
drainRequest(req);
|
|
141
|
+
sendForbidden(res);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const contentType = (req.headers["content-type"] || "").split(";")[0].trim().toLowerCase();
|
|
145
|
+
if (contentType !== "application/json") {
|
|
146
|
+
drainRequest(req);
|
|
147
|
+
sendBadRequest(res);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const body = await readJsonBody(req, res);
|
|
152
|
+
if (body === null) return;
|
|
153
|
+
if (!body || typeof body !== "object") {
|
|
154
|
+
sendBadRequest(res);
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const { sessionId, action, seq, messageId } = body;
|
|
159
|
+
if (typeof sessionId !== "string" || sessionId.length === 0) {
|
|
160
|
+
sendBadRequest(res);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
if (action !== "recall" && action !== "delete" && action !== "deleteFrom") {
|
|
164
|
+
sendBadRequest(res);
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
const hasSeq = Number.isSafeInteger(seq) && seq >= 0;
|
|
168
|
+
const hasMessageId = typeof messageId === "string" && messageId.length > 0;
|
|
169
|
+
if (!hasSeq && !hasMessageId) {
|
|
170
|
+
sendBadRequest(res);
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const agent = ctx.agents.get(sessionId);
|
|
175
|
+
if (agent === undefined || agent.session === undefined) {
|
|
176
|
+
sendError(res, 409, "SESSION_NOT_LIVE");
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
const session = agent.session;
|
|
180
|
+
if (agent.status === "running") {
|
|
181
|
+
sendError(res, 423, "AGENT_BUSY");
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const events = session.snapshotEvents();
|
|
186
|
+
const nodes = [...session.surface.nodes];
|
|
187
|
+
|
|
188
|
+
let targetSeq = seq;
|
|
189
|
+
if (!hasSeq) {
|
|
190
|
+
targetSeq = resolveSeqByMessageId(events, nodes, messageId);
|
|
191
|
+
if (targetSeq === null) {
|
|
192
|
+
sendError(res, 409, "TARGET_NOT_FOUND");
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const plan = planAction(events, nodes, { action, seq: targetSeq });
|
|
198
|
+
if (!plan.ok) {
|
|
199
|
+
sendError(res, statusCodeOf(plan.code), plan.code);
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const data = {
|
|
204
|
+
role: "user",
|
|
205
|
+
id: newTombstoneId(),
|
|
206
|
+
content: [{ type: "text", text: TOMBSTONE_TEXT[action] }],
|
|
207
|
+
source: {
|
|
208
|
+
kind: "user",
|
|
209
|
+
producer: PRODUCER,
|
|
210
|
+
action,
|
|
211
|
+
via: plan.via,
|
|
212
|
+
removed: plan.removed,
|
|
213
|
+
kinds: plan.kinds,
|
|
214
|
+
turn: plan.turn
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
try {
|
|
219
|
+
await agent.runMaintenance(async () => {
|
|
220
|
+
session.append("user/message", data, {
|
|
221
|
+
surfaceOp: { op: "replace", startSeq: plan.startSeq, endSeq: plan.endSeq },
|
|
222
|
+
sourceEventSeqs: plan.removed
|
|
223
|
+
});
|
|
224
|
+
await ctx.sessions.flush(session);
|
|
225
|
+
});
|
|
226
|
+
} catch (err) {
|
|
227
|
+
// 优先按结构化字段判定 busy(err.code / err.status);宿主的忙错误目前
|
|
228
|
+
// 没有 code,此时才回退到文案匹配。
|
|
229
|
+
if (isBusyError(err)) {
|
|
230
|
+
sendError(res, 423, "AGENT_BUSY");
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
234
|
+
if (typeof ctx.logger?.warn === "function") {
|
|
235
|
+
ctx.logger.warn(`[dsh-message-actions] ${action} failed: ${message}`);
|
|
236
|
+
}
|
|
237
|
+
sendError(res, 500, "INTERNAL");
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
sendJson(res, 200, {
|
|
242
|
+
ok: true,
|
|
243
|
+
value: {
|
|
244
|
+
action,
|
|
245
|
+
seq,
|
|
246
|
+
via: plan.via,
|
|
247
|
+
removed: plan.removed,
|
|
248
|
+
turn: plan.turn,
|
|
249
|
+
step: plan.step,
|
|
250
|
+
refillText: plan.refillText
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function makeMessagesHandler(ctx) {
|
|
257
|
+
return async function handleMessages(req, res) {
|
|
258
|
+
if (req.method !== "GET") {
|
|
259
|
+
drainRequest(req);
|
|
260
|
+
sendMethodNotAllowed(res, "GET");
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
if (!isTrusted(req, ctx.webServer)) {
|
|
264
|
+
drainRequest(req);
|
|
265
|
+
sendForbidden(res);
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
const url = new URL(req.url || "/", "http://x");
|
|
269
|
+
const sessionId = url.searchParams.get("sessionId");
|
|
270
|
+
if (!sessionId) {
|
|
271
|
+
sendBadRequest(res);
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const agent = ctx.agents.get(sessionId);
|
|
276
|
+
if (agent === undefined || agent.session === undefined) {
|
|
277
|
+
sendError(res, 409, "SESSION_NOT_LIVE");
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
const session = agent.session;
|
|
281
|
+
|
|
282
|
+
const events = session.snapshotEvents();
|
|
283
|
+
const nodes = [...session.surface.nodes];
|
|
284
|
+
|
|
285
|
+
// user/message 没有 data.turn(真实日志里只有 assistant/tool 带 turn),
|
|
286
|
+
// 需要按 turn/start~turn/end 区间推导,否则问行按钮找不到对应 seq。
|
|
287
|
+
// 一次构建索引与 seq→turn 映射,供 rows / rounds / goneTurns 复用。
|
|
288
|
+
const turns = createTurnLookup(events);
|
|
289
|
+
|
|
290
|
+
// 全文按需接口:只给分享图 / 导出使用,普通 3s 轮询不经过这里。
|
|
291
|
+
if (url.searchParams.get("full") === "1") {
|
|
292
|
+
const turnsParam = url.searchParams.get("turns");
|
|
293
|
+
let turnFilter = null;
|
|
294
|
+
if (turnsParam !== null && turnsParam !== "") {
|
|
295
|
+
turnFilter = new Set(
|
|
296
|
+
turnsParam.split(",")
|
|
297
|
+
.filter((s) => s.trim() !== "")
|
|
298
|
+
.map((s) => Number(s))
|
|
299
|
+
.filter(Number.isSafeInteger)
|
|
300
|
+
);
|
|
301
|
+
}
|
|
302
|
+
const rounds = roundsOf(events, nodes, turns);
|
|
303
|
+
const liveNodes = liveNodesOf(events, nodes);
|
|
304
|
+
const lastSeq = liveNodes.length > 0 ? liveNodes[liveNodes.length - 1] : 0;
|
|
305
|
+
sendJson(res, 200, {
|
|
306
|
+
ok: true,
|
|
307
|
+
value: {
|
|
308
|
+
version: Number.isSafeInteger(lastSeq) ? lastSeq : 0,
|
|
309
|
+
nodeCount: liveNodes.length,
|
|
310
|
+
rounds: turnFilter === null ? rounds : rounds.filter((round) => turnFilter.has(round.turn))
|
|
311
|
+
}
|
|
312
|
+
});
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
let filter = null;
|
|
317
|
+
const seqsParam = url.searchParams.get("seqs");
|
|
318
|
+
if (seqsParam !== null && seqsParam !== "") {
|
|
319
|
+
filter = new Set(
|
|
320
|
+
seqsParam.split(",")
|
|
321
|
+
.filter((s) => s.trim() !== "")
|
|
322
|
+
.map((s) => Number(s))
|
|
323
|
+
.filter(Number.isSafeInteger)
|
|
324
|
+
);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// 增量游标:since=<上次快照 version> 时只回新增行(不带 since 仍为全量)。
|
|
328
|
+
// 选择游标而非 seqs 列表:seqs 在这里是「包含列表」,且长会话已持有 seq
|
|
329
|
+
// 会无限增长;游标只传一个整数,语义与追加式事件日志天然吻合。
|
|
330
|
+
const sinceParam = url.searchParams.get("since");
|
|
331
|
+
let since = null;
|
|
332
|
+
if (sinceParam !== null && sinceParam !== "") {
|
|
333
|
+
const parsed = Number(sinceParam.trim());
|
|
334
|
+
since = Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : null;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// 摘要轮询:只回 preview / words / usage / callId,不回正文。
|
|
338
|
+
// 系统 / 开发者提示词与工具结果正文从不进入摘要(预览也只覆盖问 / 答)。
|
|
339
|
+
sendJson(res, 200, {
|
|
340
|
+
ok: true,
|
|
341
|
+
value: messagesSummaryOf(events, nodes, turns, { filter, since, previewLimit: 200 })
|
|
342
|
+
});
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// ---------------------------------------------------------------------------
|
|
347
|
+
// 费用统计服务(余额观测 + 单次结算 + 持久化状态)
|
|
348
|
+
// ---------------------------------------------------------------------------
|
|
349
|
+
|
|
350
|
+
const COST_REFRESH_MIN_INTERVAL_MS = 60 * 1000;
|
|
351
|
+
const COST_BALANCE_TIMEOUT_MS = 10 * 1000;
|
|
352
|
+
const ROUTING_TIMEOUT_MS = 3 * 1000;
|
|
353
|
+
const ROUTING_CACHE_MS = 5 * 1000;
|
|
354
|
+
const DSH_VERSION_FALLBACK = "0.2.1";
|
|
355
|
+
|
|
356
|
+
/** getBalance 的客户端元数据:时区固定北京时间,不随本机漂移。 */
|
|
357
|
+
function accountClientMetadata() {
|
|
358
|
+
const env = typeof process !== "undefined" && process.env ? process.env : {};
|
|
359
|
+
const version = typeof env.DSH_VERSION === "string" && env.DSH_VERSION.trim()
|
|
360
|
+
? env.DSH_VERSION.trim()
|
|
361
|
+
: DSH_VERSION_FALLBACK;
|
|
362
|
+
return { version, locale: "zh-CN", timezoneOffsetSeconds: 8 * 3600 };
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** 事件时刻:优先数值 time,其次 ISO 字符串,最后宿主收包时刻。 */
|
|
366
|
+
function eventTime(event) {
|
|
367
|
+
if (event && typeof event === "object") {
|
|
368
|
+
if (typeof event.time === "number" && Number.isFinite(event.time)) return event.time;
|
|
369
|
+
if (typeof event.time === "string") {
|
|
370
|
+
const parsed = Date.parse(event.time);
|
|
371
|
+
if (Number.isFinite(parsed)) return parsed;
|
|
372
|
+
}
|
|
373
|
+
if (event.data && typeof event.data.at === "number" && Number.isFinite(event.data.at)) {
|
|
374
|
+
return event.data.at;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
return Date.now();
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** 钱包列表按 CNY 求和(其他币种忽略,不换算)。 */
|
|
381
|
+
function sumCnyWallets(wallets) {
|
|
382
|
+
if (!Array.isArray(wallets)) return 0;
|
|
383
|
+
let cents = 0;
|
|
384
|
+
for (const wallet of wallets) {
|
|
385
|
+
if (!wallet || typeof wallet !== "object") continue;
|
|
386
|
+
if (wallet.currency !== "CNY") continue;
|
|
387
|
+
const value = yuanToCents(wallet.balance);
|
|
388
|
+
if (value !== null) cents += value;
|
|
389
|
+
}
|
|
390
|
+
return cents;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
function withTimeout(promise, ms) {
|
|
394
|
+
let timer;
|
|
395
|
+
const timeout = new Promise((_, reject) => {
|
|
396
|
+
timer = setTimeout(() => reject(new Error("balance request timed out")), ms);
|
|
397
|
+
});
|
|
398
|
+
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function accountServiceOf(ctx) {
|
|
402
|
+
try {
|
|
403
|
+
const service = ctx.get("deepseekAccount");
|
|
404
|
+
if (service && typeof service.getBalance === "function") return service;
|
|
405
|
+
} catch {
|
|
406
|
+
/* 服务缺失 */
|
|
407
|
+
}
|
|
408
|
+
return null;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
async function hasApiKey(ctx) {
|
|
412
|
+
try {
|
|
413
|
+
const credentials = ctx.get("credentials");
|
|
414
|
+
if (credentials && typeof credentials.resolve === "function") {
|
|
415
|
+
const resolved = await credentials.resolve("DEEPSEEK_API_KEY");
|
|
416
|
+
const value = resolved && typeof resolved === "object" ? resolved.value : resolved;
|
|
417
|
+
if (typeof value === "string" && value.trim().length > 0) return true;
|
|
418
|
+
}
|
|
419
|
+
} catch {
|
|
420
|
+
/* 凭据服务不可用,回退环境变量 */
|
|
421
|
+
}
|
|
422
|
+
const env = typeof process !== "undefined" && process.env ? process.env : {};
|
|
423
|
+
return typeof env.DEEPSEEK_API_KEY === "string" && env.DEEPSEEK_API_KEY.trim().length > 0;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* 创建费用统计服务。内存状态为唯一读写源,写盘为整份原子替换。
|
|
428
|
+
* @param ctx Cordis 宿主上下文
|
|
429
|
+
* @param config 宿主 Config(volatile 对象)
|
|
430
|
+
*/
|
|
431
|
+
function createCostService(ctx, config) {
|
|
432
|
+
const cfg = config || {};
|
|
433
|
+
// 运行时读取开关,默认值与旧版保持一致(未配置 = 开启)。
|
|
434
|
+
const switches = () => costSwitches(cfg);
|
|
435
|
+
const isEnabled = () => switches().enabled;
|
|
436
|
+
|
|
437
|
+
const statePath = resolveStatePath();
|
|
438
|
+
const loaded = loadCostState(statePath, ctx.logger);
|
|
439
|
+
const state = loaded.state;
|
|
440
|
+
const readOnly = loaded.readOnly;
|
|
441
|
+
|
|
442
|
+
if (!isEnabled()) {
|
|
443
|
+
// 启动时总开关关闭:丢掉上次的余额基线,重新开启后首次观测只建基线,不补记关闭期间的差额。
|
|
444
|
+
state.lastBalanceCents = null;
|
|
445
|
+
state.lastBalanceAt = 0;
|
|
446
|
+
}
|
|
447
|
+
let lastEnabled = isEnabled();
|
|
448
|
+
|
|
449
|
+
const cache = { rechargeCents: null, bonusCents: null, totalCents: null, updatedAt: 0 };
|
|
450
|
+
const buffers = new Map();
|
|
451
|
+
const MAX_BUFFERS = 200;
|
|
452
|
+
let lastTurn = null;
|
|
453
|
+
let inFlight = null;
|
|
454
|
+
let lastFetchFailed = false;
|
|
455
|
+
let lastMessageProvider;
|
|
456
|
+
let lastHeaderProvider;
|
|
457
|
+
let routingCache = { at: 0, value: null };
|
|
458
|
+
|
|
459
|
+
const warn = (message) => {
|
|
460
|
+
if (typeof ctx.logger?.warn === "function") ctx.logger.warn(`[dsh-message-actions] ${message}`);
|
|
461
|
+
};
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* 写盘并返回结果:`{ ok:true }` 或 `{ ok:false, error }`。
|
|
465
|
+
* 只读 / 写入失败不再被吞掉——调用方(余额校正路由)据此返回 500,
|
|
466
|
+
* 避免客户端把未落盘的写操作显示为成功。
|
|
467
|
+
*/
|
|
468
|
+
function persist() {
|
|
469
|
+
state.updatedAt = Date.now();
|
|
470
|
+
state.dailySpendCents = pruneDailySpend(state.dailySpendCents, state.updatedAt, shared.DAILY_KEEP_DAYS);
|
|
471
|
+
return persistCostState(statePath, state, readOnly, ctx.logger);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
async function routingInfo() {
|
|
475
|
+
const now = Date.now();
|
|
476
|
+
if (routingCache.value && now - routingCache.at < ROUTING_CACHE_MS) return routingCache.value;
|
|
477
|
+
|
|
478
|
+
const provider = lastMessageProvider || lastHeaderProvider;
|
|
479
|
+
const mapped = routingOfProvider(provider);
|
|
480
|
+
const finish = (value) => {
|
|
481
|
+
routingCache = { at: Date.now(), value };
|
|
482
|
+
return value;
|
|
483
|
+
};
|
|
484
|
+
if (mapped) return finish({ routing: mapped, provider });
|
|
485
|
+
|
|
486
|
+
let hasKey = false;
|
|
487
|
+
try {
|
|
488
|
+
hasKey = await withTimeout(Promise.resolve(hasApiKey(ctx)), ROUTING_TIMEOUT_MS);
|
|
489
|
+
} catch {
|
|
490
|
+
hasKey = false; // 凭据服务卡住时按未配置处理,继续尝试账户路由
|
|
491
|
+
}
|
|
492
|
+
if (hasKey) return finish({ routing: "api-key", provider: "deepseek-official" });
|
|
493
|
+
|
|
494
|
+
const account = accountServiceOf(ctx);
|
|
495
|
+
if (!account) return finish({ routing: "unavailable", provider: undefined });
|
|
496
|
+
try {
|
|
497
|
+
const snapshot = await withTimeout(Promise.resolve(account.getState()), ROUTING_TIMEOUT_MS);
|
|
498
|
+
const status = snapshot && typeof snapshot === "object" ? snapshot.status : undefined;
|
|
499
|
+
if (status === "credential-stored") return finish({ routing: "account", provider: "deepseek-account" });
|
|
500
|
+
return finish({ routing: "signed-out", provider: undefined });
|
|
501
|
+
} catch {
|
|
502
|
+
return finish({ routing: "unavailable", provider: undefined });
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
async function fetchOnce() {
|
|
507
|
+
const routing = (await routingInfo()).routing;
|
|
508
|
+
if (routing !== "account") {
|
|
509
|
+
lastFetchFailed = false;
|
|
510
|
+
return;
|
|
511
|
+
}
|
|
512
|
+
state.lastAttemptAt = Date.now();
|
|
513
|
+
const account = accountServiceOf(ctx);
|
|
514
|
+
if (!account) {
|
|
515
|
+
lastFetchFailed = true;
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
let result;
|
|
519
|
+
try {
|
|
520
|
+
result = await withTimeout(
|
|
521
|
+
Promise.resolve(account.getBalance(accountClientMetadata())),
|
|
522
|
+
COST_BALANCE_TIMEOUT_MS
|
|
523
|
+
);
|
|
524
|
+
} catch {
|
|
525
|
+
lastFetchFailed = true;
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
if (!result || typeof result !== "object" || (typeof result.status === "string" && result.status !== "ready")) {
|
|
529
|
+
lastFetchFailed = true;
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
const rechargeCents = sumCnyWallets(result.value);
|
|
533
|
+
const bonusCents = sumCnyWallets(result.bonusWallets);
|
|
534
|
+
const totalCents = rechargeCents + bonusCents;
|
|
535
|
+
const at = Date.now();
|
|
536
|
+
|
|
537
|
+
cache.rechargeCents = rechargeCents;
|
|
538
|
+
cache.bonusCents = bonusCents;
|
|
539
|
+
cache.totalCents = totalCents;
|
|
540
|
+
cache.updatedAt = at;
|
|
541
|
+
lastFetchFailed = false;
|
|
542
|
+
|
|
543
|
+
const observed = observeBalance(state, { cents: totalCents, routing: "account", at });
|
|
544
|
+
Object.assign(state, observed.state);
|
|
545
|
+
state.lastAttemptAt = at;
|
|
546
|
+
persist();
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** 背景 / 强制刷新;单飞 + 60s 节流 + 10s 超时。 */
|
|
550
|
+
function refresh(force) {
|
|
551
|
+
const enabled = isEnabled();
|
|
552
|
+
if (enabled !== lastEnabled) {
|
|
553
|
+
lastEnabled = enabled;
|
|
554
|
+
if (!enabled) {
|
|
555
|
+
// 运行中关闭总开关:与「启动时已关闭」同路径,丢弃余额基线。
|
|
556
|
+
// 重新开启后首次观测只建基线,不把关闭期间的消费计入「日用」。
|
|
557
|
+
state.lastBalanceCents = null;
|
|
558
|
+
state.lastBalanceAt = 0;
|
|
559
|
+
persist();
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
if (!enabled) return Promise.resolve();
|
|
563
|
+
if (inFlight) return inFlight;
|
|
564
|
+
const now = Date.now();
|
|
565
|
+
if (!force && now - state.lastAttemptAt < COST_REFRESH_MIN_INTERVAL_MS) return Promise.resolve();
|
|
566
|
+
inFlight = fetchOnce()
|
|
567
|
+
.catch((err) => {
|
|
568
|
+
lastFetchFailed = true;
|
|
569
|
+
warn(`balance refresh failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
570
|
+
})
|
|
571
|
+
.finally(() => {
|
|
572
|
+
inFlight = null;
|
|
573
|
+
});
|
|
574
|
+
return inFlight;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
/**
|
|
578
|
+
* 余额校正:先改内存再落盘;落盘失败时把 4 个字段回滚,
|
|
579
|
+
* 返回失败结果,避免内存状态与磁盘状态不一致。
|
|
580
|
+
*/
|
|
581
|
+
function applyCorrection(creditCents, debitCents) {
|
|
582
|
+
const previous = {
|
|
583
|
+
credit: state.correctionCreditCents,
|
|
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;
|
|
592
|
+
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
|
+
}
|
|
599
|
+
return saved;
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
async function stateValue() {
|
|
603
|
+
const now = Date.now();
|
|
604
|
+
const routing = (await routingInfo()).routing;
|
|
605
|
+
let status;
|
|
606
|
+
if (routing === "signed-out") status = "signed-out";
|
|
607
|
+
else if (routing === "api-key") status = "api-key";
|
|
608
|
+
else if (routing === "unavailable") status = "unavailable";
|
|
609
|
+
else if (routing === "local") status = "local";
|
|
610
|
+
else status = cache.updatedAt > 0 && !lastFetchFailed ? "ready" : "stale";
|
|
611
|
+
|
|
612
|
+
const period = periodInfo(now);
|
|
613
|
+
return {
|
|
614
|
+
status,
|
|
615
|
+
billing: routing,
|
|
616
|
+
balance: {
|
|
617
|
+
rechargeCents: cache.rechargeCents,
|
|
618
|
+
bonusCents: cache.bonusCents,
|
|
619
|
+
totalCents: cache.totalCents,
|
|
620
|
+
updatedAt: cache.updatedAt,
|
|
621
|
+
refreshing: inFlight !== null
|
|
622
|
+
},
|
|
623
|
+
dailyCents: state.dailySpendCents[beijingDateKey(now)] || 0,
|
|
624
|
+
pendingAdjustmentCents: state.pendingAdjustmentCents,
|
|
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
|
+
},
|
|
637
|
+
period: period.period,
|
|
638
|
+
nextChangeAt: period.nextChangeAt,
|
|
639
|
+
lastTurn: switches().perTurn ? lastTurn : null
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/** 会话事件:跟踪最近模型路由,并在 turn/end 时结算本轮。 */
|
|
644
|
+
function onSessionEvent(session, event) {
|
|
645
|
+
if (!isEnabled()) return;
|
|
646
|
+
if (!event || typeof event !== "object") return;
|
|
647
|
+
const sessionId = session && typeof session.id === "string" ? session.id : undefined;
|
|
648
|
+
if (!sessionId) return;
|
|
649
|
+
const type = event.type;
|
|
650
|
+
const data = event.data || {};
|
|
651
|
+
|
|
652
|
+
if (type === "assistant/message") {
|
|
653
|
+
const route = routeOfUsage(data.usage) || routeOfMessage(data.message);
|
|
654
|
+
if (route) {
|
|
655
|
+
lastMessageProvider = route.provider;
|
|
656
|
+
routingCache = { at: 0, value: null };
|
|
657
|
+
}
|
|
658
|
+
} else if (type === "request/header") {
|
|
659
|
+
const provider = data.header && data.header.config ? data.header.config.provider : undefined;
|
|
660
|
+
if (typeof provider === "string" && provider.length > 0) {
|
|
661
|
+
lastHeaderProvider = provider;
|
|
662
|
+
routingCache = { at: 0, value: null };
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
if (!switches().perTurn) {
|
|
667
|
+
// 运行中关闭「单次」后不再保留旧的 lastTurn,避免重新开启时闪回过期金额。
|
|
668
|
+
lastTurn = null;
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
if (type === "turn/start") {
|
|
672
|
+
// 防御性上限:会话中途异常结束(没有 turn/end)时不让缓冲无限增长。
|
|
673
|
+
if (buffers.size >= MAX_BUFFERS && !buffers.has(sessionId)) {
|
|
674
|
+
const oldest = buffers.keys().next();
|
|
675
|
+
if (!oldest.done) buffers.delete(oldest.value);
|
|
676
|
+
}
|
|
677
|
+
buffers.set(sessionId, createTurnBuffer(
|
|
678
|
+
Number.isSafeInteger(data.turn) ? data.turn : undefined,
|
|
679
|
+
eventTime(event)
|
|
680
|
+
));
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
const buffer = buffers.get(sessionId);
|
|
685
|
+
if (!buffer) return; // 未见 turn/start:不回放历史
|
|
686
|
+
appendTurnEvent(buffer, event);
|
|
687
|
+
if (type !== "turn/end") return;
|
|
688
|
+
|
|
689
|
+
buffers.delete(sessionId);
|
|
690
|
+
if (buffer.overflow) return;
|
|
691
|
+
const usage = deriveTurnUsage(buffer.events);
|
|
692
|
+
if (!usage) return;
|
|
693
|
+
const at = Number.isFinite(usage.at) ? usage.at : buffer.at;
|
|
694
|
+
const period = periodInfo(at).period;
|
|
695
|
+
lastTurn = {
|
|
696
|
+
at,
|
|
697
|
+
endedAt: Number.isFinite(usage.endedAt) ? usage.endedAt : eventTime(event),
|
|
698
|
+
provider: usage.provider,
|
|
699
|
+
models: usage.models,
|
|
700
|
+
tokens: usage.tokens,
|
|
701
|
+
costMicros: turnCostOfGroups(usage.groups, period, PRICE_TABLE),
|
|
702
|
+
turn: Number.isSafeInteger(usage.turn) ? usage.turn : buffer.turn
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
function dispose() {
|
|
707
|
+
buffers.clear();
|
|
708
|
+
inFlight = null;
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
return {
|
|
712
|
+
isEnabled,
|
|
713
|
+
isPerTurn: () => switches().perTurn,
|
|
714
|
+
refresh,
|
|
715
|
+
stateValue,
|
|
716
|
+
applyCorrection,
|
|
717
|
+
onSessionEvent,
|
|
718
|
+
dispose,
|
|
719
|
+
state,
|
|
720
|
+
readOnly
|
|
721
|
+
};
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
// ---------------------------------------------------------------------------
|
|
725
|
+
// 费用统计路由
|
|
726
|
+
// ---------------------------------------------------------------------------
|
|
727
|
+
|
|
728
|
+
function makeCostStateHandler(ctx, service) {
|
|
729
|
+
return async function handleCostState(req, res) {
|
|
730
|
+
if (req.method !== "GET") {
|
|
731
|
+
drainRequest(req);
|
|
732
|
+
sendMethodNotAllowed(res, "GET");
|
|
733
|
+
return;
|
|
734
|
+
}
|
|
735
|
+
if (!isTrusted(req, ctx.webServer)) {
|
|
736
|
+
drainRequest(req);
|
|
737
|
+
sendForbidden(res);
|
|
738
|
+
return;
|
|
739
|
+
}
|
|
740
|
+
try {
|
|
741
|
+
const url = new URL(req.url || "/", "http://x");
|
|
742
|
+
const force = url.searchParams.get("refresh") === "1";
|
|
743
|
+
if (service.isEnabled()) {
|
|
744
|
+
if (force) await service.refresh(true);
|
|
745
|
+
else service.refresh(false).catch(() => {});
|
|
746
|
+
}
|
|
747
|
+
sendJson(res, 200, { ok: true, value: await service.stateValue() });
|
|
748
|
+
} catch (err) {
|
|
749
|
+
if (typeof ctx.logger?.warn === "function") {
|
|
750
|
+
ctx.logger.warn(`[dsh-message-actions] cost state failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
751
|
+
}
|
|
752
|
+
sendError(res, 500, "INTERNAL");
|
|
753
|
+
}
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
function makeCostCorrectionHandler(ctx, service) {
|
|
758
|
+
return async function handleCostCorrection(req, res) {
|
|
759
|
+
if (req.method !== "POST") {
|
|
760
|
+
drainRequest(req);
|
|
761
|
+
sendMethodNotAllowed(res, "POST");
|
|
762
|
+
return;
|
|
763
|
+
}
|
|
764
|
+
if (!isTrusted(req, ctx.webServer)) {
|
|
765
|
+
drainRequest(req);
|
|
766
|
+
sendForbidden(res);
|
|
767
|
+
return;
|
|
768
|
+
}
|
|
769
|
+
const contentType = (req.headers["content-type"] || "").split(";")[0].trim().toLowerCase();
|
|
770
|
+
if (contentType !== "application/json") {
|
|
771
|
+
drainRequest(req);
|
|
772
|
+
sendBadRequest(res);
|
|
773
|
+
return;
|
|
774
|
+
}
|
|
775
|
+
const body = await readJsonBody(req, res);
|
|
776
|
+
if (body === null) return;
|
|
777
|
+
if (!body || typeof body !== "object") {
|
|
778
|
+
sendBadRequest(res);
|
|
779
|
+
return;
|
|
780
|
+
}
|
|
781
|
+
const credit = validateCorrectionAmount(body.creditYuan);
|
|
782
|
+
const debit = validateCorrectionAmount(body.debitYuan);
|
|
783
|
+
if (!credit.ok || !debit.ok) {
|
|
784
|
+
sendError(res, 400, "INVALID_AMOUNT");
|
|
785
|
+
return;
|
|
786
|
+
}
|
|
787
|
+
try {
|
|
788
|
+
const saved = service.applyCorrection(credit.cents, debit.cents);
|
|
789
|
+
if (!saved.ok) {
|
|
790
|
+
sendError(res, 500, saved.error);
|
|
791
|
+
return;
|
|
792
|
+
}
|
|
793
|
+
sendJson(res, 200, { ok: true, value: await service.stateValue() });
|
|
794
|
+
} catch (err) {
|
|
795
|
+
if (typeof ctx.logger?.warn === "function") {
|
|
796
|
+
ctx.logger.warn(`[dsh-message-actions] correction failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
797
|
+
}
|
|
798
|
+
sendError(res, 500, "INTERNAL");
|
|
799
|
+
}
|
|
800
|
+
};
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
// ---------------------------------------------------------------------------
|
|
804
|
+
// 插件主体
|
|
805
|
+
// ---------------------------------------------------------------------------
|
|
806
|
+
|
|
807
|
+
function apply(ctx, config) {
|
|
808
|
+
ctx.effect(
|
|
809
|
+
() => ctx.webServer.register({
|
|
810
|
+
kind: "exact",
|
|
811
|
+
path: "/dsh-message-actions",
|
|
812
|
+
handler: makeActionHandler(ctx)
|
|
813
|
+
}),
|
|
814
|
+
"dsh-message-actions: write route"
|
|
815
|
+
);
|
|
816
|
+
ctx.effect(
|
|
817
|
+
() => ctx.webServer.register({
|
|
818
|
+
kind: "exact",
|
|
819
|
+
path: "/dsh-message-actions/messages",
|
|
820
|
+
handler: makeMessagesHandler(ctx)
|
|
821
|
+
}),
|
|
822
|
+
"dsh-message-actions: read route"
|
|
823
|
+
);
|
|
824
|
+
|
|
825
|
+
// —— 费用统计 ——
|
|
826
|
+
const cost = createCostService(ctx, config);
|
|
827
|
+
|
|
828
|
+
ctx.effect(
|
|
829
|
+
() => ctx.webServer.register({
|
|
830
|
+
kind: "exact",
|
|
831
|
+
path: "/dsh-message-actions/cost/state",
|
|
832
|
+
handler: makeCostStateHandler(ctx, cost)
|
|
833
|
+
}),
|
|
834
|
+
"dsh-message-actions: cost state route"
|
|
835
|
+
);
|
|
836
|
+
ctx.effect(
|
|
837
|
+
() => ctx.webServer.register({
|
|
838
|
+
kind: "exact",
|
|
839
|
+
path: "/dsh-message-actions/cost/correction",
|
|
840
|
+
handler: makeCostCorrectionHandler(ctx, cost)
|
|
841
|
+
}),
|
|
842
|
+
"dsh-message-actions: cost correction route"
|
|
843
|
+
);
|
|
844
|
+
|
|
845
|
+
ctx.effect(() => {
|
|
846
|
+
const offEvent = ctx.on("session/event", (session, event) => cost.onSessionEvent(session, event));
|
|
847
|
+
// 始终创建定时器,但每次触发都重新读开关:运行中关闭后不再取数,
|
|
848
|
+
// 重新打开后也无需重启即可恢复(默认开启时行为与旧版一致)。
|
|
849
|
+
const timer = setInterval(() => {
|
|
850
|
+
if (!cost.isEnabled()) return;
|
|
851
|
+
cost.refresh(false).catch(() => {});
|
|
852
|
+
}, COST_REFRESH_MIN_INTERVAL_MS);
|
|
853
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
854
|
+
return () => {
|
|
855
|
+
if (typeof offEvent === "function") offEvent();
|
|
856
|
+
clearInterval(timer);
|
|
857
|
+
cost.dispose();
|
|
858
|
+
};
|
|
859
|
+
}, "dsh-message-actions: cost service");
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
export { Config, apply, inject, name };
|