dsh-plugin-mesh 0.5.20 → 0.5.22

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/AGENTS.md CHANGED
@@ -88,6 +88,14 @@ unless the request carries the renderer token).
88
88
  "wired but not actually connected" changes (a gate that was only mentioned in a
89
89
  comment, `install.sh` not copying `scripts/`, a placeholder that hid a missing
90
90
  file). When you add a gate, prove it has teeth: break the input and watch it fail.
91
+ 8. **No runtime dependencies that need build scripts.** Installing must be plain
92
+ unpacking. 0.5.6–0.5.20 pulled `ssh2` into `dependencies`; its `install: node
93
+ install.js` script made the **whole install fail on iPad** (DSH Go):
94
+ `[ERR_PNPM_IGNORED_BUILDS] Ignored build scripts: cpu-features, ssh2`, while
95
+ 0.5.5 (zero deps) installed clean in the same installer. `optionalDependencies`
96
+ does **not** help — same error. Optional features (SSH/`ssh2`) must be lazily
97
+ `require()`d with an actionable message when absent. `scripts/check-install-safe.mjs`
98
+ enforces this in `npm run check`.
91
99
 
92
100
  ## 4. Architecture map
93
101
 
@@ -130,6 +138,7 @@ inject the prompt → the peer's agent replies by calling `mesh_run`.
130
138
  | Kill switch | `npm run selftest:switch` | shutdown merge rules: `off` defaults to true, `all` closes both scopes, strict booleans only (15) |
131
139
  | Update check | `npm run selftest:update` | version compare/prerelease, registry fallback, "failure is not up-to-date" (22) |
132
140
  | One-click upgrade | `npm run selftest:upgrade` | integrity, tar paths, change classification, atomic swap/rollback (26) |
141
+ | Missing `ssh2` | `npm run selftest:sshdep` | SSH must say "ssh2 not installed" (with a fix command), never "peer rejected our key" |
133
142
 
134
143
  `lib/_selftest-newsession.mjs` is a manual end-to-end check that needs a dev host
135
144
  running; it is deliberately not part of `npm test` because it creates real agent
package/README.md CHANGED
@@ -58,7 +58,10 @@ dsh plugin add dsh-plugin-mesh
58
58
 
59
59
  - `desktop` profile 要在 **DSH Desktop 自带的终端**里跑(普通终端会被 dsh 拒绝);
60
60
  - 其它 profile 用普通终端即可;
61
- - 装完**必须重启一次 DSH** —— 插件在启动时加载。
61
+ - 装完**必须重启一次 DSH** —— 插件在启动时加载;
62
+ - 插件**零运行时依赖**:安装只解包,不跑构建脚本 —— 所以 iPad(DSH Go)这类不允许
63
+ 依赖跑构建脚本的宿主也装得上。只有「SSH 终端」要一个可选模块 `ssh2`(默认不装,
64
+ 缺了只影响 SSH),要用时在 profile 目录 `pnpm add ssh2`。
62
65
 
63
66
  **第 2 步 · 起个名字**
64
67
 
@@ -114,13 +117,41 @@ macOS(Intel / Apple Silicon)· Windows · Linux · Android(Termux)· WSL
114
117
 
115
118
  ---
116
119
 
