@mrrisega/dsh-remote 0.7.12-beta.6 → 0.8.0

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.
@@ -0,0 +1,302 @@
1
+ /**
2
+ * im-commands — 三家 IM 机器人(企微 / 钉钉 / 飞书)共用的**命令层**(2026-11-08)。
3
+ *
4
+ * 业主实测:在钉钉里发 `/ls` 期望列会话,但当时没有命令层 → `/ls` 被当成 prompt 转给了模型。
5
+ * 命令层把这类「控制类消息」在**进模型之前**拦下、自己执行并回复;解析器/文案/能力门禁三家共用,
6
+ * 各通道只负责把回复发出去(企微被动回复 / 钉钉 sessionWebhook / 飞书 im/v1/messages)。
7
+ *
8
+ * 命令表(能力门禁复用 `WECHAT_CAPABILITY_TABLE`,与会员升级文案同口径):
9
+ * | 命令 | 能力 | 免费 | 说明 |
10
+ * | /help | 无 | ✅ | 列出全部命令(含会员命令标注) |
11
+ * | /status | 无 | ✅ | 连接状态 + 当前会话 + 本月剩余指令 |
12
+ * | /stop | 无 | ✅ | 急停当前任务(安全阀必须免费、立即生效)|
13
+ * | /ls | sessions | ❌ | 最近 ≤10 个会话(标题/索引/当前标记) |
14
+ * | /use <N> | sessions | ❌ | 切换当前绑定会话(写配置 sessionId) |
15
+ * | /unbind | 无 | ✅ | 解绑/退订本会话推送(合规:随时可退订)|
16
+ *
17
+ * 未命中的 `/xxx`:回帮助提示(含"未知命令"),**绝不转给模型**。
18
+ * 回复一律用纯文本列表(不用 Markdown 表格;各通道发送前还会走 im-format 兜底)。
19
+ */
20
+
21
+ import path from "node:path";
22
+
23
+ import { WECHAT_CAPABILITY_TABLE, grantsCap } from "./wechat-runtime.mjs";
24
+ import { IM_BOTS_FILE, atomicWriteJson, readJsonFile } from "./wecom-bot.mjs";
25
+
26
+ /** 命令表(顺序即 /help 展示顺序)。`free` 只是文档标记;真正门禁看 caps。 */
27
+ export const IM_COMMANDS = Object.freeze([
28
+ Object.freeze({ name: "/help", caps: Object.freeze([]), free: true, usage: "/help", summary: "查看命令" }),
29
+ Object.freeze({ name: "/status", caps: Object.freeze([]), free: true, usage: "/status", summary: "连接状态 / 当前会话 / 本月额度" }),
30
+ Object.freeze({ name: "/stop", caps: Object.freeze([]), free: true, usage: "/stop", summary: "急停当前任务" }),
31
+ Object.freeze({ name: "/ls", caps: Object.freeze(["sessions"]), free: false, usage: "/ls", summary: "列出最近会话(会员)" }),
32
+ Object.freeze({ name: "/use", caps: Object.freeze(["sessions"]), free: false, usage: "/use <序号>", summary: "切换当前会话(会员)" }),
33
+ Object.freeze({ name: "/unbind", caps: Object.freeze([]), free: true, usage: "/unbind", summary: "解绑本会话推送(随时可退订)" })
34
+ ]);
35
+
36
+ /** 会话标题截断(按码点,避免切坏 emoji/中文)。 */
37
+ export function truncateTitle(title, max = 24) {
38
+ const s = String(title == null ? "" : title).replace(/\s+/g, " ").trim();
39
+ if (!s) return "";
40
+ const chars = Array.from(s);
41
+ return chars.length <= max ? s : `${chars.slice(0, Math.max(1, max - 1)).join("")}…`;
42
+ }
43
+
44
+ function pad2(n) { return String(n).padStart(2, "0"); }
45
+ function fmtTime(at) {
46
+ const n = Number(at) || 0;
47
+ if (!n) return "";
48
+ try {
49
+ const d = new Date(n);
50
+ return `${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
51
+ } catch { return ""; }
52
+ }
53
+
54
+ /**
55
+ * 解析一条消息是否为命令。
56
+ * @returns {{name:string, arg:string, unknown?:boolean, raw:string}|null} null = 普通文本(照旧转给模型)
57
+ */
58
+ export function parseImCommand(text) {
59
+ const raw = String(text == null ? "" : text).trim();
60
+ if (!raw.startsWith("/")) return null;
61
+ const m = /^\/([a-zA-Z]*)(?:\s+([^\s]+))?(?:\s+([\s\S]*))?$/.exec(raw);
62
+ if (!m) return { name: "/", arg: "", unknown: true, raw };
63
+ const word = String(m[1] || "").toLowerCase();
64
+ return { name: word ? `/${word}` : "/", arg: String(m[2] || "").toLowerCase(), rest: m[3] || "", unknown: !word, raw };
65
+ }
66
+
67
+ /** 当前 caps 是否具备该命令要求(点号前缀规则,与会员表同源)。 */
68
+ export function commandAllowed(command, caps) {
69
+ const list = Array.isArray(caps) ? caps : [];
70
+ return (command.caps || []).every((c) => grantsCap(list, c));
71
+ }
72
+
73
+ function appPromo(ctx) {
74
+ const base = String((ctx && ctx.appUrl) || "").trim().replace(/\/+$/, "");
75
+ if (!base) return "";
76
+ return `${base}/promo`;
77
+ }
78
+
79
+ /** /help:列出全部命令(免费/会员标注;免费档会提示哪些需要会员)。 */
80
+ export function helpText(ctx = {}) {
81
+ const caps = Array.isArray(ctx.caps) ? ctx.caps : [];
82
+ const lines = ["📋 可用命令(命令不会发给模型,直接执行)", ""];
83
+ for (const cmd of IM_COMMANDS) {
84
+ const allowed = commandAllowed(cmd, caps);
85
+ const mark = cmd.free ? "" : allowed ? "(会员)" : "(会员·当前档不可用)";
86
+ lines.push(`${cmd.usage} — ${cmd.summary}${mark}`);
87
+ }
88
+ lines.push("", "免费档可用的命令:/help /status /stop /unbind(急停与退订永远免费)。");
89
+ if (caps.includes("sessions")) lines.push("你的档位已包含会话管理(/ls、/use)。");
90
+ return lines.join("\n");
91
+ }
92
+
93
+ /** 未知 /xxx:不转给模型,回"未知命令 + 帮助提示"。 */
94
+ export function unknownCommandText(cmd, ctx = {}) {
95
+ const name = cmd && cmd.name && cmd.name !== "/" ? cmd.name : cmd && cmd.raw ? String(cmd.raw).split(/\s+/)[0] : "/?";
96
+ return `未知命令:${name}\n\n${helpText(ctx)}`;
97
+ }
98
+
99
+ /** 会员功能被拦:与现有升级文案同口径(能做什么/去哪升级),只是更简短。 */
100
+ export function upgradeText(commandName, ctx = {}) {
101
+ const promo = appPromo(ctx);
102
+ const lines = [
103
+ `🔒 ${commandName} 是会员功能(列出/切换会话)`,
104
+ "",
105
+ "免费可用:/help /status /stop /unbind(急停、退订永远免费)",
106
+ "升级 Pro:指令不限量、可开新任务、可切换/多会话"
107
+ ];
108
+ if (promo) lines.push(`👉 ${promo}`);
109
+ return lines.join("\n");
110
+ }
111
+
112
+ /** /status:与状态文件同源的连接/会话/额度摘要。 */
113
+ export async function statusText(ctx = {}) {
114
+ const snap = typeof ctx.statusSnapshot === "function" ? await ctx.statusSnapshot() : (ctx.status || {});
115
+ const s = snap && typeof snap === "object" ? snap : {};
116
+ const channel = String(s.channelLabel || ctx.channelLabel || "IM");
117
+ const connected = s.connected === true;
118
+ const authed = s.authenticated === true;
119
+ const state = String(s.state || (connected ? "connected" : "idle"));
120
+ const stateLine = connected
121
+ ? (authed ? "✅ 已连接(认证通过)" : "✅ 已连接(等待认证)")
122
+ : `⚠️ 未连接(${state}${s.lastError ? `:${truncateTitle(s.lastError, 40)}` : ""})`;
123
+ const conv = truncateTitle(s.currentSessionTitle || s.boundSessionTitle || "", 24) || "未选择";
124
+ const convId = String(s.currentSessionId || s.boundSessionId || "");
125
+ const shortId = convId ? convId.replace(/^session-/, "").slice(0, 8) : "";
126
+ const limit = Number(s.messagesPerMonth) || 0;
127
+ const used = Number(s.usage && s.usage.messages) || 0;
128
+ const quotaLine = limit > 0
129
+ ? `本月指令:已用 ${used}/${limit}${s.tier ? `(${s.tier})` : ""}`
130
+ : `本月指令:不限${s.tier ? `(${s.tier})` : ""}`;
131
+ const lines = [
132
+ "📊 连接状态",
133
+ `· 通道:${channel}`,
134
+ `· 状态:${stateLine}`,
135
+ `· 当前会话:${conv}${shortId ? `(#${shortId})` : ""}`,
136
+ `· ${quotaLine}`
137
+ ];
138
+ if (s.remainingMessages !== null && s.remainingMessages !== undefined && limit > 0) {
139
+ lines.push(`· 剩余:${Number(s.remainingMessages) || 0} 条`);
140
+ }
141
+ return lines.join("\n");
142
+ }
143
+
144
+ /** ctx 的 currentSessionId/currentSessionTitle 允许函数或字符串(各通道实现风格不一)。 */
145
+ function resolveMaybeFn(value) {
146
+ try { return typeof value === "function" ? String(value() || "") : String(value || ""); } catch { return ""; }
147
+ }
148
+
149
+ /** 统一取最近会话列表(ctx.sessions 返回 [{sessionId,title,updatedAt,running}])。 */
150
+ export async function listSessions(ctx = {}) {
151
+ if (typeof ctx.sessions !== "function") return [];
152
+ const rows = await ctx.sessions();
153
+ if (!Array.isArray(rows)) return [];
154
+ return rows
155
+ .filter((r) => r && typeof r.sessionId === "string" && r.sessionId)
156
+ .slice(0, 10)
157
+ .map((r) => ({
158
+ sessionId: r.sessionId,
159
+ title: String(r.title || r.sessionTitle || "").trim() || r.sessionId,
160
+ updatedAt: Number(r.updatedAt) || 0,
161
+ running: r.running === true
162
+ }));
163
+ }
164
+
165
+ /** /ls:≤10 个会话,标题截断 24 + 索引 + 当前标记 + 更新时间。 */
166
+ export async function lsText(ctx = {}) {
167
+ const rows = await listSessions(ctx);
168
+ const current = resolveMaybeFn(ctx.currentSessionId) || String(ctx.activeSessionId || "");
169
+ if (!rows.length) {
170
+ return "📂 最近没有可列出的会话。\n\n先在电脑的 DeepSeek Harness 里打开/运行一个会话,再发 /ls。";
171
+ }
172
+ const lines = ["📂 最近会话(最多 10 个)", ""];
173
+ rows.forEach((r, i) => {
174
+ const isCurrent = r.sessionId === current;
175
+ const time = fmtTime(r.updatedAt);
176
+ const marks = [isCurrent ? "(当前)" : "", r.running ? "· 运行中" : "", time ? `· ${time}` : ""].filter(Boolean).join(" ");
177
+ lines.push(`${i + 1}. ${truncateTitle(r.title, 24)}${marks ? ` ${marks}` : ""}`);
178
+ });
179
+ lines.push("", "回复 /use <序号> 切换会话(例如 /use 1)。");
180
+ return { text: lines.join("\n"), rows };
181
+ }
182
+
183
+ /** /use <N>:切换当前绑定会话(写配置 sessionId/sessionTitle)。 */
184
+ export async function useText(ctx = {}, arg = "") {
185
+ const rows = await listSessions(ctx);
186
+ if (!rows.length) return "现在没有可切换的会话。先在电脑上打开一个会话,再发 /ls 看看。";
187
+ const raw = String(arg || "").trim();
188
+ if (!raw) return "用法:/use <序号>(先发 /ls 查看会话列表,例如 /use 1)";
189
+ const n = Number(raw);
190
+ if (!Number.isInteger(n) || n < 1 || n > rows.length) {
191
+ return `序号超出范围:当前列表是 1-${rows.length}。先发 /ls 查看列表,再用 /use <序号> 切换。`;
192
+ }
193
+ const pick = rows[n - 1];
194
+ if (typeof ctx.switchSession !== "function") return "当前通道还不支持切换会话(订阅器未就绪),请在电脑上切换。";
195
+ const r = await ctx.switchSession({ sessionId: pick.sessionId, title: pick.title });
196
+ if (!r || r.ok !== true) {
197
+ return `切换失败:${truncateTitle((r && (r.message || r.reason)) || "未知错误", 60)}。可以到电脑上切换,或稍后再试。`;
198
+ }
199
+ return `✅ 已切换到 #${n} ${truncateTitle(pick.title, 24) || pick.sessionId}`;
200
+ }
201
+
202
+ /** /stop:急停当前任务(免费、立即生效;回执明确)。 */
203
+ export async function stopText(ctx = {}) {
204
+ const current = resolveMaybeFn(ctx.currentSessionId) || String(ctx.activeSessionId || "");
205
+ if (!current) return "当前没有正在运行的会话,无需急停。";
206
+ if (typeof ctx.cancelSession !== "function") return "急停失败:后台还没连上事件通道(订阅器未就绪)。请在电脑上停止任务。";
207
+ const title = truncateTitle(resolveMaybeFn(ctx.currentSessionTitle) || ctx.activeSessionTitle || current, 24);
208
+ let r;
209
+ try { r = await ctx.cancelSession({ sessionId: current }); } catch (e) {
210
+ r = { ok: false, message: e && e.message ? e.message : String(e) };
211
+ }
212
+ if (r && r.ok === true) return `⏹ 已急停:${title}(已发送中止,正在停止当前任务)`;
213
+ return `⏹ 急停请求已发出,但没收到确认:${truncateTitle((r && (r.message || r.reason)) || "未知错误", 60)}。请到电脑上确认任务是否已停。`;
214
+ }
215
+
216
+ /** /unbind:解绑本会话推送(免费;合规要求任何人可退订)。 */
217
+ export async function unbindText(ctx = {}) {
218
+ if (typeof ctx.unbind !== "function") return "解绑失败:当前通道暂不支持解绑,请在电脑的「远程访问」里关闭该通道。";
219
+ let r;
220
+ try { r = await ctx.unbind(); } catch (e) { r = { ok: false, message: e && e.message ? e.message : String(e) }; }
221
+ if (r && r.ok === true) return "✅ 已解绑:这台电脑不再向本会话推送通知。想重新接收,发任意消息即可重新绑定。";
222
+ return `解绑失败:${truncateTitle((r && (r.message || r.reason)) || "未知错误", 60)}`;
223
+ }
224
+
225
+ /**
226
+ * 执行一条命令(**命中即返回 handled:true,调用方直接回复 text 并 return,绝不进模型**)。
227
+ *
228
+ * @param {{text:string, ctx:object}} args
229
+ * ctx 契约(各通道按自己能力提供,缺的降级):
230
+ * · caps[]、tier、appUrl、channelLabel
231
+ * · sessions(): Promise<[{sessionId,title,updatedAt,running}]>
232
+ * · currentSessionId(): string、currentSessionTitle?: string、activeSessionId?
233
+ * · cancelSession({sessionId})、switchSession({sessionId,title})、unbind()
234
+ * · statusSnapshot(): Promise<{connected,authenticated,state,lastError,tier,usage,messagesPerMonth,remainingMessages,currentSessionTitle,currentSessionId}>
235
+ * @returns {Promise<{handled:boolean, ok?:boolean, gated?:boolean, command?:string, text?:string, rows?:Array}>}
236
+ */
237
+ export async function executeImCommand({ text, ctx = {} } = {}) {
238
+ const cmd = parseImCommand(text);
239
+ if (!cmd) return { handled: false };
240
+ const caps = Array.isArray(ctx.caps) ? ctx.caps : [];
241
+ const known = IM_COMMANDS.find((c) => c.name === cmd.name);
242
+ if (!known) return { handled: true, ok: false, command: cmd.name, text: unknownCommandText(cmd, ctx) };
243
+ if (!commandAllowed(known, caps)) {
244
+ return { handled: true, ok: false, gated: true, command: known.name, text: upgradeText(known.name, ctx) };
245
+ }
246
+ try {
247
+ switch (known.name) {
248
+ case "/help":
249
+ return { handled: true, ok: true, command: known.name, text: helpText(ctx) };
250
+ case "/status":
251
+ return { handled: true, ok: true, command: known.name, text: await statusText(ctx) };
252
+ case "/stop":
253
+ return { handled: true, ok: true, command: known.name, text: await stopText(ctx) };
254
+ case "/unbind":
255
+ return { handled: true, ok: true, command: known.name, text: await unbindText(ctx) };
256
+ case "/ls": {
257
+ const r = await lsText(ctx);
258
+ return { handled: true, ok: true, command: known.name, text: typeof r === "string" ? r : r.text, rows: typeof r === "string" ? [] : r.rows };
259
+ }
260
+ case "/use":
261
+ return { handled: true, ok: true, command: known.name, text: await useText(ctx, cmd.arg) };
262
+ default:
263
+ return { handled: true, ok: false, command: known.name, text: unknownCommandText(cmd, ctx) };
264
+ }
265
+ } catch (e) {
266
+ return {
267
+ handled: true,
268
+ ok: false,
269
+ command: known.name,
270
+ text: `命令执行失败:${truncateTitle(e && e.message ? e.message : e, 60)}。可以到电脑上看一眼,或稍后再试。`
271
+ };
272
+ }
273
+ }
274
+
275
+ /** 能力表(导出方便各通道显示"会员功能"标记;单一真相源)。 */
276
+ export const IM_COMMAND_CAPABILITY_TABLE = WECHAT_CAPABILITY_TABLE;
277
+
278
+ /**
279
+ * 切换会话时写 `im-bots.json` 对应通道的 `sessionId/sessionTitle`(0600 原子写,保留其它段)。
280
+ * 各通道 controller 会热更新并在下一次入站用新会话。
281
+ */
282
+ export function writeImBotsSession(relayDir, channel, { sessionId, sessionTitle } = {}) {
283
+ const dir = String(relayDir || "");
284
+ const ch = String(channel || "");
285
+ if (!dir || !ch) return { ok: false, reason: "no_target" };
286
+ const sid = String(sessionId || "").trim();
287
+ if (!sid) return { ok: false, reason: "no_session_id" };
288
+ try {
289
+ const file = path.join(dir, IM_BOTS_FILE);
290
+ const prev = readJsonFile(file);
291
+ const base = prev && typeof prev === "object" && !Array.isArray(prev) ? prev : {};
292
+ const cur = base[ch] && typeof base[ch] === "object" ? base[ch] : {};
293
+ atomicWriteJson(file, {
294
+ ...base,
295
+ version: 1,
296
+ [ch]: { ...cur, sessionId: sid, sessionTitle: truncateTitle(sessionTitle || "", 60) }
297
+ }, { onWarn: () => { /* 静默 */ } });
298
+ return { ok: true };
299
+ } catch (e) {
300
+ return { ok: false, reason: e && e.message ? e.message : String(e) };
301
+ }
302
+ }
@@ -53,6 +53,9 @@ import WebSocket from "ws";
53
53
  import { createEventSubscriber, NODE_KINDS } from "./dsh-events.mjs";
54
54
  // 通道感知格式化(2026-11-08:企微/钉钉 markdown 不支持表格,发前统一适配;飞书/微信各有分支)
55
55
  import { formatForChannel } from "./im-format.mjs";
56
+ // 命令层(2026-11-08):/help /status /stop /ls /use /unbind 在**进模型前**拦下执行;
57
+ // 解析/文案/能力门禁三家共用(与会员升级文案同口径)。
58
+ import { executeImCommand, writeImBotsSession } from "./im-commands.mjs";
56
59
  // 会员能力表 = **单一真相源**:直接复用微信通道那套(WECHAT_CAPABILITY_TABLE / limitsFor / grantsCap),
57
60
  // 不另造一套。企微/飞书/钉钉将来都套同一套判定(见 research/.../im-channel-membership-design.md)。
58
61
  import {
@@ -716,8 +719,8 @@ export function createWecomBot(options = {}) {
716
719
  const approvalCardTtlMs = positiveNumber(options.approvalCardTtlMs, APPROVAL_CARD_TTL_MS);
717
720
  const onApprovalDecision = typeof options.onApprovalDecision === "function" ? options.onApprovalDecision : null;
718
721
  // 会话可选绑定(task-24):配置固定的会话(空 = 跟随活跃会话)
719
- const configuredSessionId = String(options.configuredSessionId || "").trim();
720
- const configuredSessionTitle = truncateText(options.configuredSessionTitle || "", 60);
722
+ let configuredSessionId = String(options.configuredSessionId || "").trim();
723
+ let configuredSessionTitle = truncateText(options.configuredSessionTitle || "", 60);
721
724
  // ── 会员判定(2026-11-07 业主拍板:通知免费、审批免费、互动半阉割)──
722
725
  // capsProvider 由 bridge 注入(复用微信通道的 resolveWechatTier:字符串档位或 {plan,caps,limits,rev});
723
726
  // 拿不到 / 未注入 → **按 free fail-closed**。
@@ -1367,8 +1370,87 @@ export function createWecomBot(options = {}) {
1367
1370
  }
1368
1371
 
1369
1372
  /** 把入站文本转给 DSH 会话(尽力,失败给用户一句人话)。 */
1373
+ /**
1374
+ * 命令层(三家共用 `im-commands.mjs`):命中返回 true(已回复,调用方直接 return)。
1375
+ * 回复走被动回复/主动推送(replyText),不经过模型、不计额度。
1376
+ */
1377
+ async function handleCommand(frame, info) {
1378
+ const text = String((info && info.text) || "");
1379
+ if (!/^\s*\//.test(text)) return false; // 快路径:非命令不构造 ctx
1380
+ const cmd = await executeImCommand({
1381
+ text,
1382
+ ctx: {
1383
+ caps: capsNow(),
1384
+ tier: tierNow(),
1385
+ appUrl,
1386
+ channelLabel: "企业微信",
1387
+ sessions: async () => {
1388
+ try { await refreshSessions({ force: true }); } catch { /* 忽略 */ }
1389
+ return sessionList.map((x) => ({ sessionId: x.id, title: x.title, updatedAt: x.updatedAt, running: false }));
1390
+ },
1391
+ currentSessionId: () => {
1392
+ const known = boundSessionId || activeSession.id || "";
1393
+ if (known) return known;
1394
+ if (configuredSessionId && canCap("sessions")) return configuredSessionId;
1395
+ if (sessionList.length) return sessionList[0].id;
1396
+ const sub = subscriber;
1397
+ try {
1398
+ if (sub && typeof sub.sessions === "function") {
1399
+ const ids = sub.sessions();
1400
+ if (Array.isArray(ids) && ids.length) return String(ids[0]);
1401
+ }
1402
+ } catch { /* 忽略 */ }
1403
+ return "";
1404
+ },
1405
+ currentSessionTitle: () => titleOfSession(boundSessionId || activeSession.id, activeSession.title || ""),
1406
+ cancelSession: async ({ sessionId }) => {
1407
+ const sub = subscriber;
1408
+ if (!sub || typeof sub.cancelSession !== "function") return { ok: false, message: "订阅器未就绪" };
1409
+ try {
1410
+ const r = await sub.cancelSession({ sessionId });
1411
+ return r && typeof r === "object" ? r : { ok: Boolean(r) };
1412
+ } catch (e) { return { ok: false, message: e && e.message ? e.message : String(e) }; }
1413
+ },
1414
+ switchSession: async ({ sessionId, title }) => {
1415
+ const r = writeImBotsSession(relayDir, "wecom", { sessionId, sessionTitle: title });
1416
+ if (r.ok) {
1417
+ configuredSessionId = sessionId;
1418
+ configuredSessionTitle = truncateText(title || "", 60);
1419
+ writeStatus();
1420
+ }
1421
+ return r;
1422
+ },
1423
+ unbind: async () => {
1424
+ state.boundChatId = "";
1425
+ writeStatus();
1426
+ return { ok: true };
1427
+ },
1428
+ statusSnapshot: async () => ({
1429
+ connected: state.connected === true,
1430
+ authenticated: state.authenticated === true,
1431
+ state: state.connected ? "connected" : "idle",
1432
+ lastError: state.lastError || "",
1433
+ tier: tierNow(),
1434
+ usage: { month: monthKey(), messages: usageThisMonth() },
1435
+ messagesPerMonth: messageLimitNow(),
1436
+ remainingMessages: messageLimitNow() ? Math.max(0, messageLimitNow() - usageThisMonth()) : null,
1437
+ currentSessionId: boundSessionId || activeSession.id || "",
1438
+ currentSessionTitle: titleOfSession(boundSessionId || activeSession.id, activeSession.title || "")
1439
+ })
1440
+ }
1441
+ });
1442
+ if (!cmd || !cmd.handled) return false;
1443
+ replyText(frame, cmd.text);
1444
+ emitter.emit("command", { ...info, command: cmd.command, ok: cmd.ok === true, gated: cmd.gated === true });
1445
+ log.info(`命令 ${cmd.command}${cmd.gated ? "(会员闸拦截)" : ""} 已回复(不转模型)`);
1446
+ return true;
1447
+ }
1448
+
1370
1449
  async function dispatchInbound(frame, info) {
1371
1450
  const sub = subscriber;
1451
+ // ⓪ 命令层:命中即执行并回复,**绝不进模型**,也不计入额度(/stop、/unbind 永远免费)
1452
+ const cmd = await handleCommand(frame, info);
1453
+ if (cmd) return;
1372
1454
  // ① 会员闸(通知/审批免费;派活受能力与月度额度约束,fail-closed)
1373
1455
  const gated = await membershipGate(frame, info);
1374
1456
  if (gated) return;
@@ -149,7 +149,7 @@ function findDepWs(startDir) {
149
149
  * 漏同步就会出现「入口脚本在、依赖不在」的半装运行时(插件半据此判定「运行环境已就绪」,
150
150
  * 却永远起不来 bridge —— 2026-09-23 用户反馈的现场)。`src/channel-ref.mjs` 同理(本安装器也 import)。
151
151
  */
152
- const RUNTIME_CLIENT_FILES = ["mobile-adapter.mjs", "dsh-bridge.mjs", "e2ee-shim.mjs", "e2ee-client.mjs", "e2ee-shim-script.js", "mobile-adapter.test.mjs", "wechat-channel.mjs", "dsh-events.mjs", "wechat-runtime.mjs", "wecom-bot.mjs", "im-format.mjs", "dingtalk-bot.mjs", "dingtalk-auth.mjs", "feishu-bot.mjs", "src/lifecycle.mjs", "src/channel-ref.mjs"];
152
+ const RUNTIME_CLIENT_FILES = ["mobile-adapter.mjs", "dsh-bridge.mjs", "e2ee-shim.mjs", "e2ee-client.mjs", "e2ee-shim-script.js", "mobile-adapter.test.mjs", "wechat-channel.mjs", "dsh-events.mjs", "wechat-runtime.mjs", "wecom-bot.mjs", "im-format.mjs", "dingtalk-bot.mjs", "dingtalk-auth.mjs", "im-commands.mjs", "feishu-bot.mjs", "src/lifecycle.mjs", "src/channel-ref.mjs"];
153
153
 
154
154
  /**
155
155
  * 把"客户端脚本"补齐到配置目录。