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/lib/store.cjs ADDED
@@ -0,0 +1,261 @@
1
+ // dsh-message-actions — 费用统计状态文件(宿主侧)。
2
+ //
3
+ // 只被宿主 index.mjs 引用,不进入客户端产物。
4
+ // 官方 @deepseek-ai/dsh-home-paths 与 @deepseek-ai/dsh-atomic-write 属内部包,
5
+ // 第三方插件不保证可解析,因此这里自带等价实现:
6
+ // - $DSH_HOME || ~/.dsh
7
+ // - 临时文件写入(mode 0600)→ rename 原子替换(Windows 重试)
8
+ //
9
+ // 恢复策略:
10
+ // - 文件超过 4MB:记录一次可诊断 warn,直接以默认状态原子重建并恢复可写;
11
+ // - 未超限但 JSON 解析失败:把原文件改名为 cost-state.bad-<时间戳>.json 保留现场;
12
+ // - 版本高于当前版本:按只读快照处理,不回写。
13
+
14
+ const fs = require("node:fs");
15
+ const os = require("node:os");
16
+ const path = require("node:path");
17
+
18
+ const STATE_VERSION = 1;
19
+ const FILE_NAME = "cost-state.json";
20
+ const DIR_NAME = "dsh-message-actions";
21
+ /** 状态文件读取上限:正常只有几 KB,超限视为异常文件,不再解析。 */
22
+ const MAX_STATE_BYTES = 4 * 1024 * 1024;
23
+
24
+ /** 展开 `~` / `~/` 前缀(不处理 Windows 的 %VAR%)。 */
25
+ function expandHome(value) {
26
+ const raw = String(value == null ? "" : value);
27
+ if (raw === "~") return os.homedir();
28
+ if (raw.startsWith("~/") || raw.startsWith("~\\")) {
29
+ return path.join(os.homedir(), raw.slice(2));
30
+ }
31
+ return raw;
32
+ }
33
+
34
+ /** DSH home:`$DSH_HOME` 优先,其次 `~/.dsh`。 */
35
+ function resolveDshHome(env) {
36
+ const source = env || process.env || {};
37
+ const override = typeof source.DSH_HOME === "string" ? source.DSH_HOME.trim() : "";
38
+ if (override) return path.resolve(expandHome(override));
39
+ return path.join(os.homedir(), ".dsh");
40
+ }
41
+
42
+ /** 状态文件绝对路径。 */
43
+ function resolveStatePath(env) {
44
+ return path.join(resolveDshHome(env), "plugins", DIR_NAME, FILE_NAME);
45
+ }
46
+
47
+ /** 空状态(§4.2 字段全集)。 */
48
+ function defaultState() {
49
+ return {
50
+ version: STATE_VERSION,
51
+ baselineBalanceCents: null,
52
+ lastBalanceCents: null,
53
+ lastBalanceAt: 0,
54
+ lastAttemptAt: 0,
55
+ lastRouting: null,
56
+ observedSpendTotalCents: 0,
57
+ dailySpendCents: {},
58
+ pendingAdjustmentCents: 0,
59
+ pendingAdjustmentAt: 0,
60
+ correctionCreditCents: 0,
61
+ correctionDebitCents: 0,
62
+ updatedAt: 0
63
+ };
64
+ }
65
+
66
+ function centsOrNull(value) {
67
+ return Number.isFinite(value) ? Math.round(value) : null;
68
+ }
69
+
70
+ function intOr(value, fallback) {
71
+ return Number.isFinite(value) ? Math.round(value) : fallback;
72
+ }
73
+
74
+ /**
75
+ * 只认已知字段并补默认值;丢弃未知字段,避免旧版本读写污染。
76
+ * `version` 高于当前版本时置 readOnly(调用方据此跳过写盘)。
77
+ */
78
+ function normalizeCostState(raw) {
79
+ const base = defaultState();
80
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
81
+ return { state: base, readOnly: false };
82
+ }
83
+ const version = intOr(raw.version, STATE_VERSION);
84
+ const readOnly = version > STATE_VERSION;
85
+ const daily = {};
86
+ if (raw.dailySpendCents && typeof raw.dailySpendCents === "object") {
87
+ for (const [key, value] of Object.entries(raw.dailySpendCents)) {
88
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(key)) continue;
89
+ if (!Number.isFinite(value)) continue;
90
+ daily[key] = Math.round(value);
91
+ }
92
+ }
93
+ const state = {
94
+ version: Math.min(version, STATE_VERSION),
95
+ baselineBalanceCents: centsOrNull(raw.baselineBalanceCents),
96
+ lastBalanceCents: centsOrNull(raw.lastBalanceCents),
97
+ lastBalanceAt: intOr(raw.lastBalanceAt, 0),
98
+ lastAttemptAt: intOr(raw.lastAttemptAt, 0),
99
+ lastRouting: typeof raw.lastRouting === "string" ? raw.lastRouting : null,
100
+ observedSpendTotalCents: intOr(raw.observedSpendTotalCents, 0),
101
+ dailySpendCents: daily,
102
+ pendingAdjustmentCents: intOr(raw.pendingAdjustmentCents, 0),
103
+ pendingAdjustmentAt: intOr(raw.pendingAdjustmentAt, 0),
104
+ correctionCreditCents: intOr(raw.correctionCreditCents, 0),
105
+ correctionDebitCents: intOr(raw.correctionDebitCents, 0),
106
+ updatedAt: intOr(raw.updatedAt, 0)
107
+ };
108
+ return { state, readOnly };
109
+ }
110
+
111
+ function badName(filePath) {
112
+ return filePath.replace(/\.json$/i, "") + ".bad-" + Date.now() + ".json";
113
+ }
114
+
115
+ /**
116
+ * 读取状态文件。读失败 / 损坏 → 改名保留现场并返回空状态。
117
+ * 超过 maxBytes(默认 4MB)的文件直接忽略,避免异常大文件解析阻塞宿主启动。
118
+ * @returns {{ state, readOnly, recovered: boolean }}
119
+ */
120
+ function loadCostState(filePath, logger, maxBytes) {
121
+ const warn = (msg) => {
122
+ if (logger && typeof logger.warn === "function") logger.warn(`[dsh-message-actions] ${msg}`);
123
+ };
124
+ const limit = Number.isFinite(maxBytes) && maxBytes > 0 ? maxBytes : MAX_STATE_BYTES;
125
+ let text;
126
+ try {
127
+ const stat = fs.statSync(filePath);
128
+ if (stat.size > limit) {
129
+ // 超限文件不解析,直接以默认状态重建;不生成 .bad 副本,也不进入只读。
130
+ // 警告保留体积与阈值,便于用户日后排查(不弹用户可见错误框)。
131
+ warn(`cost state too large (${stat.size} bytes, limit ${limit}), rebuilt with defaults`);
132
+ const state = defaultState();
133
+ try {
134
+ saveCostState(filePath, state);
135
+ } catch (err) {
136
+ // 重建写盘失败不阻塞启动:内存状态仍可正常记账,下次 persist 会重试。
137
+ warn(`rebuilt cost state write failed: ${err instanceof Error ? err.message : String(err)}`);
138
+ }
139
+ return { state, readOnly: false, recovered: true };
140
+ }
141
+ text = fs.readFileSync(filePath, "utf8");
142
+ } catch (err) {
143
+ if (err && err.code === "ENOENT") return { state: defaultState(), readOnly: false, recovered: false };
144
+ warn(`read cost state failed: ${err instanceof Error ? err.message : String(err)}`);
145
+ return { state: defaultState(), readOnly: false, recovered: false };
146
+ }
147
+ try {
148
+ const parsed = JSON.parse(text);
149
+ const { state, readOnly } = normalizeCostState(parsed);
150
+ return { state, readOnly, recovered: false };
151
+ } catch (err) {
152
+ try {
153
+ fs.renameSync(filePath, badName(filePath));
154
+ warn(`cost state corrupted, moved aside: ${err instanceof Error ? err.message : String(err)}`);
155
+ } catch {
156
+ /* 改名失败也不阻塞启动 */
157
+ }
158
+ return { state: defaultState(), readOnly: false, recovered: true };
159
+ }
160
+ }
161
+
162
+ /**
163
+ * 同步退避等待:优先 Atomics.wait(不占 CPU),不可用时才短暂自旋。
164
+ * 仅在 rename 因文件占用短暂失败时使用,单次 ≤ 100ms。
165
+ */
166
+ function waitBriefly(ms) {
167
+ try {
168
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
169
+ return;
170
+ } catch {
171
+ /* 环境不支持 Atomics.wait,退回自旋 */
172
+ }
173
+ const until = Date.now() + ms;
174
+ while (Date.now() < until) {
175
+ /* busy wait(兜底,总时长 ≤ 100ms) */
176
+ }
177
+ }
178
+
179
+ /**
180
+ * 原子写:同目录临时文件(0600)→ rename 覆盖。
181
+ * 失败时删除临时文件并把异常抛给调用方(调用方只记 warn,保留内存状态)。
182
+ */
183
+ function saveCostState(filePath, state) {
184
+ const dir = path.dirname(filePath);
185
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
186
+ const tmp = path.join(dir, "." + path.basename(filePath) + "." + process.pid + "." + Date.now() + ".tmp");
187
+ const body = JSON.stringify(state, null, 2) + "\n";
188
+ let handle;
189
+ try {
190
+ handle = fs.openSync(tmp, "wx", 0o600);
191
+ fs.writeSync(handle, body, null, "utf8");
192
+ fs.fsyncSync(handle);
193
+ fs.closeSync(handle);
194
+ handle = undefined;
195
+ } catch (err) {
196
+ if (handle !== undefined) {
197
+ try {
198
+ fs.closeSync(handle);
199
+ } catch {
200
+ /* ignore */
201
+ }
202
+ }
203
+ try {
204
+ fs.unlinkSync(tmp);
205
+ } catch {
206
+ /* ignore */
207
+ }
208
+ throw err;
209
+ }
210
+ for (let i = 0; i < 5; i += 1) {
211
+ try {
212
+ fs.renameSync(tmp, filePath);
213
+ return;
214
+ } catch (err) {
215
+ if (i === 4) {
216
+ try {
217
+ fs.unlinkSync(tmp);
218
+ } catch {
219
+ /* ignore */
220
+ }
221
+ throw err;
222
+ }
223
+ // Windows 上目标文件被占用时 rename 会短暂失败,退避重试。
224
+ // 优先 Atomics.wait(宿主为 Node 主进程,可阻塞但不占 CPU);不可用时才短暂自旋。
225
+ waitBriefly(20 + i * 20);
226
+ }
227
+ }
228
+ }
229
+
230
+ /**
231
+ * 把内存状态写入磁盘,并返回结构化结果(不再吞掉失败)。
232
+ * 只读模式(状态文件版本高于当前版本)与写入异常都返回 `{ ok:false, error }`,
233
+ * 供路由据此回 500,避免客户端把未落盘的校正当成已保存。
234
+ * @returns {{ ok: true } | { ok: false, error: 'READ_ONLY' | 'WRITE_FAILED' }}
235
+ */
236
+ function persistCostState(filePath, state, readOnly, logger) {
237
+ if (readOnly) return { ok: false, error: "READ_ONLY" };
238
+ try {
239
+ saveCostState(filePath, state);
240
+ return { ok: true };
241
+ } catch (err) {
242
+ const message = err instanceof Error ? err.message : String(err);
243
+ if (logger && typeof logger.warn === "function") {
244
+ logger.warn(`[dsh-message-actions] write cost state failed: ${message}`);
245
+ }
246
+ return { ok: false, error: "WRITE_FAILED" };
247
+ }
248
+ }
249
+
250
+ module.exports = {
251
+ STATE_VERSION,
252
+ MAX_STATE_BYTES,
253
+ expandHome,
254
+ resolveDshHome,
255
+ resolveStatePath,
256
+ defaultState,
257
+ normalizeCostState,
258
+ loadCostState,
259
+ saveCostState,
260
+ persistCostState
261
+ };
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Messages & Cost",
4
+ "description": "Recall, delete, and delete-to-end messages; multi-select share and export; per-answer statistics; DeepSeek balance, daily spend, and per-turn cost."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "消息费用",
4
+ "description": "撤回、删除、删至末尾;多选分享与导出对话;回答统计;DeepSeek 账户余额、日用与单次费用统计。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "dsh-message-actions",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.1",
4
+ "description": "消息费用:撤回、删除、删至末尾、分享、导出、回答统计与 DeepSeek 费用统计(DSH 插件)。",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/aijacko/dsh-message-actions.git"
10
+ },
11
+ "homepage": "https://github.com/aijacko/dsh-message-actions#readme",
12
+ "keywords": [
13
+ "dsh",
14
+ "dsh-plugin",
15
+ "deepseek-harness",
16
+ "deepseek",
17
+ "plugin"
18
+ ],
19
+ "publishConfig": {
20
+ "registry": "https://registry.npmjs.org",
21
+ "access": "public"
22
+ },
23
+ "exports": {
24
+ ".": "./lib/index.js",
25
+ "./client": "./lib/client.js",
26
+ "./locale/*.json": "./locale/*.json",
27
+ "./icon": "./icon.svg"
28
+ },
29
+ "scripts": {
30
+ "build": "node build.mjs",
31
+ "test": "node test/check.mjs",
32
+ "prepack": "node build.mjs"
33
+ },
34
+ "files": [
35
+ "lib/index.js",
36
+ "lib/client.js",
37
+ "lib/shared.cjs",
38
+ "lib/store.cjs",
39
+ "lib/http.cjs",
40
+ "cordis.patch.yml",
41
+ "locale/*.json",
42
+ "icon.svg"
43
+ ],
44
+ "dsh": {
45
+ "bundle": {
46
+ "patch": "./cordis.patch.yml"
47
+ },
48
+ "client": {
49
+ "platform": "web",
50
+ "immediately": true,
51
+ "inject": [
52
+ "@deepseek-ai/dsh-client-locale",
53
+ "@deepseek-ai/dsh-client-ui-conversation",
54
+ "@deepseek-ai/dsh-client-ui-settings",
55
+ "@deepseek-ai/dsh-client-ui-sidebar"
56
+ ]
57
+ }
58
+ }
6
59
  }