120
+ ## 路线图:往哪走(每个方向都会演化)
121
+
122
+ 七个方向各自迭代 v1/v2/v3,**版本号是能力增量,不是时间,也不跨方向对齐**。
123
+ 方向之间没有全局顺序,只有**闸门** —— 多数方向的下一版都等 R-v1(事件层)先到位,其余可以并行。
124
+
125
+ | 方向 | 现在 | 下一版 | 子路线图 |
126
+ |---|---|---|---|
127
+ | **会话事件智能路由** | 派出即止,无终态 | 调用事件流模型重构 + 任务流水账(journal) + 结果信封 + 取消 | [route](https://github.com/peng456/dsh-plugin-mesh/blob/main/docs/roadmap/route.md) |
128
+ | **接入** | DSH + MCP 手接 | MCP · Skills<br>CC / Codex / WorkBuddy / opencode / VS Code / Copilot 等适配<br>dshInWeb 适配 | [adapter](https://github.com/peng456/dsh-plugin-mesh/blob/main/docs/roadmap/adapter.md) |
129
+ | **trace** | 无 | 状态时间线(等 R-v1) | [trace](https://github.com/peng456/dsh-plugin-mesh/blob/main/docs/roadmap/trace.md) |
130
+ | **玩法** | 一对一派发 | 组群 | [play](https://github.com/peng456/dsh-plugin-mesh/blob/main/docs/roadmap/play.md) |
131
+ | **界面** | 面板 + 任务列表 | 结果卡 + 通知 + `mesh demo` | [ui](https://github.com/peng456/dsh-plugin-mesh/blob/main/docs/roadmap/ui.md) |
132
+ | **协议** | 两份实现(`lib/` + `mcp-mesh`) | 收编成一份 + 名片区 v3 | [protocol](https://github.com/peng456/dsh-plugin-mesh/blob/main/docs/roadmap/protocol.md) |
133
+ | **安全** | 同网段默认可派 | 幽灵对端校验 + 高危动作确认 | [security](https://github.com/peng456/dsh-plugin-mesh/blob/main/docs/roadmap/security.md) |
134
+
135
+ 每个子路线图里都有:**现状证据 → 版本史(v0 已发布 / v1 计划 / v2、v3 条件)→ 各版验收判据 → 闸门 → 不做什么**。
136
+ 版本细则发版时追加,不覆盖历史。
137
+
138
+ **今天就缺的那一件**:派出去的任务没有终态 —— 返回 `200` 只说明对端**收下了**,
139
+ 不代表跑完了,也不能取消。它闸住了 trace / 结果卡 / 扇出三条方向。
140
+
141
+ 完整矩阵(v2/v3、闸门表、验收判据、指标、风险、明确不做什么)见
142
+ [`ROADMAP.md`](https://github.com/peng456/dsh-plugin-mesh/blob/main/ROADMAP.md)。
143
+
144
+ ---
145
+
117
146
  ## 深入阅读
118
147
 
119
148
  | 想要什么 | 去哪 |
120
149
  |---|---|
150
+ | 路线图、决策记录、指标与不做什么 | [`ROADMAP.md`](https://github.com/peng456/dsh-plugin-mesh/blob/main/ROADMAP.md) |
121
151
  | 给 agent 的机器可读事实(工具、配置项、端口) | [`llms.txt`](llms.txt) |
122
152
  | 英文快速上手 | [`README.en.md`](README.en.md) |
123
153
  | 设计取舍、组播/防火墙/tsnet 细节、配置项全表、排障 | [`docs/DESIGN-NOTES.md`](https://github.com/peng456/dsh-plugin-mesh/blob/main/docs/DESIGN-NOTES.md) |
154
+ | 设计与实施记录(任务追踪 / 同机多 agent / 身份与通道 / 放置) | [`docs/design/`](https://github.com/peng456/dsh-plugin-mesh/tree/main/docs/design) |
124
155
  | 改这个仓库前的硬约束与坑 | [`AGENTS.md`](AGENTS.md) |
125
156
  | 参与开发、发版流程 | [`CONTRIBUTING.md`](CONTRIBUTING.md) |
126
157
 
@@ -150,21 +150,45 @@ test("fromMachine 缺失时回退 from 的机器名部分", () => {
150
150
 
151
151
  console.log("\n── 回执必须绕过闸门(否则结果永远回不来)──");
152
152
 
153
+ const NOW = Date.parse("2026-11-24T12:00:00.000Z");
154
+ const fresh = (extra = {}) => ({ toMachine: "hos", thread: "build-1", at: new Date(NOW - 60_000).toISOString(), ...extra });
155
+
153
156
  test("同一台机器 + 同一 thread 的回执 → 是回执", () => {
154
- const out = [{ toMachine: "hos", thread: "build-1" }];
155
- assert.equal(isReplyToOutbound({ fromMachine: "hos", thread: "build-1" }, out), true);
157
+ assert.equal(isReplyToOutbound({ fromMachine: "hos", thread: "build-1" }, [fresh()], NOW), true);
158
+ });
159
+
160
+ test("对端声明了 answers → 按 id 精确认领(同一个 thread 的第 2 轮也是回执)", () => {
161
+ const out = [fresh({ id: "t-1" }), fresh({ id: "t-2" })];
162
+ assert.equal(isReplyToOutbound({ fromMachine: "hos", thread: "build-1", answers: "t-2" }, out, NOW), true);
163
+ // 声明的 id 不是发给这台机器的 → 不认(不能让陌生机器借一个 id 绕过闸门)
164
+ assert.equal(isReplyToOutbound({ fromMachine: "evilbox", thread: "build-1", answers: "t-2" }, out, NOW), false);
165
+ });
166
+
167
+ test("同一 thread 上已认领过的派发 → 第 2 条不再是回执(D-001 / #33)", () => {
168
+ const out = [fresh({ replyAt: new Date(NOW - 30_000).toISOString() })];
169
+ assert.equal(isReplyToOutbound({ fromMachine: "hos", thread: "build-1" }, out, NOW), false);
170
+ });
171
+
172
+ test("我方自己发出去的回执不参与认领(它不期待别人再回一条)", () => {
173
+ const out = [fresh({ answers: "t-0" })];
174
+ assert.equal(isReplyToOutbound({ fromMachine: "hos", thread: "build-1" }, out, NOW), false);
175
+ });
176
+
177
+ test("超过认领窗口的旧派发 → 不再认领(否则它会永远吃掉同 thread 的新任务)", () => {
178
+ const stale = fresh({ at: new Date(NOW - 2 * 3600_000).toISOString() });
179
+ assert.equal(isReplyToOutbound({ fromMachine: "hos", thread: "build-1" }, [stale], NOW), false);
156
180
  });
157
181
 
158
182
  test("换一台机器或换一个 thread → 不是回执(不能借旧 thread 名绕过)", () => {
159
- const out = [{ toMachine: "hos", thread: "build-1" }];
160
- assert.equal(isReplyToOutbound({ fromMachine: "evilbox", thread: "build-1" }, out), false);
161
- assert.equal(isReplyToOutbound({ fromMachine: "hos", thread: "build-2" }, out), false);
183
+ const out = [fresh()];
184
+ assert.equal(isReplyToOutbound({ fromMachine: "evilbox", thread: "build-1" }, out, NOW), false);
185
+ assert.equal(isReplyToOutbound({ fromMachine: "hos", thread: "build-2" }, out, NOW), false);
162
186
  });
163
187
 
164
188
  test("没有 thread / 没有机器名 / outbound 不是数组 → 都不是回执", () => {
165
- assert.equal(isReplyToOutbound({ fromMachine: "hos" }, [{ toMachine: "hos", thread: "" }]), false);
166
- assert.equal(isReplyToOutbound({ thread: "x" }, [{ toMachine: "hos", thread: "x" }]), false);
167
- assert.equal(isReplyToOutbound({ fromMachine: "hos", thread: "x" }, null), false);
189
+ assert.equal(isReplyToOutbound({ fromMachine: "hos" }, [fresh({ thread: "" })], NOW), false);
190
+ assert.equal(isReplyToOutbound({ thread: "x" }, [fresh({ thread: "x" })], NOW), false);
191
+ assert.equal(isReplyToOutbound({ fromMachine: "hos", thread: "x" }, null, NOW), false);
168
192
  });
169
193
 
170
194
  console.log(`\n${failed === 0 ? "全部通过" : "有失败"}:${passed} 通过 / ${failed} 失败\n`);
@@ -249,6 +249,26 @@ try {
249
249
  assert.equal(original.messages.length, agentReplyBefore, "agent 互刷的 noWake 仍然不唤醒");
250
250
  console.log("✓ agent-originated noWake replies stay recorded-only");
251
251
 
252
+ // ── D-001 / issue #33:同一 thread 的第 2、3 轮是真任务,不是回执 ──
253
+ //
254
+ // 旧判据是"这个 thread 上我方派过没有",第 2 轮必然命中,于是提示词被写成
255
+ // 「这是回执…不要回派」,结果静默丢失。现在:worker 会话发出的回执带
256
+ // `answers: <任务 id>`,接收端按 id 认领一次,因此每一轮都是新任务。
257
+ const multi = "d001-multiround";
258
+ for (const round of [1, 2, 3]) {
259
+ await a.send("B", multi, "original-session");
260
+ await until(() => b.inbound.filter((t) => t.thread === multi).length >= round);
261
+ const rec = b.inbound.filter((t) => t.thread === multi).at(-1);
262
+ assert.equal(rec.isReply, false, `第 ${round} 轮的同一 thread 任务被误判成回执(D-001 / #33)`);
263
+ // 第 1 轮新建会话,第 2 轮起复用同一个会话(上下文连续)。
264
+ const session = [...b.agents.keys()].at(-1);
265
+ const sent = await b.send("A", multi, session);
266
+ assert.match(String(sent), /已派发/, String(sent));
267
+ await until(() => a.inbound.at(-1)?.thread === multi && a.inbound.at(-1)?.isReply === true);
268
+ assert.equal(a.inbound.at(-1).status, "injected-thread-session", "回执要注入发起会话");
269
+ }
270
+ console.log("✓ same thread round 1..3 are tasks, not replies (D-001 / #33)");
271
+
252
272
  // 一键关闭的工具面:三个范围、默认关闭、不认识的范围要明确报错。
253
273
  const switchTool = b.tools.get("mesh_switch");
254
274
  assert.ok(switchTool, "必须注册 mesh_switch");
@@ -0,0 +1,93 @@
1
+ /**
2
+ * 「ssh2 没装」这句话的自测。
3
+ *
4
+ * 守的是一个用户可见的误导:ssh2 不再是插件的依赖(原因见 `lib/ssh-host.js`
5
+ * 文件头和 `scripts/check-install-safe.mjs`),所以**大部分机器上它都没装**。
6
+ * 而 `open()` 会先拿密钥试一次,模块缺失会让那一步失败 —— 如果不管,最后会被包成
7
+ *
8
+ * 对端拒绝了本机保存的密钥(…)。改用密码登录一次即可…
9
+ *
10
+ * 用户照着这句话去重新部署密钥,永远修不好一个"没装模块"的问题(2026-11-23 实测
11
+ * 就是这个错法)。所以这里把两条都钉住:
12
+ * · 缺 ssh2 → 说"没装",并给出能动手的命令;
13
+ * · 这条错误不许出现"对端拒绝了本机保存的密钥"。
14
+ *
15
+ * 做法是把 `ssh-host.js`(只依赖 node 内置模块)复制到一个没有 node_modules 的
16
+ * 临时目录里 import —— 那个位置一定解析不到 ssh2,等于真实缺依赖的机器。
17
+ *
18
+ * node lib/_selftest-ssh-dep.mjs
19
+ */
20
+ import { strict as assert } from "node:assert";
21
+ import { execFileSync } from "node:child_process";
22
+ import { copyFileSync, mkdtempSync, rmSync } from "node:fs";
23
+ import { tmpdir } from "node:os";
24
+ import { dirname, join } from "node:path";
25
+ import { fileURLToPath } from "node:url";
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 here = dirname(fileURLToPath(import.meta.url));
42
+ const sandbox = mkdtempSync(join(tmpdir(), "mesh-ssh-dep-"));
43
+
44
+ /** 在沙箱里跑一次 open(),把真实错误消息捞回来。 */
45
+ function openWithoutSsh2() {
46
+ copyFileSync(join(here, "ssh-host.js"), join(sandbox, "ssh-host.js"));
47
+ const code = `
48
+ const { createSshManager } = await import(${JSON.stringify(join(sandbox, "ssh-host.js"))});
49
+ const stateDir = ${JSON.stringify(join(sandbox, "state"))};
50
+ const ssh = createSshManager({ stateDir, credentialsPath: stateDir + "/creds.json" });
51
+ try {
52
+ await ssh.open({ machine: "peer", host: "127.0.0.1", port: 1, username: "nobody" });
53
+ console.log("NO_ERROR");
54
+ } catch (err) {
55
+ console.log(String(err && err.message ? err.message : err));
56
+ }
57
+ `;
58
+ return execFileSync(process.execPath, ["--input-type=module", "-e", code], {
59
+ encoding: "utf8",
60
+ timeout: 20000,
61
+ cwd: sandbox,
62
+ }).trim();
63
+ }
64
+
65
+ console.log("\n── 缺 ssh2 时的说法 ──");
66
+
67
+ let message = "";
68
+ test("能拿到一条错误消息(不是静默成功)", () => {
69
+ message = openWithoutSsh2();
70
+ assert.ok(message && message !== "NO_ERROR", `期望报错,实际:${message}`);
71
+ });
72
+
73
+ test("说清是「没装 ssh2」,而不是其它原因", () => {
74
+ assert.match(message, /ssh2/);
75
+ assert.match(message, /没装/);
76
+ });
77
+
78
+ test("给出能动手的命令", () => {
79
+ assert.match(message, /pnpm add ssh2/);
80
+ });
81
+
82
+ test("不把「没装模块」伪装成「对端拒绝了密钥」", () => {
83
+ assert.doesNotMatch(message, /对端拒绝了本机保存的密钥/);
84
+ });
85
+
86
+ test("是单行消息(原始 Require stack 不糊进面板)", () => {
87
+ assert.equal(message.split("\n").length, 1, `实际:${JSON.stringify(message)}`);
88
+ });
89
+
90
+ rmSync(sandbox, { recursive: true, force: true });
91
+
92
+ console.log(`\n${failed === 0 ? "全部通过" : "有失败"}:${passed} 通过 / ${failed} 失败\n`);
93
+ process.exit(failed === 0 ? 0 : 1);
package/lib/approval.js CHANGED
@@ -128,27 +128,69 @@ export function needsApproval({ enabled = false, approved = [], peer = {}, pairi
128
128
  return !isApproved(approved, peer);
129
129
  }
130
130
 
131
+ /** 没有 `answers` 声明时的认领窗口(毫秒)。超窗口的旧派发不再被认领,避免它永远吃掉同 thread 的新任务。 */
132
+ export const REPLY_WINDOW_MS = 30 * 60_000;
133
+
131
134
  /**
132
- * 这条入站任务是不是在「回答问题」而不是派新活?
135
+ * 这条入站任务在回答哪一次派发?返回被它回答的那条派发记录;不是回执则返回
136
+ * `null`。闸门只**查**不改,真正写 `replyAt` 的是处理阶段(见 index.js),
137
+ * 这样"要不要审批"和"要不要当回执"看的是同一个判据。
133
138
  *
134
- * 判据和 handleInboundTask 里的一致:同一台机器 + 同一个 thread 上,我们确实
135
- * 往外派过任务。回执**必须绕过**首次确认闸门,否则对方把结果派回来时会被本机
136
- * 拦下,整条回路卡死在"等允许"。
139
+ * 两级判据:
137
140
  *
138
- * 抽成纯函数是为了能单测这条绕过 —— 写错了是静默灾难:要么结果回不来,
139
- * 要么陌生机器能借一个旧 thread 名绕过闸门。
141
+ * 1. **声明优先**:对端带了 `answers: <任务 id>`,按 id + 机器精确认领。这是
142
+ * D-001(issue #33)的治本路径 —— 意图由发送方声明,不靠历史推断。
143
+ * 2. **老对端回退**:没有声明时,认领"同机器 + 同 thread"上最早一条**未认领**、
144
+ * 且**本身不是回执**的派发(窗口 `windowMs` 内)。认领一次就写 `replyAt`,
145
+ * 所以同一 thread 的第 2 轮起不会再被当成回执。
146
+ *
147
+ * 为什么"本身不是回执"要排除:我方发出去的回执(`answers` 非空)不期待别人
148
+ * 再回一条。不排除的话,它会在发送方永远挂着,把之后每一轮都判成回执 ——
149
+ * 这正是 issue #33 里那版补丁不管用的原因。
140
150
  *
141
- * @param {object} task 入站任务
142
151
  * @param {Array} outbound 本机发出的任务记录
152
+ * @param {object} task 入站任务
153
+ * @param {number} now 当前时间(毫秒),便于测试
154
+ * @param {number} windowMs 回退判据的认领窗口
143
155
  */
144
- export function isReplyToOutbound(task = {}, outbound = []) {
145
- const thread = String(task?.thread || "").trim();
146
- if (!thread) return false;
156
+ export function replyClaim(outbound, task = {}, now = Date.now(), windowMs = REPLY_WINDOW_MS) {
157
+ const list = Array.isArray(outbound) ? outbound : [];
147
158
  const machine = String(task?.fromMachine || String(task?.from || "").split("/")[0] || "").trim();
148
- if (!machine) return false;
149
- return (Array.isArray(outbound) ? outbound : []).some(
150
- (o) =>
151
- String(o?.toMachine || "").trim() === machine &&
152
- String(o?.thread || "").trim() === thread,
159
+ const declared = String(task?.answers || "").trim();
160
+ if (declared) {
161
+ // id 已经足够唯一,机器名再挡一次伪造:陌生机器不能借一个我们发给别人的 id 绕过闸门。
162
+ return list.find((o) => String(o?.id || "") === declared && String(o?.toMachine || "").trim() === machine) ?? null;
163
+ }
164
+ const thread = String(task?.thread || "").trim();
165
+ if (!machine || !thread) return null;
166
+ const window = Number.isFinite(windowMs) && windowMs > 0 ? windowMs : REPLY_WINDOW_MS;
167
+ return (
168
+ list.find((o) => {
169
+ const at = Date.parse(o?.at ?? "");
170
+ return (
171
+ String(o?.toMachine || "").trim() === machine &&
172
+ String(o?.thread || "").trim() === thread &&
173
+ o?.ok !== false && // 没送达的派发不期待回执
174
+ !o?.answers && // 这一条本身是回执,不是待认领的派发
175
+ !o?.replyAt && // 已经认领过
176
+ Number.isFinite(at) &&
177
+ now - at <= window
178
+ );
179
+ }) ?? null
153
180
  );
154
181
  }
182
+
183
+ /**
184
+ * 这条入站任务是不是在「回答问题」而不是派新活?
185
+ *
186
+ * 回执**必须绕过**首次确认闸门,否则对方把结果派回来时会被本机拦下,整条回路
187
+ * 卡死在"等允许"。判据与 handleInboundTask 共用 `replyClaim`,避免两处漂移。
188
+ *
189
+ * @param {object} task 入站任务
190
+ * @param {Array} outbound 本机发出的任务记录
191
+ * @param {number} now 当前时间(毫秒)
192
+ * @param {number} windowMs 回退判据的认领窗口
193
+ */
194
+ export function isReplyToOutbound(task = {}, outbound = [], now = Date.now(), windowMs = REPLY_WINDOW_MS) {
195
+ return replyClaim(outbound, task, now, windowMs) !== null;
196
+ }
package/lib/index.js CHANGED
@@ -89,6 +89,7 @@ import {
89
89
  needsApproval,
90
90
  normalizeApproved,
91
91
  peerOfTask,
92
+ replyClaim,
92
93
  revokePeer,
93
94
  } from "./approval.js";
94
95
  import {
@@ -130,7 +131,7 @@ import {
130
131
  export const name = "dsh-plugin-mesh";
131
132
  export const inject = ["tools", "webServer"];
132
133
 
133
- const VERSION = "0.5.20";
134
+ const VERSION = "0.5.22";
134
135
  // 诊断用:进程启动时间 + 入口真实路径。磁盘上的版本**不在这里缓存** ——
135
136
  // 升级之后进程还跑旧代码,版本号必须现读磁盘才能立刻反映出来(真踩过:
136
137
  // 磁盘升到 0.5.1,进程还在 0.5.0,界面显示 0.5.0)。
@@ -250,6 +251,12 @@ export const Config = z.object({
250
251
  /** 超过这么久没心跳、也没 ping 通,算离线 */
251
252
  peerTtlMs: z.natural().default(20000),
252
253
  requestTimeoutMs: z.natural().default(20000),
254
+ /**
255
+ * 回执认领窗口(毫秒)。对端带了 `replyTo` 时按 id 精确认领、不受此限;
256
+ * 只有**没有声明**的老对端才靠"同机器同 thread 上最近的派发"认领,超过这个
257
+ * 窗口的派发不再被认领 —— 否则一条没等到回执的派发会永远吃掉同 thread 的新任务。
258
+ */
259
+ replyWindowMs: z.natural().default(30 * 60_000),
253
260
 
254
261
  // ── 发现方式(两者互补,默认都开)──
255
262
  /** 用 UDP 组播做被动发现:零配置、即时 */
@@ -2191,18 +2198,24 @@ function classifyInbound(task, threadState, config, now, capFor, { canInject = f
2191
2198
  * 最后才新建会话。复用是为了避免"每条消息都从零重新探索上下文"。
2192
2199
  */
2193
2200
  function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled, onHistoryChange, outbound) {
2201
+ const now = Date.now();
2194
2202
  // ── 这条入站是「回执」还是「新任务」? ──
2195
2203
  //
2196
- // 判据:同一台机器 + 同一个 thread 上,我们确实往外派过任务。
2204
+ // 判据见 approval.js 的 `replyClaim`:对端声明了 `answers` 就按 id 精确认领;
2205
+ // 没有声明时回退到"同机器同 thread 上最早一条未认领的派发"。**认领一次就
2206
+ // 落 `replyAt`**,所以同一 thread 的第 2 轮起不会再被当成回执(D-001 / #33)。
2197
2207
  // 是回执的话,提示词要明确禁止再回派,否则两边会互相回执形成循环
2198
2208
  // (2026-10-21 手动派发实测:一轮几十条)。
2199
- if (task?.thread) {
2200
- const from = String(task.fromMachine || String(task.from || "").split("/")[0] || "");
2201
- const sameThread = (o) => String(o.toMachine || "") === from && String(o.thread || "") === String(task.thread);
2202
- task.isReply = (outbound ?? []).some(sameThread);
2209
+ if (task?.thread || task?.answers) {
2210
+ const claimed = replyClaim(outbound, task, now, config.replyWindowMs);
2211
+ task.isReply = !!claimed;
2203
2212
  // 人发起的派发(聊天窗口 @ / 面板手动派发)的回执:即使发送方标了 noWake,
2204
2213
  // 也要投递回会话 —— 那是用户等着的答案,不是可以静默丢掉的寒暄。
2205
- task.humanReply = task.isReply && (outbound ?? []).some((o) => sameThread(o) && o.human === true);
2214
+ task.humanReply = task.isReply && claimed?.human === true;
2215
+ if (claimed && !claimed.replyAt) {
2216
+ claimed.replyAt = new Date(now).toISOString();
2217
+ onHistoryChange?.();
2218
+ }
2206
2219
  }
2207
2220
  const rec = inbound.find((t) => t.id === task.id);
2208
2221
  // 记下"回信地址",与"本机用哪个会话处理"是两件事。对端可以 GET
@@ -2223,7 +2236,6 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
2223
2236
  return null;
2224
2237
  }
2225
2238
  };
2226
- const now = Date.now();
2227
2239
 
2228
2240
  // 闸门:先判断值不值得开跑,再决定走哪条路径
2229
2241
  // 先判断"能不能注入已有会话":能的话冷却不适用(见 classifyInbound 的说明)
@@ -2283,6 +2295,24 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
2283
2295
  saveThreads(threadState);
2284
2296
  };
2285
2297
 
2298
+ /**
2299
+ * 记下"这个会话正在回答哪条入站任务"。worker 会话回派时带上 `answers`,
2300
+ * 对端就能按 id 精确认领,不必猜(D-001 / issue #33)。
2301
+ *
2302
+ * 只记**任务型**入站:回执被注入某个会话之后,那个会话接着发出的东西是新的
2303
+ * 请求(同一 thread 的第 2 轮),标记必须清掉,否则发起端自己的第二轮会被
2304
+ * 对端当成回执吞掉 —— 那正是这个缺陷的另一半。
2305
+ */
2306
+ const noteAnswering = (sessionId) => {
2307
+ if (!key) return;
2308
+ const st = threadState.get(key) ?? { wakesAt: [], sessionId: "" };
2309
+ st.sessionId = String(sessionId);
2310
+ if (task.isReply === true) delete st.answering;
2311
+ else st.answering = { id: task.id, sessionId: String(sessionId), at: now };
2312
+ threadState.set(key, st);
2313
+ saveThreads(threadState);
2314
+ };
2315
+
2286
2316
  /**
2287
2317
  * 把一个任务注入本机某个仍在运行的会话。
2288
2318
  *
@@ -2329,7 +2359,10 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
2329
2359
  // 除非发送方显式要求新起会话(task.newSession),此时跳过复用直接建新的
2330
2360
  if (key && task.newSession !== true) {
2331
2361
  const known = threadState.get(key)?.sessionId;
2332
- if (known && injectInto(known, "injected-thread-session", "同 thread 会话")) return;
2362
+ if (known && injectInto(known, "injected-thread-session", "同 thread 会话")) {
2363
+ noteAnswering(known);
2364
+ return;
2365
+ }
2333
2366
  }
2334
2367
 
2335
2368
  // 路径 B 已移除 —— 原来这里是拿 `task.originSession` 去本机找活跃会话。
@@ -2405,12 +2438,7 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
2405
2438
  ? `${resumed ? "恢复了已结束的会话" : "新建会话"}并绑定会话键 ${key}(${why})`
2406
2439
  : "新建会话(无会话键,一次性任务,用完不绑定)";
2407
2440
  }
2408
- if (key) {
2409
- const st = threadState.get(key) ?? { wakesAt: [now], sessionId: "" };
2410
- st.sessionId = String(sessionId);
2411
- threadState.set(key, st);
2412
- saveThreads(threadState);
2413
- }
2441
+ if (key) noteAnswering(sessionId);
2414
2442
  log(`任务 ${task.id} 已派发,会话 ${String(sessionId).slice(0, 20)}…`);
2415
2443
 
2416
2444
  // 排空队列:排队那些消息和第一条属于同一场对话,按到达顺序注入同一个会话
@@ -3251,6 +3279,7 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
3251
3279
  task: body.task,
3252
3280
  thread: body.thread ? String(body.thread) : "",
3253
3281
  originSession: body.originSession ? String(body.originSession) : "",
3282
+ answers: body.answers ? String(body.answers) : "",
3254
3283
  noWake: body.noWake === true,
3255
3284
  newSession: body.newSession === true,
3256
3285
  workspace: body.workspace ? String(body.workspace) : "",
@@ -3273,7 +3302,7 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
3273
3302
  //
3274
3303
  // 回执不算:同一台机器 + 同一个 thread 上我们确实往外派过任务,那这条
3275
3304
  // 就是对方在回答案,不是新活儿 —— 对回执再要一次确认会把整条回路卡死。
3276
- const replyFromPeer = isReplyToOutbound(task, outbound);
3305
+ const replyFromPeer = isReplyToOutbound(task, outbound, Date.now(), config.replyWindowMs);
3277
3306
  if (!replyFromPeer && inboundNeedsApproval(config, task)) {
3278
3307
  task.status = "needs-approval";
3279
3308
  task.routeDecision = `等待本机确认:还没有允许「${peerOfTask(task).machine || task.sourceAddress || "未知设备"}」`;
@@ -3671,6 +3700,21 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
3671
3700
  threadState.set(replyKey, { ...previous, wakesAt: previous?.wakesAt ?? [], sessionId: payload.originSession });
3672
3701
  saveThreads(threadState);
3673
3702
  // Retain the binding on failure: a timeout does not prove non-delivery.
3703
+
3704
+ // 这条派发是在回某条入站任务吗?是的话声明 `answers`,对端据此按 id
3705
+ // 精确认领,不必再靠"同 thread 派过没有"去猜(D-001 / issue #33)。
3706
+ //
3707
+ // 只认**任务型**入站发出的回执:回执被注入某个会话之后,那个会话接着
3708
+ // 发出的东西是新的请求(同一 thread 的第 2 轮),不是回执 —— 否则发起端
3709
+ // 自己的第二轮会被对端当成回执吞掉。
3710
+ const answering = threadState.get(replyKey)?.answering;
3711
+ if (answering && String(answering.sessionId || "") === payload.originSession) {
3712
+ payload.answers = String(answering.id);
3713
+ const st = threadState.get(replyKey);
3714
+ delete st.answering; // 一次任务只认一次回执;后续派发按新任务算
3715
+ threadState.set(replyKey, st);
3716
+ saveThreads(threadState);
3717
+ }
3674
3718
  }
3675
3719
 
3676
3720
  const started = Date.now();
package/lib/ssh-host.js CHANGED
@@ -19,13 +19,20 @@ import { dirname, join } from "node:path";
19
19
  const RING_LIMIT = 200 * 1024;
20
20
 
21
21
  /**
22
- * ssh2 必须**懒加载**,不能在模块顶层静态 import。
22
+ * ssh2 必须**懒加载**,不能在模块顶层静态 import,也**不能写进 package.json 的依赖**。
23
23
  *
24
- * 为什么:CI 里跑 `npm test` 的机器不装依赖(这个项目原来零运行时依赖,测试
24
+ * 懒加载的理由:CI 里跑 `npm test` 的机器不装依赖(这个项目零运行时依赖,测试
25
25
  * 也不需要 node_modules);静态 import 会让 `lib/index.js` 一被加载就
26
26
  * ERR_MODULE_NOT_FOUND,连不碰 SSH 的整套自测都红(实测 2026-10-29,ci 三条
27
- * job 全红)。改成用 createRequire 在真正要连 SSH 时再取,缺依赖就给出
28
- * 一句能动手的话,而不是把插件拖垮。
27
+ * job 全红)。
28
+ *
29
+ * 不写进依赖的理由(真实事故,2026-11-23):ssh2 带一个安装脚本
30
+ * `install: node install.js`(编译可选的原生加速模块 cpu-features)。宿主不允许
31
+ * 依赖跑构建脚本时,pnpm 会整次安装失败 —— iPad 上的 DSH Go 就抛
32
+ * `[ERR_PNPM_IGNORED_BUILDS] Ignored build scripts: cpu-features, ssh2`,
33
+ * 0.5.6–0.5.20 因此根本装不上 iPad(0.5.5 零依赖,同一个安装器干净通过)。
34
+ * 所以 SSH 变成"要用的人自己装":`package.json` 里没有它,缺了只影响 SSH 面板,
35
+ * 其余 mesh 功能照常。
29
36
  */
30
37
  let ssh2Module;
31
38
  function loadSsh2() {
@@ -37,9 +44,13 @@ function loadSsh2() {
37
44
  if (!ssh2Module?.Client) throw new Error("模块里没有 Client");
38
45
  return ssh2Module;
39
46
  } catch (err) {
47
+ // 原始的 ERR_MODULE_NOT_FOUND 带多行 "Require stack:",塞进面板会糊成一片;
48
+ // 只要第一行的"找不到哪个模块"就够了。
49
+ const reason = String(err?.message ?? err).split("\n")[0].trim();
40
50
  throw new Error(
41
- `SSH 依赖 ssh2 不可用(插件安装不完整):${err?.message ?? err}。` +
42
- "重装插件(会自动装依赖),或在插件目录执行 npm i ssh2。",
51
+ `SSH 终端需要额外的 ssh2 模块,这台机器上没装(${reason})。` +
52
+ "SSH 是可选项,其余 mesh 功能不受影响;要用就在 profile 目录执行 " +
53
+ "`pnpm add ssh2`(没有 pnpm 用 `npm i ssh2`),然后重开面板。",
43
54
  );
44
55
  }
45
56
  }
@@ -348,6 +359,10 @@ export function createSshManager({ stateDir, credentialsPath, log = () => {}, wa
348
359
  * @returns {Promise<string>} 会话 id
349
360
  */
350
361
  const open = async ({ host, port = 22, username, password = "", cols = 80, rows = 24, machine = "" }) => {
362
+ // ssh2 不是依赖(见文件头),缺了要在**尝试连接之前**就说清楚。否则它会先
363
+ // 在密钥那一步被当成一次认证失败,最后被包成"对端拒绝了本机保存的密钥" ——
364
+ // 用户按那句话去重新部署密钥,永远修不好一个"没装模块"的问题(实测 2026-11-23)。
365
+ loadSsh2();
351
366
  const key = ensureKey();
352
367
  const saved = known(machine) ?? {};
353
368
  // 这里的 port 是**实际连接用的端口**:直连时是用户的端口,走 tailnet 出站流时
package/llms.txt CHANGED
@@ -20,6 +20,15 @@ From source instead: `git clone https://github.com/peng456/dsh-plugin-mesh && cd
20
20
 
21
21
  **A restart of the dsh host is required after install** — the plugin loads at startup.
22
22
 
23
+ **No runtime dependencies: install is plain unpacking, and no dependency build
24
+ script runs.** That is a hard constraint — a host that refuses dependency build
25
+ scripts (iPad's DSH Go aborts pnpm with `ERR_PNPM_IGNORED_BUILDS`) fails the whole
26
+ install otherwise. 0.5.6–0.5.20 pulled `ssh2` into `dependencies` and hit exactly
27
+ that; 0.5.5 (zero deps) installed clean in the same installer.
28
+ `scripts/check-install-safe.mjs` keeps it that way. `ssh2` is needed only by the
29
+ SSH terminal and is deliberately **not** a dependency — install it yourself
30
+ (`pnpm add ssh2` in the profile) if you want that panel.
31
+
23
32
  Verify after restart: `GET http://127.0.0.1:45917/mesh/v1/health` returns JSON containing `{"app":"dsh-mesh","machine":"<name>",...}`.
24
33
 
25
34
  ## What it does at runtime
@@ -34,7 +43,7 @@ Verify after restart: `GET http://127.0.0.1:45917/mesh/v1/health` returns JSON c
34
43
  - One-click install: the inline "新版本 vX" link calls `POST /mesh/api/upgrade` (same-origin loopback only). It downloads the npm tarball for that version, verifies `dist.integrity` (sha512), extracts to a sibling staging dir, runs a real `import()` loadability check, backs up the old directory (`.mesh-upgrade-backup-*`, last 3 kept) and atomically swaps. Any failure keeps the old version and returns the failing stage. The result classifies the change: `restartRequired` only when `lib/` changed (plus version-only bumps), `reloadRequired` when only `client/` changed.
35
44
  - A successful install writes `upgrade.json` under the mesh state dir; until the process restarts, `GET /mesh/api/update` reports `pendingUpgrade` so the UI offers **重启生效** (`POST /mesh/api/upgrade/restart`) or **重载界面** instead of installing again (`POST /mesh/api/upgrade/reload` uses DSH Desktop's built-in `desktopSettingsController.reloadRenderer()`, the same action as Settings → Developer options → Reload interface; other hosts fall back to a page reload). On DSH Desktop the restart goes through the host's own `desktopSettingsController.restart()` (native confirm + ordered relaunch); plain `dsh web`/headless falls back to dshmarket's self-restart (`POST /dsh-market/api/v1/restart`) when that plugin is installed and not under a detected systemd supervisor. When neither entry exists the response is `mode:"manual"` with an explicit reason — it never pretends a restart happened.
36
45
  - The prefilled feedback issue carries the same diagnostics text as the diagnostics section; `buildDiagnostics()` deliberately excludes secrets (pairing code, tsnet auth key). The author's email (`geekstartup@163.com`) is the fallback when GitHub is unreachable.
37
- - **First-contact approval (default on).** An inbound task from a machine that is not in `state.json`'s `approvedPeers` is stored with `status: "needs-approval"` and answered with **HTTP 202** `{ok:true,pendingApproval:true}`; no agent session is created. The owner allows or denies it in the panel (`POST /mesh/api/approval` `{id,action:"allow"|"deny"}`); allowing adds the peer to `approvedPeers` and immediately runs the stored task. `POST /mesh/api/approval/revoke` `{machine}` removes trust. Replies (a task whose `thread` matches an outbound dispatch to the same machine) bypass the gate — otherwise the result would never come back. With `requirePairing` on (or the pairing switch enabled) the gate is skipped: pairing is the stronger trust gesture.
46
+ - **First-contact approval (default on).** An inbound task from a machine that is not in `state.json`'s `approvedPeers` is stored with `status: "needs-approval"` and answered with **HTTP 202** `{ok:true,pendingApproval:true}`; no agent session is created. The owner allows or denies it in the panel (`POST /mesh/api/approval` `{id,action:"allow"|"deny"}`); allowing adds the peer to `approvedPeers` and immediately runs the stored task. `POST /mesh/api/approval/revoke` `{machine}` removes trust. Replies bypass the gate — otherwise the result would never come back: a reply declares `answers: <task id>` naming one of this machine's outbound dispatch ids; for peers that do not declare it, a task whose `thread` matches an unclaimed outbound dispatch to the same machine (within `replyWindowMs`, default 30 min) still counts. With `requirePairing` on (or the pairing switch enabled) the gate is skipped: pairing is the stronger trust gesture.
38
47
  - `GET /mesh/api/demo` returns a read-only snapshot of this machine (platform, CPU, memory, load, uptime, a few runtimes) used by the panel's single-machine demo. It contains no secrets and changes no state.
39
48
  - `/mesh/api/state` additionally exposes `approvals[]` (pending first-contact tasks, only present when the debug gate below is on) and `approvedPeers[]` (`{machine,address,at}`).
40
49
 
@@ -61,7 +70,7 @@ These are outcomes, not a fixed feature list: the peer agent can run any command
61
70
 
62
71
  `peer` accepts a machine name, an instance id, or `ip:port`. **Do not pass `machine/user`** — `from` fields look like `machine/user`, but the peer key is the machine name only.
63
72
 
64
- Reuse the same `thread` value for the same piece of work: the receiving side reuses one session per `thread`, which saves tokens and keeps context. Use `noWake: true` for pure acknowledgements — otherwise a task wakes an agent session on the peer.
73
+ Reuse the same `thread` value for the same piece of work: the receiving side reuses one session per `thread`, which saves tokens and keeps context. Use `noWake: true` for pure acknowledgements — otherwise a task wakes an agent session on the peer. When an agent answers a task it received, the plugin attaches `answers: <task id>` automatically, so the peer routes the result to the exact dispatch instead of guessing from the thread.
65
74
 
66
75
  `newSession: true` forces a fresh session while keeping the same conversation key (i.e. it is still the same conversation, with a clean context).
67
76
 
@@ -121,6 +130,9 @@ the home board, enabled while the peer is online):
121
130
  plugin generates an RSA key (PKCS#1 PEM — ssh2 cannot read Node's ed25519 export),
122
131
  appends the public key to the peer's `authorized_keys` idempotently, then proves it
123
132
  with a fresh private-key-only connection. A different username falls back to password.
133
+ - The SSH panel needs the optional `ssh2` module, which is **not** installed by the
134
+ plugin (see Install). Missing it is reported as "SSH 终端需要额外的 ssh2 模块…" and
135
+ nothing else degrades; `ssh-host.js` loads it lazily so the plugin always mounts.
124
136
  - The private key and credentials live under the profile's mesh directory (mode 0600);
125
137
  they are never broadcast and never included in the peer card.
126
138
 
@@ -192,6 +204,7 @@ Override by id in the profile's `cordis.patch.yml`:
192
204
  | `threadWindowMs` | natural | `3600000` | Window for the cap above |
193
205
  | `threadCooldownMs` | natural | `5000` | Cooldown between session-creating wakes |
194
206
  | `minTaskChars` | natural | `24` | Bodies shorter than this are not woken (inbox only) |
207
+ | `replyWindowMs` | natural | `1800000` | How long an undeclared dispatch stays claimable as the target of a reply |
195
208
 
196
209
  ## Tailnet setup (the only step that needs an external account)
197
210
 
@@ -227,6 +240,9 @@ Outbound dispatch tries LAN first, then each tailnet channel in order.
227
240
  - A dsh host that can load cordis plugins with a client half (DSH Desktop, or `dsh web` + a profile).
228
241
  - Node >= 20 for development. Peer `@deepseek-ai/*` packages are provided by the host and are not bundled.
229
242
  - No Go toolchain and no Tailscale client are required by end users.
243
+ - No build toolchain or compiler is required to install: the package has no runtime
244
+ dependencies and runs no install scripts. The SSH terminal additionally wants the
245
+ optional `ssh2` module (user-installed; see Install).
230
246
 
231
247
  ## Development
232
248
 
@@ -248,8 +264,18 @@ npm run build:sidecar # rebuild the Go tsnet sidecar (cross-platform)
248
264
  - `README.md` — user-facing entry (Chinese): what it gives you, 5-minute start, safety, FAQ
249
265
  - `docs/DESIGN-NOTES.md` — the old long-form README: multicast/scan/firewall details, tsnet, identity, full config table, security model, limits, development
250
266
  - `DESIGN.md` — design rationale, trade-offs and post-mortems (Chinese)
251
- - `Placement设计.md` — placement design and implementation record (Chinese)
252
- - `设备身份与多通道设计.md` — identity and multi-channel design (Chinese)
267
+ - `ROADMAP.md` — the single roadmap: seven directions x versions, gates, metrics, risks (Chinese)
268
+ - `docs/roadmap/` — per-direction sub-roadmaps: `route.md` `security.md` `protocol.md` `adapter.md` `trace.md` `ui.md` `play.md` (Chinese)
269
+ - `docs/GROWTH.md` — positioning, competition, community and release cadence (Chinese)
270
+ - `docs/EVIDENCE.md` — where every number in the roadmap comes from (Chinese)
271
+ - `docs/DECISIONS.md` — historical decision log (Chinese)
272
+ - `PROTOCOL-COMPARISON.md` — comparison against A2A / MCP / ACP and peers (Chinese)
273
+ - `docs/PLUGIN-SPEC.md` — external spec: requirements, ports, host capability levels
274
+ - `docs/design/` — design and implementation records:
275
+ - `Placement设计.md` — placement design and implementation record (Chinese)
276
+ - `设备身份与多通道设计.md` — identity and multi-channel design (Chinese)
277
+ - `同机多Agent设计.md` — one node per machine, multiple agents attached (Chinese)
278
+ - `任务追踪设计.md` — layered task accounting design (Chinese)
253
279
  - `docs/index.html` — user-facing showcase, Chinese (GitHub Pages)
254
280
  - `docs/demo.html` — 60-second animated walkthrough (schematic; connects to nothing)
255
281
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-mesh",
3
- "version": "0.5.20",
3
+ "version": "0.5.22",
4
4
  "type": "module",
5
5
  "description": "把跑不完的活交给另一台电脑;跑完,结果回到你面前。两台装了 DSH 的电脑各装一次,自动互相发现,任务派过去由对端的 agent 执行,结果派回来。Hand a long task to another machine: your DSH instances find each other, the peer runs it, and the result comes back. No pairing codes, no IPs, no Tailscale client.",
6
6
  "license": "MIT",
@@ -69,13 +69,14 @@
69
69
  "selftest:update": "node lib/_selftest-update.mjs",
70
70
  "selftest:upgrade": "node lib/_selftest-upgrade.mjs",
71
71
  "selftest:approval": "node lib/_selftest-approval.mjs",
72
- "test": "npm run check && npm run selftest && npm run selftest:prompt && npm run selftest:at && npm run selftest:at:host && npm run selftest:pairing && npm run selftest:approval && npm run selftest:switch && npm run selftest:client && npm run selftest:caps && npm run selftest:release && npm run selftest:reply && npm run selftest:reasoning && npm run selftest:resume && npm run selftest:persist && npm run selftest:layout && npm run selftest:diagnostics && npm run selftest:osinfo && npm run selftest:peerweb && npm run selftest:webtarget && npm run selftest:webfence && npm run selftest:webhost && npm run selftest:sshtarget && npm run selftest:update && npm run selftest:upgrade",
73
- "check": "node scripts/check-version.mjs && node scripts/check-tdz.mjs && node --check lib/index.js && node --check lib/layout.js && node --check lib/discovery.js && node --check lib/conversation.js && node --check lib/identity.js && node --check lib/capabilities.js && node --check lib/prompt.js && node --check lib/at-mention.js && node --check lib/pairing.js && node --check lib/switch.js && node --check lib/scan.js && node --check lib/update.js && node --check lib/upgrade.js && node --check lib/peer-web.js && node --check lib/web-target.js && node --check lib/web-fence.js && node --check lib/ssh-target.js && node --check lib/tsnet/download.js && node --check lib/tsnet/manager.js && node --check lib/tsnet/bridge.js && node --check lib/tsnet/channels.js && node --check client/client.js && node --check scripts/release-plan.mjs && npm run check:loadable && npm run check:docs",
72
+ "test": "npm run check && npm run selftest && npm run selftest:prompt && npm run selftest:at && npm run selftest:at:host && npm run selftest:pairing && npm run selftest:approval && npm run selftest:switch && npm run selftest:client && npm run selftest:caps && npm run selftest:release && npm run selftest:reply && npm run selftest:reasoning && npm run selftest:resume && npm run selftest:persist && npm run selftest:layout && npm run selftest:diagnostics && npm run selftest:osinfo && npm run selftest:peerweb && npm run selftest:webtarget && npm run selftest:webfence && npm run selftest:webhost && npm run selftest:sshtarget && npm run selftest:update && npm run selftest:upgrade && npm run selftest:sshdep",
73
+ "check": "node scripts/check-version.mjs && npm run check:install && node scripts/check-tdz.mjs && node --check lib/index.js && node --check lib/layout.js && node --check lib/discovery.js && node --check lib/conversation.js && node --check lib/identity.js && node --check lib/capabilities.js && node --check lib/prompt.js && node --check lib/at-mention.js && node --check lib/pairing.js && node --check lib/switch.js && node --check lib/scan.js && node --check lib/update.js && node --check lib/upgrade.js && node --check lib/peer-web.js && node --check lib/web-target.js && node --check lib/web-fence.js && node --check lib/ssh-target.js && node --check lib/tsnet/download.js && node --check lib/tsnet/manager.js && node --check lib/tsnet/bridge.js && node --check lib/tsnet/channels.js && node --check client/client.js && node --check scripts/release-plan.mjs && npm run check:loadable && npm run check:docs",
74
74
  "build:sidecar": "bash scripts/build-sidecar.sh",
75
75
  "verify:mirror": "node scripts/verify-lan-mirror.mjs",
76
76
  "release:plan": "node scripts/release-plan.mjs",
77
77
  "release-plugin": "bash scripts/release-plugin.sh",
78
78
  "check:loadable": "node scripts/check-loadable.mjs --allow-missing-runtime-dep",
79
+ "check:install": "node scripts/check-install-safe.mjs",
79
80
  "check:deploy": "node scripts/check-loadable.mjs",
80
81
  "check:scope": "python3 tools/scopecheck.py lib/index.js",
81
82
  "prepublishOnly": "npm test && node scripts/check-tarball.mjs",
@@ -88,7 +89,8 @@
88
89
  "selftest:webtarget": "node lib/_selftest-web-target.mjs",
89
90
  "selftest:webfence": "node lib/_selftest-web-fence.mjs",
90
91
  "selftest:webhost": "node lib/_selftest-webhost.mjs",
91
- "selftest:sshtarget": "node lib/_selftest-ssh-target.mjs"
92
+ "selftest:sshtarget": "node lib/_selftest-ssh-target.mjs",
93
+ "selftest:sshdep": "node lib/_selftest-ssh-dep.mjs"
92
94
  },
93
95
  "publishConfig": {
94
96
  "registry": "https://registry.npmjs.org/",
@@ -142,8 +144,5 @@
142
144
  },
143
145
  "engines": {
144
146
  "node": ">=20"
145
- },
146
- "dependencies": {
147
- "ssh2": "^1.16.0"
148
147
  }
149
148
  }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * 校验「这个包能装进跑不了构建脚本的宿主」。
3
+ *
4
+ * ── 为什么要有这道闸(真实事故,2026-11-23)─────────────────────────
5
+ * 0.5.6 起把 `ssh2` 写进了 `dependencies`。ssh2 自带一个安装脚本
6
+ * `install: node install.js`(去编译可选的原生加速模块 cpu-features),于是
7
+ * 每个装这个插件的宿主都会被要求跑一次构建:
8
+ *
9
+ * · macOS / Linux / Android(termux) 上有 node 和编译器,装得上,所以没人发现;
10
+ * · iPad 上的 DSH Go 装不上 —— 宿主不允许依赖跑构建脚本,pnpm 直接抛
11
+ *
12
+ * [ERR_PNPM_IGNORED_BUILDS] Ignored build scripts:
13
+ * cpu-features@0.0.10, ssh2@1.17.0
14
+ *
15
+ * 整次安装失败,插件根本装不上去。对照实验:同为 iPad 的 0.5.5 零依赖,
16
+ * 同一个安装器里 `Done in 2.6s`,干净通过。
17
+ *
18
+ * 结论写进规则:**运行时依赖必须为空**,或者只能是已核实「没有 preinstall /
19
+ * install / postinstall 脚本、纯 JS」的包 —— 后者要显式进下面的 ALLOW,
20
+ * 并写清核实方式,别靠"看起来没问题"。
21
+ *
22
+ * 需要可选能力(比如 SSH 用的 ssh2)时:不要放依赖里。按需 `import()` / `require()`
23
+ * 并在缺失时给一句能动手的话(见 `lib/ssh-host.js`),装不装由用户决定。
24
+ *
25
+ * 跑法:node scripts/check-install-safe.mjs (已挂在 npm run check 里)
26
+ */
27
+ import { readFileSync } from "node:fs";
28
+ import { dirname, join } from "node:path";
29
+ import { fileURLToPath } from "node:url";
30
+
31
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
32
+ const pkg = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8"));
33
+
34
+ /**
35
+ * 允许出现在 dependencies / optionalDependencies 里的包。
36
+ *
37
+ * **当前必须为空**:加任何一项之前,先确认它没有 preinstall/install/postinstall
38
+ * 脚本(`npm view <包>@<版本> scripts`),并把核实结论写在下面。
39
+ * optionalDependencies 也一样会触发构建脚本,别指望"可选"能绕过 —— 实测
40
+ * `optionalDependencies: { ssh2 }` 在同一个受限安装器里仍然抛
41
+ * ERR_PNPM_IGNORED_BUILDS。
42
+ */
43
+ const ALLOW = /** @type {Record<string, string>} */ ({});
44
+
45
+ /** 包自己的安装脚本同样会在用户机器上跑,一律不要。 */
46
+ const FORBIDDEN_SELF_SCRIPTS = ["preinstall", "install", "postinstall", "prepare"];
47
+
48
+ const failures = [];
49
+
50
+ for (const name of FORBIDDEN_SELF_SCRIPTS) {
51
+ if (pkg.scripts?.[name]) {
52
+ failures.push(
53
+ `package.json 的 scripts.${name} 会在用户安装时执行;这个包必须"装即用、不跑脚本"。`,
54
+ );
55
+ }
56
+ }
57
+
58
+ const declared = {
59
+ ...(pkg.dependencies ?? {}),
60
+ ...(pkg.optionalDependencies ?? {}),
61
+ };
62
+
63
+ for (const name of Object.keys(declared)) {
64
+ if (ALLOW[name]) continue;
65
+ failures.push(
66
+ `运行时依赖 ${name}@${declared[name]} 未核实「无构建脚本」。\n` +
67
+ ` 依赖的安装脚本在 iPad 这类宿主上跑不了,会让整次安装失败(0.5.6–0.5.20 真踩过)。\n` +
68
+ ` 要保留它:先 npm view ${name}@<版本> scripts 确认没有 preinstall/install/postinstall,\n` +
69
+ ` 再加进 scripts/check-install-safe.mjs 的 ALLOW 并写明核实结论。\n` +
70
+ ` 只是"要用的时候才需要"的能力(如 ssh2):从依赖里去掉,按需 import() 即可。`,
71
+ );
72
+ }
73
+
74
+ if (failures.length > 0) {
75
+ console.error("✗ 安装安全性检查未通过:");
76
+ for (const line of failures) console.error(` - ${line}`);
77
+ process.exit(1);
78
+ }
79
+
80
+ const deps = Object.keys(declared);
81
+ console.log(
82
+ deps.length === 0
83
+ ? "✓ 零运行时依赖(安装不需要构建脚本)"
84
+ : `✓ 运行时依赖均已核实无构建脚本:${deps.join(", ")}`,
85
+ );