dsh-plugin-mesh 0.5.7 → 0.5.9

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/cordis.patch.yml CHANGED
@@ -53,6 +53,12 @@
53
53
  # 若网络不完全可信(合租/公司/有访客设备),改成 true 再对齐配对码。
54
54
  requirePairing: false
55
55
 
56
+ # 陌生设备第一次派活时,本机先弹一次确认(默认开)。
57
+ # 允许过的设备写进 state.json 的 approvedPeers,同一台不再问。
58
+ # 开了 requirePairing 就不再重复问 —— 配对码是更强的信任动作。
59
+ # 想让内网完全免打扰(自己家几台机器)就改成 false。
60
+ requireApproval: true
61
+
56
62
  # 对端任务在本机新建会话时的选项
57
63
  agentPreset: standard
58
64
  # 对端派来的是外部不可信输入,默认不给 danger-full-access
@@ -61,6 +67,10 @@
61
67
  # 留空会回退到用户主目录 —— 那意味着对端任务在整个家目录里跑,建议指定。
62
68
  workspaceRoot: ''
63
69
 
70
+ # 聊天窗口 @ 派发:会话输入框里 @ 一台在线设备后,发送即把正文派给它。
71
+ # 关掉后 @ 只当普通文本(想自己用 mesh_run 决定派不派时关掉)。
72
+ atDispatch: true
73
+
64
74
  # ── 循环限速 ──
65
75
  #
66
76
  # 入站任务会自动新建会话并让 agent 开跑,而每条消息都由远端决定。
@@ -0,0 +1,165 @@
1
+ /**
2
+ * 「陌生设备首次派活要确认」的自测。
3
+ *
4
+ * 这是安全相关判定,判错的后果是静默的:界面上写着"默认会先问你",实际上
5
+ * 陌生机器照样能直接让本机开一个 agent 会话。所以用断言盯死这几件事:
6
+ * · 缺省要拦(不能因为 config 里没写这个键就放行)
7
+ * · 显式 false 才不拦
8
+ * · 允许过一台,就只放行这一台(按机器名或地址命中)
9
+ * · 配对码开启时不重复问(它是更强的信任动作)
10
+ * · 撤销之后立刻重新拦
11
+ * · 坏数据(字符串、null、缺字段)不能把闸门炸开
12
+ *
13
+ * node lib/_selftest-approval.mjs
14
+ */
15
+ import { strict as assert } from "node:assert";
16
+ import {
17
+ MAX_APPROVED_PEERS,
18
+ approvePeer,
19
+ isApproved,
20
+ isReplyToOutbound,
21
+ needsApproval,
22
+ normalizeApproved,
23
+ peerOfTask,
24
+ revokePeer,
25
+ } from "./approval.js";
26
+
27
+ let passed = 0;
28
+ let failed = 0;
29
+ function test(name, fn) {
30
+ try {
31
+ fn();
32
+ passed += 1;
33
+ console.log(` ✓ ${name}`);
34
+ } catch (err) {
35
+ failed += 1;
36
+ console.log(` ✗ ${name}`);
37
+ console.log(` ${err?.message ?? err}`);
38
+ }
39
+ }
40
+
41
+ const taskFrom = (machine, address = "") => ({
42
+ id: "t-1",
43
+ from: `${machine}/peng`,
44
+ fromMachine: machine,
45
+ task: "报一下系统负载",
46
+ sourceAddress: address,
47
+ });
48
+
49
+ console.log("\n── 缺省必须拦:这是「装上就安全」的底线 ──");
50
+
51
+ test("config 里没有 requireApproval 这个键 → 仍然要拦", () => {
52
+ const peer = peerOfTask(taskFrom("陌生机"));
53
+ assert.equal(needsApproval({ config: {}, approved: [], peer }), true);
54
+ });
55
+
56
+ test("显式 requireApproval: false 才放行(老用户想回到零配置)", () => {
57
+ const peer = peerOfTask(taskFrom("陌生机"));
58
+ assert.equal(needsApproval({ config: { requireApproval: false }, approved: [], peer }), false);
59
+ });
60
+
61
+ test("配对码已开启 → 不再重复问(配对码是更强的信任动作)", () => {
62
+ const peer = peerOfTask(taskFrom("陌生机"));
63
+ assert.equal(needsApproval({ config: {}, approved: [], peer, pairingRequired: true }), false);
64
+ });
65
+
66
+ console.log("\n── 允许过的机器要记住,且只记这一台 ──");
67
+
68
+ test("允许 A 之后 A 免问、B 仍然要问", () => {
69
+ const a = peerOfTask(taskFrom("A机"));
70
+ const b = peerOfTask(taskFrom("B机"));
71
+ const approved = approvePeer([], a, "2026-01-01T00:00:00.000Z");
72
+ assert.equal(needsApproval({ config: {}, approved, peer: a }), false);
73
+ assert.equal(needsApproval({ config: {}, approved, peer: b }), true);
74
+ });
75
+
76
+ test("机器名大小写不敏感(Windows 上尤其重要)", () => {
77
+ const approved = approvePeer([], peerOfTask(taskFrom("DESKTOP-ABC")));
78
+ assert.equal(isApproved(approved, peerOfTask(taskFrom("desktop-abc"))), true);
79
+ });
80
+
81
+ test("只给了地址的对端也能被记住(旧版本对端)", () => {
82
+ // "unknown" 是老对端的占位符,不能当成一台叫 unknown 的机器
83
+ const peer = peerOfTask({ from: "unknown", sourceAddress: "192.168.1.9" });
84
+ assert.equal(peer.machine, "");
85
+ const approved = approvePeer([], peer);
86
+ assert.equal(isApproved(approved, { machine: "", address: "192.168.1.9" }), true);
87
+ // 另一个地址不能被顺带放行
88
+ assert.equal(isApproved(approved, { machine: "", address: "192.168.1.10" }), false);
89
+ });
90
+
91
+ test("有机器名就只认机器名 —— 不能因为地址相同就放行另一台(tailnet 反代下都是 127.0.0.1)", () => {
92
+ const a = peerOfTask({ fromMachine: "A机", sourceAddress: "127.0.0.1" });
93
+ const approved = approvePeer([], a);
94
+ const b = peerOfTask({ fromMachine: "B机", sourceAddress: "127.0.0.1" });
95
+ assert.equal(isApproved(approved, b), false);
96
+ });
97
+
98
+ test("重复允许同一台机器 → 幂等,不会长出两条记录", () => {
99
+ const a = peerOfTask(taskFrom("A机"));
100
+ const once = approvePeer([], a);
101
+ const twice = approvePeer(once, a);
102
+ assert.equal(twice.length, 1);
103
+ });
104
+
105
+ test("撤销之后立刻重新拦", () => {
106
+ const a = peerOfTask(taskFrom("A机"));
107
+ const approved = approvePeer([], a);
108
+ const revoked = revokePeer(approved, "a机");
109
+ assert.equal(needsApproval({ config: {}, approved: revoked, peer: a }), true);
110
+ });
111
+
112
+ console.log("\n── 坏数据不能把闸门炸开 ──");
113
+
114
+ test("approvedPeers 是 null / 字符串 / 混入坏条目 → 归一化成空或只留好条目", () => {
115
+ assert.deepEqual(normalizeApproved(null), []);
116
+ assert.deepEqual(normalizeApproved("oops"), []);
117
+ assert.deepEqual(normalizeApproved([null, 1, "x", {}, { machine: "ok" }]).length, 1);
118
+ });
119
+
120
+ test("既没有机器名也没有地址的对端 → 必须问(不能因为认不出来就放行)", () => {
121
+ const peer = peerOfTask({ from: "", sourceAddress: "" });
122
+ assert.equal(needsApproval({ config: {}, approved: [], peer }), true);
123
+ });
124
+
125
+ test("批准记录有上限,不会无限增长", () => {
126
+ let list = [];
127
+ for (let i = 0; i < MAX_APPROVED_PEERS + 10; i += 1) list = approvePeer(list, { machine: `m${i}`, address: "" });
128
+ assert.equal(list.length, MAX_APPROVED_PEERS);
129
+ // 最新的那台必须在,最旧的被挤掉
130
+ assert.equal(isApproved(list, { machine: `m${MAX_APPROVED_PEERS + 9}`, address: "" }), true);
131
+ assert.equal(isApproved(list, { machine: "m0", address: "" }), false);
132
+ });
133
+
134
+ console.log("\n── peerOfTask:机器名优先,地址兜底 ──");
135
+
136
+ test("优先用 fromMachine,不用 from 里拼出来的前缀", () => {
137
+ const p = peerOfTask({ from: "旧名字/peng", fromMachine: "新名字", sourceAddress: "10.0.0.5" });
138
+ assert.equal(p.machine, "新名字");
139
+ });
140
+
141
+ test("fromMachine 缺失时回退 from 的机器名部分", () => {
142
+ assert.equal(peerOfTask({ from: "hos/peng" }).machine, "hos");
143
+ });
144
+
145
+ console.log("\n── 回执必须绕过闸门(否则结果永远回不来)──");
146
+
147
+ test("同一台机器 + 同一 thread 的回执 → 是回执", () => {
148
+ const out = [{ toMachine: "hos", thread: "build-1" }];
149
+ assert.equal(isReplyToOutbound({ fromMachine: "hos", thread: "build-1" }, out), true);
150
+ });
151
+
152
+ test("换一台机器或换一个 thread → 不是回执(不能借旧 thread 名绕过)", () => {
153
+ const out = [{ toMachine: "hos", thread: "build-1" }];
154
+ assert.equal(isReplyToOutbound({ fromMachine: "evilbox", thread: "build-1" }, out), false);
155
+ assert.equal(isReplyToOutbound({ fromMachine: "hos", thread: "build-2" }, out), false);
156
+ });
157
+
158
+ test("没有 thread / 没有机器名 / outbound 不是数组 → 都不是回执", () => {
159
+ assert.equal(isReplyToOutbound({ fromMachine: "hos" }, [{ toMachine: "hos", thread: "" }]), false);
160
+ assert.equal(isReplyToOutbound({ thread: "x" }, [{ toMachine: "hos", thread: "x" }]), false);
161
+ assert.equal(isReplyToOutbound({ fromMachine: "hos", thread: "x" }, null), false);
162
+ });
163
+
164
+ console.log(`\n${failed === 0 ? "全部通过" : "有失败"}:${passed} 通过 / ${failed} 失败\n`);
165
+ process.exit(failed === 0 ? 0 : 1);
@@ -0,0 +1,377 @@
1
+ /**
2
+ * 聊天窗口 @ 派发(宿主侧)的端到端自测。
3
+ *
4
+ * 与 _selftest-reply-route.mjs 同一套手法:把 lib/index.js 放进 VM 里加载,
5
+ * 用假对端 HTTP 服务收包,驱动真实的 `agent/pre-step` 监听器 —— 不装 DSH、
6
+ * 不调模型、不出网。
7
+ *
8
+ * 盯住的是「静默失败」最容易发生的那几处:
9
+ * · 消息开头的 @目标 真的变成了一次 POST,正文被完整带过去;
10
+ * · 改写后的消息明确说「已派发 / 未派发」,不会让 agent 在本机重做一遍;
11
+ * · 离线 / 同名歧义 / 只有 @ 没正文 → 不发包,但原因必须写出来;
12
+ * · 同一条消息被 pre-step 拿到两次 → 只派发一次;
13
+ * · 正文中间的 @ 不自动派发。
14
+ *
15
+ * node --experimental-vm-modules lib/_selftest-at-mention-host.mjs
16
+ */
17
+ import assert from "node:assert/strict";
18
+ import vm from "node:vm";
19
+ import http from "node:http";
20
+ import { readFileSync, mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
21
+ import { tmpdir } from "node:os";
22
+ import { join } from "node:path";
23
+ import { conversationKey } from "./conversation.js";
24
+
25
+ let passed = 0;
26
+ let failed = 0;
27
+ async function test(name, fn) {
28
+ try {
29
+ await fn();
30
+ passed += 1;
31
+ console.log(` ✓ ${name}`);
32
+ } catch (err) {
33
+ failed += 1;
34
+ console.log(` ✗ ${name}`);
35
+ console.log(` ${err?.message ?? err}`);
36
+ }
37
+ }
38
+
39
+ const root = mkdtempSync(join(tmpdir(), "mesh-at-test-"));
40
+ mkdirSync(join(root, "mesh"), { recursive: true });
41
+ writeFileSync(join(root, "mesh", "state.json"), JSON.stringify({ secret: "test-only-shared-secret" }));
42
+
43
+ // ── 假对端:收 /mesh/v1/task ──
44
+ const posts = [];
45
+ const server = http.createServer((req, res) => {
46
+ let raw = "";
47
+ req.on("data", (c) => {
48
+ raw += c;
49
+ });
50
+ req.on("end", () => {
51
+ let body = null;
52
+ try {
53
+ body = JSON.parse(raw);
54
+ } catch {
55
+ body = { raw };
56
+ }
57
+ posts.push({ url: req.url, token: req.headers["x-dsh-mesh-token"], body });
58
+ res.writeHead(200, { "Content-Type": "application/json" });
59
+ res.end(JSON.stringify({ ok: true }));
60
+ });
61
+ });
62
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
63
+ const peerPort = server.address().port;
64
+
65
+ // ── 在 VM 里加载 lib/index.js,并暴露要测的内部函数 ──
66
+ const entryUrl = new URL("./index.js", import.meta.url);
67
+ const entrySource =
68
+ readFileSync(entryUrl, "utf8") +
69
+ "\nexport { registerAtMentions, dispatchTaskToPeer, resolvePeerTarget, classifyInbound };\n";
70
+
71
+ const context = vm.createContext({
72
+ console,
73
+ Buffer,
74
+ URL,
75
+ AbortSignal,
76
+ AbortController,
77
+ setTimeout,
78
+ clearTimeout,
79
+ setInterval,
80
+ clearInterval,
81
+ fetch,
82
+ process: { ...process, env: { ...process.env, DSH_HOME: root } },
83
+ });
84
+ const schema = new Proxy(() => schema, { get: () => schema });
85
+ const mocks = {
86
+ "@deepseek-ai/schemastery": { default: schema },
87
+ "@deepseek-ai/dsh-brand": { brandString: (value) => value },
88
+ "@deepseek-ai/dsh-tools": { defineTool: (tool) => tool },
89
+ "@deepseek-ai/dsh-llm": { createUserMessage: (message) => message },
90
+ };
91
+ const module = new vm.SourceTextModule(entrySource, {
92
+ context,
93
+ identifier: entryUrl.href,
94
+ initializeImportMeta: (meta) => {
95
+ meta.url = entryUrl.href;
96
+ },
97
+ });
98
+ await module.link(async (specifier) => {
99
+ const exports = mocks[specifier] ?? (await import(specifier.startsWith(".") ? new URL(specifier, entryUrl).href : specifier));
100
+ return new vm.SyntheticModule(
101
+ Object.keys(exports),
102
+ function () {
103
+ for (const key of Object.keys(exports)) this.setExport(key, exports[key]);
104
+ },
105
+ { context },
106
+ );
107
+ });
108
+ await module.evaluate();
109
+ const { registerAtMentions, resolvePeerTarget, classifyInbound } = module.namespace;
110
+
111
+ // ── 假环境 ──
112
+ const peer = (machine, extra = {}) => ({
113
+ id: `id-${machine}`,
114
+ machine,
115
+ online: true,
116
+ host: "127.0.0.1",
117
+ port: peerPort,
118
+ transport: "lan",
119
+ endpoints: [{ transport: "lan", host: "127.0.0.1", port: peerPort, lastSeen: Date.now() }],
120
+ ...extra,
121
+ });
122
+
123
+ function makeHarness({ peers = [peer("mac")], atDispatch = true, allOff = false } = {}) {
124
+ const logs = [];
125
+ const warns = [];
126
+ const outbound = [];
127
+ const threadState = new Map();
128
+ const listeners = new Map();
129
+ const ctx = {
130
+ on: (name, fn, opts) => {
131
+ listeners.set(name, { fn, opts });
132
+ return () => listeners.delete(name);
133
+ },
134
+ };
135
+ const deps = {
136
+ discovery: {
137
+ peers: () => peers,
138
+ selfRecord: () => ({ machine: "me", id: "me", host: "127.0.0.1", port: 0 }),
139
+ },
140
+ identity: { name: "me" },
141
+ config: { atDispatch, requestTimeoutMs: 2000 },
142
+ outbound,
143
+ threadState,
144
+ hostDispatched: new Map(),
145
+ log: (m) => logs.push(String(m)),
146
+ warn: (m) => warns.push(String(m)),
147
+ onHistoryChange: () => {},
148
+ meshSwitch: { status: () => ({ all: allOff }) },
149
+ };
150
+ registerAtMentions(ctx, deps);
151
+ const listener = listeners.get("agent/pre-step")?.fn;
152
+ /**
153
+ * 跑一次 pre-step:喂一条 user 消息,返回模型将看到的消息列表。
154
+ */
155
+ async function step(text, { agentSession = "s-1", id = `msg-${Math.random()}`, role } = {}) {
156
+ assert.ok(listener, "agent/pre-step 监听器没有注册");
157
+ const message = role || {
158
+ id,
159
+ role: "user",
160
+ source: { kind: "user" },
161
+ content: [{ type: "text", text }],
162
+ };
163
+ const next = async () => ({ kind: "enter", messages: [message] });
164
+ const decision = await listener({ agent: { session: { id: agentSession } }, signal: new AbortController().signal }, next);
165
+ return { decision, message };
166
+ }
167
+ return { deps, listener, step, logs, warns, outbound, threadState };
168
+ }
169
+
170
+ const textOf = (message) => message.content.filter((b) => b.type === "text").map((b) => b.text).join("\n");
171
+
172
+ console.log("\n── 正常路径:开头 @在线机器 → 真的发出去 ──");
173
+
174
+ await test("派发一次 POST:完整正文、带配对码、thread 绑定到当前会话", async () => {
175
+ posts.length = 0;
176
+ const h = makeHarness();
177
+ const { decision } = await h.step("@mac 看看磁盘空间");
178
+ assert.equal(posts.length, 1, "应当正好发一条");
179
+ const post = posts[0];
180
+ assert.equal(post.url, "/mesh/v1/task");
181
+ assert.equal(post.token, "test-only-shared-secret");
182
+ assert.equal(post.body.task, "看看磁盘空间", "正文必须去掉 @目标");
183
+ assert.equal(post.body.originSession, "s-1", "回执要落回当前会话");
184
+ assert.equal(post.body.human, true, "聊天窗口 @ 是人敲的,要带 human 标记(对端才不会被长度闸门吞掉)");
185
+ assert.match(post.body.thread, /^at-t-[0-9a-f]+$/, `thread 形态:${post.body.thread}`);
186
+ assert.equal(h.threadState.size, 1, "thread 必须绑定到本机会话");
187
+
188
+ const shown = textOf(decision.messages[0]);
189
+ assert.match(shown, /看看磁盘空间/);
190
+ assert.match(shown, /已派发/);
191
+ assert.match(shown, /等待回执/);
192
+ assert.match(shown, /不要调用任何工具/);
193
+ assert.ok(shown.includes(post.body.id), "改写里要带任务 id,方便对账");
194
+ });
195
+
196
+ await test("多个 @目标 → 每个目标各发一次", async () => {
197
+ posts.length = 0;
198
+ const h = makeHarness({ peers: [peer("mac"), peer("hos")] });
199
+ const { decision } = await h.step("@mac @hos 一起看看");
200
+ assert.equal(posts.length, 2);
201
+ assert.deepEqual(posts.map((p) => p.body.task), ["一起看看", "一起看看"]);
202
+ const shown = textOf(decision.messages[0]);
203
+ assert.match(shown, /mac/);
204
+ assert.match(shown, /hos/);
205
+ });
206
+
207
+ await test("同一条消息被 pre-step 拿到两次 → 只派发一次", async () => {
208
+ posts.length = 0;
209
+ const h = makeHarness();
210
+ await h.step("@mac 看看磁盘", { id: "same-id" });
211
+ const second = await h.step("@mac 看看磁盘", { id: "same-id" });
212
+ assert.equal(posts.length, 1, "重复投喂不能重复派发");
213
+ assert.match(textOf(second.decision.messages[0]), /@mac/, "第二次原样放行(不做第二次改写)");
214
+ });
215
+
216
+ console.log("\n── 不该派发 / 必须说出原因 ──");
217
+
218
+ await test("正文中间的 @ 不自动派发,消息原样放行", async () => {
219
+ posts.length = 0;
220
+ const h = makeHarness();
221
+ const { decision } = await h.step("请让 @mac 看看磁盘");
222
+ assert.equal(posts.length, 0);
223
+ assert.equal(decision.messages[0].content[0].text, "请让 @mac 看看磁盘");
224
+ });
225
+
226
+ await test("未知名字的 @ 不当派发目标(文件引用 / 打错字)", async () => {
227
+ posts.length = 0;
228
+ const h = makeHarness();
229
+ for (const text of ["@AGENTS.md 看看", "@macx hi"]) {
230
+ const { decision } = await h.step(text);
231
+ assert.equal(decision.messages[0].content[0].text, text, `${text} 不该被改写`);
232
+ }
233
+ assert.equal(posts.length, 0);
234
+ });
235
+
236
+ await test("离线机器:不发包,但必须写清「当前离线」且「没有在本机执行」", async () => {
237
+ posts.length = 0;
238
+ const h = makeHarness({ peers: [peer("mac", { online: false })] });
239
+ const { decision } = await h.step("@mac 看看磁盘");
240
+ assert.equal(posts.length, 0, "离线不该发包");
241
+ const shown = textOf(decision.messages[0]);
242
+ assert.match(shown, /当前离线/);
243
+ assert.match(shown, /没有在本机执行/);
244
+ });
245
+
246
+ await test("只有 @ 名字没有正文:不发包,并说明原因", async () => {
247
+ posts.length = 0;
248
+ const h = makeHarness();
249
+ const { decision } = await h.step("@mac");
250
+ assert.equal(posts.length, 0);
251
+ const shown = textOf(decision.messages[0]);
252
+ assert.match(shown, /没有正文/);
253
+ });
254
+
255
+ await test("同名且多台在线:歧义要报出来,不猜目标", async () => {
256
+ posts.length = 0;
257
+ const h = makeHarness({ peers: [peer("mac"), peer("mac", { id: "id-mac-2", port: peerPort + 1 })] });
258
+ const resolved = resolvePeerTarget(h.deps.discovery, "mac");
259
+ assert.match(String(resolved.error || ""), /匹配到 2 台机器/);
260
+ const { decision } = await h.step("@mac 看看磁盘");
261
+ assert.equal(posts.length, 0);
262
+ assert.match(textOf(decision.messages[0]), /匹配到 2 台机器/);
263
+ });
264
+
265
+ await test("一键关闭(全部关):不发包,并说明是本机自己关的", async () => {
266
+ posts.length = 0;
267
+ const h = makeHarness({ allOff: true });
268
+ const { decision } = await h.step("@mac 看看磁盘");
269
+ assert.equal(posts.length, 0);
270
+ assert.match(textOf(decision.messages[0]), /已全部关闭/);
271
+ });
272
+
273
+ console.log("\n── 开关与作用域 ──");
274
+
275
+ await test("atDispatch=false → 完全不挂监听器", async () => {
276
+ const h = makeHarness({ atDispatch: false });
277
+ assert.equal(h.listener, undefined);
278
+ assert.ok(h.logs.some((l) => l.includes("已关闭")), "关闭也要留一句话,别让人以为坏了");
279
+ });
280
+
281
+ await test("非 user 来源的消息(对端回执 / 插件注入)不参与 @ 派发", async () => {
282
+ posts.length = 0;
283
+ const h = makeHarness();
284
+ const webhook = {
285
+ id: "w-1",
286
+ role: "user",
287
+ source: { kind: "webhook" },
288
+ content: [{ type: "text", text: "@mac 看看磁盘" }],
289
+ };
290
+ await h.step("@mac 看看磁盘", { role: webhook });
291
+ assert.equal(posts.length, 0);
292
+ });
293
+
294
+ console.log("\n── 对端闸门:人手动派发的短消息不能被吞成「仅记录」──");
295
+
296
+ const gateConfig = { minTaskChars: 8, maxWakesPerThread: 30, threadWindowMs: 3600000, threadCooldownMs: 5000 };
297
+
298
+ await test("6 个字的 @ 任务:带 human 时放行(否则就是真机遇到的「仅记录」)", () => {
299
+ const task = { fromMachine: "lipeng-mac", thread: "at-t-1", task: "你的磁盘占用", human: true };
300
+ const verdict = classifyInbound(task, new Map(), gateConfig, Date.now(), () => 30);
301
+ assert.equal(verdict.wake, true, `被判成 ${verdict.kind}: ${verdict.reason}`);
302
+ });
303
+
304
+ await test("同样的短消息,没有 human 标记 → 仍然只入箱(agent 互刷的闸门不能被拆掉)", () => {
305
+ const task = { fromMachine: "lipeng-mac", thread: "at-t-1", task: "你的磁盘占用" };
306
+ const verdict = classifyInbound(task, new Map(), gateConfig, Date.now(), () => 30);
307
+ assert.equal(verdict.wake, false);
308
+ assert.equal(verdict.kind, "short");
309
+ assert.match(verdict.reason, /minTaskChars/);
310
+ });
311
+
312
+ await test("纯寒暄(「收到」)带 human 也放行;不带 human 仍被拦成 notice", () => {
313
+ // minTaskChars 调到 1,让这条只测"寒暄闸门"(默认 8 时它先被长度闸门拦住)。
314
+ const noLengthGate = { ...gateConfig, minTaskChars: 1 };
315
+ const human = classifyInbound({ fromMachine: "a", thread: "t", task: "收到", human: true }, new Map(), noLengthGate, Date.now(), () => 30);
316
+ assert.equal(human.wake, true, `被判成 ${human.kind}: ${human.reason}`);
317
+ const agent = classifyInbound({ fromMachine: "a", thread: "t", task: "收到" }, new Map(), noLengthGate, Date.now(), () => 30);
318
+ assert.equal(agent.wake, false);
319
+ assert.equal(agent.kind, "notice");
320
+ });
321
+
322
+ await test("noWake 的优先级高于 human:显式回执仍不唤醒", () => {
323
+ const verdict = classifyInbound(
324
+ { fromMachine: "a", thread: "t", task: "你的磁盘占用", human: true, noWake: true },
325
+ new Map(),
326
+ gateConfig,
327
+ Date.now(),
328
+ () => 30,
329
+ );
330
+ assert.equal(verdict.wake, false);
331
+ assert.equal(verdict.kind, "noWake");
332
+ });
333
+
334
+ await test("限速闸门对 human 仍然生效(人类也不能把对端刷爆)", () => {
335
+ const now = Date.now();
336
+ const key = conversationKey({ fromMachine: "a", thread: "t" });
337
+ const state = new Map([[key, { wakesAt: Array.from({ length: 3 }, () => now - 1000), sessionId: "s" }]]);
338
+ const verdict = classifyInbound({ fromMachine: "a", thread: "t", task: "看下磁盘和内存", human: true }, state, gateConfig, now, () => 3);
339
+ assert.equal(verdict.wake, false);
340
+ assert.equal(verdict.kind, "cap");
341
+ });
342
+
343
+ console.log("\n── 假对端记录 ──");
344
+ await test("派发失败(对端 500)也要改写消息并说出原因", async () => {
345
+ const failing = http.createServer((req, res) => {
346
+ res.writeHead(500, { "Content-Type": "application/json" });
347
+ res.end(JSON.stringify({ error: "对端内部错误" }));
348
+ });
349
+ await new Promise((resolve) => failing.listen(0, "127.0.0.1", resolve));
350
+ const failPort = failing.address().port;
351
+ const h = makeHarness({
352
+ peers: [
353
+ {
354
+ id: "id-bad",
355
+ machine: "bad",
356
+ online: true,
357
+ host: "127.0.0.1",
358
+ port: failPort,
359
+ transport: "lan",
360
+ endpoints: [{ transport: "lan", host: "127.0.0.1", port: failPort, lastSeen: Date.now() }],
361
+ },
362
+ ],
363
+ });
364
+ const { decision } = await h.step("@bad 看看磁盘");
365
+ const shown = textOf(decision.messages[0]);
366
+ assert.match(shown, /未能派发/);
367
+ assert.match(shown, /对端内部错误/);
368
+ assert.equal(h.outbound.length, 1);
369
+ assert.equal(h.outbound[0].ok, false);
370
+ await new Promise((resolve) => failing.close(resolve));
371
+ });
372
+
373
+ server.close();
374
+ rmSync(root, { recursive: true, force: true });
375
+
376
+ console.log(`\n${failed === 0 ? "全部通过" : "有失败"}:${passed} 通过 / ${failed} 失败\n`);
377
+ process.exit(failed === 0 ? 0 : 1);