dsh-plugin-mesh 0.3.30 → 0.3.31

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 ADDED
@@ -0,0 +1,165 @@
1
+ # AGENTS.md — operating guide for coding agents
2
+
3
+ This file is for AI agents working **on** this repository. If you only want to
4
+ **use** the plugin, read [`llms.txt`](./llms.txt) instead — it is short and factual.
5
+
6
+ Project: `dsh-plugin-mesh`, a cordis plugin for DeepSeek Harness (dsh). MIT.
7
+ Language note: `README.md` is Chinese and long (it contains design rationale and
8
+ post-mortems). This file is the English, task-oriented entry point.
9
+
10
+ ---
11
+
12
+ ## 1. What this codebase is
13
+
14
+ A dsh plugin has two halves that ship in one npm package:
15
+
16
+ | Half | Entry | Runs in |
17
+ |---|---|---|
18
+ | Host | `lib/index.js` | the dsh host process (Node) |
19
+ | Client | `client/client.js` | the browser/Electron renderer |
20
+
21
+ `client/client.js` is a **hand-written bundle**, not built by a bundler. It must
22
+ call `window.__ModuleLoader__.load({ id: "<package name>", factory })` and the `id`
23
+ must equal the package name exactly. It may only `require("react")` and
24
+ `require("react/jsx-runtime")`.
25
+
26
+ The plugin is mounted by `dsh.bundle.patch` → `cordis.patch.yml`, which does one
27
+ `insert` of `{ id: mesh, name: dsh-plugin-mesh }`. Client UI is declared by
28
+ `dsh.client.platform = "web"` plus an `exports["./client"]` entry.
29
+
30
+ There is a third, separate program: `sidecar/` is a **Go** binary that runs a
31
+ userspace Tailscale node (tsnet). It is compiled per platform, published as GitHub
32
+ release assets, and downloaded at runtime by `lib/tsnet/download.js`.
33
+
34
+ ## 2. Zero to running (development)
35
+
36
+ ```bash
37
+ npm install # dev deps only; @deepseek-ai/* come from the host
38
+ npm run check # fast, always run this first
39
+ npm test # full suite, ~90 s, network-free
40
+ ```
41
+
42
+ To run a real isolated host (two instances can discover each other on one machine):
43
+
44
+ ```bash
45
+ MACHINE=meshdev PORT=45918 ./dev-setup.sh meshtest /tmp/dsh-mesh-dev
46
+ DSH_HOME=/tmp/dsh-mesh-dev ELECTRON_RUN_AS_NODE=1 \
47
+ "/Applications/DSH Desktop.app/Contents/MacOS/DSH Desktop" \
48
+ dev-boot.mjs --profile meshtest --port 8877 --no-open
49
+ ```
50
+
51
+ `dev-setup.sh` copies the plugin into the profile's `node_modules`; a **symlink
52
+ will not work** — dsh's profile package resolver rejects packages whose realpath
53
+ is outside `<profile>/node_modules`.
54
+
55
+ `dev-boot.mjs` exists because `desktop-cli.js` only installs the profile package
56
+ resolver inside `app.asar`; this installation is unpacked, so the resolver has to
57
+ be installed manually.
58
+
59
+ The dev host's web server is **not** behind DSH Desktop's request gate, so
60
+ `/mesh/api/*` can be driven with curl there — production cannot (it returns 403
61
+ unless the request carries the renderer token).
62
+
63
+ ## 3. Hard constraints — do not violate
64
+
65
+ 1. **Never let a probe failure look like a negative fact.** `ENOENT` means "not
66
+ installed"; a timeout means "we did not get an answer". These must stay
67
+ distinguishable and visible (`probeErrors`, `runtimesIncomplete`,
68
+ `routeDecision`, `dispatchError`). Collapsing them caused a real incident: a
69
+ busy Mac reported "no runtimes installed".
70
+ 2. **Never leave a documented command that does not exist.** The README is served
71
+ verbatim on the npm page, and the plugin catalog explicitly checks descriptions
72
+ against code. A made-up flag was caught in review.
73
+ 3. **Changing a schema `.default()` is usually not enough.** `cordis.patch.yml` in
74
+ the repo and in the user's profile pin values that override the default. Check
75
+ all three:
76
+ ```bash
77
+ grep -rn "theKey" cordis.patch.yml ~/.dsh/profiles/*/cordis.patch.yml
78
+ ```
79
+ 4. **`config:` in a patch is replaced wholesale, not merged.** Adding one key
80
+ without restating the others silently resets them to schema defaults.
81
+ 5. **Verify side-effecting scripts by running them, not by `bash -n`.** A reference
82
+ to an undefined `$REPO_ROOT` passed syntax checking and turned "delayed restart"
83
+ into a silent no-restart. Use `scripts/restart-dsh.sh --check-only` to exercise
84
+ the preflight without touching the running app.
85
+ 6. **`node --check` cannot catch TDZ.** `scripts/check-tdz.mjs` exists for that;
86
+ keep it in `npm run check`.
87
+ 7. **Do not trust "it looks fine".** This project has repeatedly shipped
88
+ "wired but not actually connected" changes (a gate that was only mentioned in a
89
+ comment, `install.sh` not copying `scripts/`, a placeholder that hid a missing
90
+ file). When you add a gate, prove it has teeth: break the input and watch it fail.
91
+
92
+ ## 4. Architecture map
93
+
94
+ ```
95
+ lib/index.js host half: config schema, discovery orchestration, peer HTTP
96
+ server, agent tools, UI routes, inbound task routing, wake logic
97
+ lib/discovery.js UDP multicast registry, endpoint-level liveness, fingerprint claim
98
+ lib/scan.js active subnet scan
99
+ lib/identity.js persistent UUID + OS machine fingerprint (claim only)
100
+ lib/conversation.js conversation key + reply target (both sides compute independently)
101
+ lib/capabilities.js runtime/GPU/capability collection, sanitising, staleness
102
+ lib/prompt.js task prompt text generation (pure, unit-tested)
103
+ lib/tsnet/ sidecar download/verify, process manager, tailnet HTTP bridge
104
+ client/client.js renderer: sidebar icon + Mesh panel, hand-written bundle
105
+ sidecar/ Go: tsnet node + control HTTP API + port forwarding
106
+ scripts/ build/release/verify/push/submit tooling
107
+ docs/ GitHub Pages showcase site
108
+ ```
109
+
110
+ Key data flow for an inbound task: `POST /mesh/v1/task` → `handleInboundTask` →
111
+ `classifyInbound` (gates: noWake, min length, greeting, per-thread cap, cooldown) →
112
+ reuse the session bound to the conversation key, or create one via `wakeAgent` →
113
+ inject the prompt → the peer's agent replies by calling `mesh_run`.
114
+
115
+ ## 5. Test map
116
+
117
+ | Suite | Command | Covers |
118
+ |---|---|---|
119
+ | Core | `npm run selftest` | discovery, endpoints, conversation keys (52) |
120
+ | Capabilities | `npm run selftest:caps` | sanitising, GPU parsing, retry-on-timeout, claim rules (64) |
121
+ | Client render | `npm run selftest:client` | bundle loads, `apply()` registers slots, component output (12) |
122
+ | Prompt | `npm run selftest:prompt` | reply target must be a machine name, not `machine/user` (10) |
123
+
124
+ `lib/_selftest-newsession.mjs` is a manual end-to-end check that needs a dev host
125
+ running; it is deliberately not part of `npm test` because it creates real agent
126
+ sessions (costs tokens).
127
+
128
+ Everything in `npm test` is **network-free** — the discovery self-test uses a
129
+ private multicast group so it cannot pollute a real LAN.
130
+
131
+ ## 6. Releasing
132
+
133
+ ```bash
134
+ npm run check && npm test
135
+ npm run release-plugin -- --publish # tarball -> GitHub release -> LAN mirror
136
+ npm publish # npm; publishConfig pins the public registry
137
+ ```
138
+
139
+ Then upgrade other machines with the command printed by `release-plugin.sh`.
140
+ If the dsh host is on this machine, `scripts/restart-dsh.sh --install [delay]`
141
+ restarts it from launchd so the restart survives killing the app.
142
+
143
+ Notes:
144
+ - `scripts/check-tarball.mjs` validates the **published artifact**, not the source
145
+ tree, because `files` in `package.json` decides what users actually get.
146
+ - npm's "staged publishing" makes a new version appear in metadata before its
147
+ tarball is downloadable. Do not declare success until the tarball returns 200.
148
+ - Keep `llms.txt` and `docs/llms.txt` identical: `npm run check` verifies it.
149
+
150
+ ## 7. Things that will waste your time if you do not know them
151
+
152
+ - **Android has no `/tmp`** (read-only root). Use `$TMPDIR`.
153
+ - **GUI-launched dsh inherits a minimal `PATH`**; runtime probes must augment it.
154
+ - **Windows**: `%LOCALAPPDATA%\Microsoft\WindowsApps` is full of zero-byte Store
155
+ alias stubs — it must not be treated as evidence that a runtime exists.
156
+ - **git-over-https to github.com is blocked on the author's network.** Use
157
+ `scripts/push-via-api.py` (exact commit replication via the REST API) instead of
158
+ `git push`.
159
+ - **`github.io` reachability varies** in mainland China.
160
+ - The author's machines: a Mac (this repo), `hos` (Android), `文超-win` (Windows).
161
+ Tasks are dispatched between them with `mesh_run`.
162
+
163
+ ## 8. Contact
164
+
165
+ geekstartup@163.com · https://github.com/peng456/dsh-plugin-mesh/issues
package/README.en.md ADDED
@@ -0,0 +1,107 @@
1
+ # dsh-plugin-mesh — English quickstart
2
+
3
+ > Discover other DeepSeek Harness (dsh) instances on your network and dispatch tasks
4
+ > between machines in both directions. No pairing codes, no IP entry, no Tailscale
5
+ > client to install.
6
+
7
+ [中文完整文档](README.md) · [llms.txt](llms.txt) (machine-oriented facts) · [AGENTS.md](AGENTS.md) (for coding agents)
8
+
9
+ ---
10
+
11
+ ## What it is
12
+
13
+ A dsh plugin. Install it on two or more machines and they find each other on the
14
+ LAN, show up in a sidebar panel, and accept tasks from one another. The receiving
15
+ machine wakes its own agent to do the work, and the result is dispatched back.
16
+
17
+ When machines are not on the same network, an optional bundled userspace Tailscale
18
+ node (tsnet) provides a second channel. It is a separate Go binary, downloaded per
19
+ platform on first use — end users need neither a Go toolchain nor the Tailscale
20
+ client.
21
+
22
+ ## Install
23
+
24
+ ```bash
25
+ dsh plugin add dsh-plugin-mesh # 'desktop' profile: in DSH Desktop's own terminal
26
+ dsh plugin --profile web add dsh-plugin-mesh # other profiles: a normal terminal works
27
+ ```
28
+
29
+ From source: `git clone https://github.com/peng456/dsh-plugin-mesh && cd dsh-plugin-mesh && ./install.sh`
30
+
31
+ **Restart the dsh host afterwards** — plugins load at startup. You should then see a
32
+ **Mesh** entry in the sidebar.
33
+
34
+ ## Three steps
35
+
36
+ 1. Install on every machine.
37
+ 2. Restart dsh on every machine.
38
+ 3. Open the **Mesh** panel. Seeing another machine means it worked.
39
+
40
+ If the panel is empty, check in this order: (a) same LAN, (b) the peer also installed
41
+ and restarted, (c) the peer's firewall allows TCP `45917` and UDP `45892`. Multicast
42
+ is often blocked by routers — the panel's **Scan subnet** button works around that.
43
+
44
+ ## What you get
45
+
46
+ - **Zero-config discovery** — UDP multicast heartbeat on `239.255.42.99:45892`, plus
47
+ an active subnet scan when multicast is blocked.
48
+ - **Capability cards** — each machine reports its runtimes (Node / Python / Go /
49
+ Docker / …), CPU cores, memory and GPU, so you can tell before dispatching whether
50
+ a machine can do the job.
51
+ - **Bidirectional dispatch** — the peer's agent can dispatch results back; both sides
52
+ compute the same conversation key independently, without negotiation.
53
+ - **Two channels with automatic failover** — LAN first, tsnet as backup (a free
54
+ Tailscale account and an auth key are required; create one at
55
+ <https://console.tailscale.com/admin/settings/keys>, and tick **Reusable**). The backup
56
+ channel is actively probed even while the LAN is healthy, so it is known-good
57
+ rather than assumed-good.
58
+ - **Traceable routing** — every task records why it went where it went, and why it
59
+ failed if it did. Both are readable from the peer.
60
+
61
+ ## Security defaults — read this
62
+
63
+ **With `requirePairing: false` (the default), any host that can reach TCP `45917` can
64
+ POST a task, and that task wakes an agent session** using the configured
65
+ `permissionPreset`. Discovery is intentionally public so you can see machines before
66
+ deciding to talk to them.
67
+
68
+ On an untrusted network (café, dorm, office):
69
+
70
+ 1. Set `requirePairing: true` in your profile's `cordis.patch.yml`.
71
+ 2. Make the pairing secret identical on both machines (the Mesh panel has a field for it).
72
+
73
+ Note the token travels in a plain HTTP header: it guards against stray devices on
74
+ the network, not against a network sniffer. It lives in `~/.dsh/mesh/state.json`
75
+ (mode 0600) and is never included in the multicast card.
76
+
77
+ ## Configuration
78
+
79
+ Override by id in the profile's `cordis.patch.yml`:
80
+
81
+ ```yaml
82
+ - id: mesh
83
+ config:
84
+ requirePairing: true
85
+ permissionPreset: workspace-write
86
+ ```
87
+
88
+ `config:` is replaced **wholesale**, not merged — restate any keys you want to keep.
89
+ The full key list with defaults is in [`llms.txt`](llms.txt#configuration).
90
+
91
+ ## Requirements
92
+
93
+ - A dsh host that can load cordis plugins with a client half (DSH Desktop, or `dsh web`).
94
+ - Node >= 20 for development. `@deepseek-ai/*` packages are supplied by the host.
95
+
96
+ ## More
97
+
98
+ | | |
99
+ |---|---|
100
+ | Full documentation (Chinese) | [README.md](README.md) |
101
+ | Machine-oriented facts / config table | [llms.txt](llms.txt) |
102
+ | Guide for coding agents | [AGENTS.md](AGENTS.md) |
103
+ | Showcase page (Chinese) | https://peng456.github.io/dsh-plugin-mesh/ |
104
+ | Issues | https://github.com/peng456/dsh-plugin-mesh/issues |
105
+ | Contact | geekstartup@163.com |
106
+
107
+ MIT licensed. Not affiliated with DeepSeek.
package/README.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # dsh-plugin-mesh
2
2
 
3
+ > 🌐 **想先看看它长什么样、怎么用?** 打开展示页:<https://peng456.github.io/dsh-plugin-mesh/>
4
+ > (面向使用者、从零讲起;本 README 面向开发与排障。)
5
+
6
+ > 🤖 **给 agent / 英文读者**:[`llms.txt`](llms.txt)(机器可读的事实:工具、配置项与默认值、端口)
7
+ > · [`AGENTS.md`](AGENTS.md)(改这个仓库前的硬约束与坑)· [`README.en.md`](README.en.md)(英文快速上手)· [`DESIGN.md`](DESIGN.md)(设计原理与复盘)
8
+ >
9
+ > 本 README 是完整中文文档,含设计取舍与踩坑记录,比较长。
10
+
3
11
  DSH 的 Mesh 插件:**启动后自动发现同一网段的其他 DSH 实例**,在侧栏提供一个
4
12
  操作页面显示各机器的在线状态,并支持把任务派给对端的 agent 执行。
5
13
  **不在同一网段也行** —— 内置用户态 Tailscale 节点,可跨互联网自组网,功能同级。
@@ -25,75 +33,7 @@ DSH 的 Mesh 插件:**启动后自动发现同一网段的其他 DSH 实例**
25
33
 
26
34
  ---
27
35
 
28
- ## 发现机制:两条互补的路
29
-
30
- 只靠组播是不够的 —— **很多路由器/AP 会隔离客户端组播,Windows 防火墙默认也拦入站组播**。
31
- 所以这里同时用两条路,任一条通就能发现:
32
-
33
- | 路径 | 做法 | 优点 | 缺点 |
34
- |---|---|---|---|
35
- | **组播心跳** | 每 5s 向 `239.255.42.99:45892` 广播,同时监听 | 零配置、即时、不产生额外连接 | 可能被路由器/防火墙挡掉 |
36
- | **主动扫描** | 并发 GET 本网段每台机器的 `:45917/mesh/v1/health` | 只要 TCP 通就能成,最可靠 | 扫一次约 1~2 秒;254 个地址 |
37
-
38
- 再加一条**ping 保活**:每 10s GET 已知对端的 `/mesh/v1/health`,刷新在线状态。
39
- 这条让"发现"一旦建立就不再依赖组播 —— 即使组播完全不通,扫描见过一次之后也能一直维持。
40
-
41
- 扫描时机:**启动时**(带退避重试,因为常抢在对方启动之前)+ **每 60s** 一次 + UI 上手动触发。
42
-
43
- **默认端口 45917**。固定端口是"扫一下就能连上"的前提。同机跑多个实例时端口会被占用,
44
- 此时自动退回随机端口(组播仍能找到,但主动扫描扫不到它)。
45
-
46
- #### ⚠️ 45917 和"UI 面端口"是两回事,排查时别混
47
-
48
- 实测的**绑定范围**(这才是能不能从别的机器读到的唯一决定因素):
49
-
50
- | 端口 | 绑定 | 谁能读 |
51
- | --- | --- | --- |
52
- | `45917`(mesh 口) | `*:45917`(全网卡) | **局域网内任意机器** —— `/mesh/v1/health`(免鉴权)、`/mesh/v1/peers`(需配对) |
53
- | DSH 的 Web/GUI 端口(这台的 Mac 是 `43120`,Android 对端是 `3080`) | `127.0.0.1:<端口>`(**仅 loopback**) | 只有本机。`/mesh/api/state` 挂在这上面,**跨机一定读不到** |
54
-
55
- > 已在 **macOS 与 Android 两个独立平台**实测同构(不是某个平台的特性):
56
- > `127.0.0.1:<GUI端口>/mesh/api/state` → 200,`<LAN IP>:<GUI端口>/...` → 连不上;
57
- > 而 `<LAN IP>:45917/mesh/v1/health` → 200。GUI 端口各平台不同(loopback-only 相同)。
58
-
59
- 所以:
60
-
61
- - 想从 A 读 B 的**版本/能力** → `GET http://<B-ip>:45917/mesh/v1/health`。
62
- - `GET /mesh/api/state` **只能读自己**:它的 `peers[]` 里是**别人**的投影,
63
- 而**不含本机**(`discovery.peers()` 只投影 `#peers`,且 upsert 显式丢弃
64
- `id === this.#id`)。读本机的 version 要看 `state.self` 或直接打 `/mesh/v1/health`。
65
- - 跨机排查时**不要**把 GUI 端口写进任何文档或脚本 —— 它在对端一定是不通的,
66
- 而失败现象(连接超时/拒绝)看起来像"对端没开服务",很容易误诊。
67
- - **受限环境下本机 socket 表可能根本读不到**(Android 无 root:`ss` 报
68
- `netlink socket: Permission denied`、`netstat` 不支持 AF_INET、`/proc/net/tcp`
69
- 也 denied)。这时**别据"读不到"下结论** —— 只能靠**功能判据**:
70
- `192.168.x.x:<mesh端口>/mesh/v1/health` 通 → 对外可服务;
71
- 同一 IP 的 GUI 端口不通 → 证实它 loopback-only。
72
- "本机看不到 socket 表" + "跨机读 GUI 面失败" 两者叠加,现象与"对端没开服务"
73
- **完全一样** —— 这正是最容易误诊的组合,必须用双向探测把两者分开。
74
-
75
- > 这组区分是踩出来的:跨机验证重启时用 `/mesh/api/state` 会拿到 403/连不上,
76
- > 用 `/mesh/v1/health` 才拿得到对端自述的 `version`(判断"进程是否已重启"的
77
- > **唯一**可靠字段 —— `capabilities` 每轮定时重采,不反映进程版本)。
78
-
79
- #### ⚠️ 重启日志里的三行,**没有一行**能证明"新代码在跑"
80
-
81
- `scripts/restart-dsh.sh` 重启后会打三行自检。实测这三行各自的证据强度是:
82
-
83
- | 日志行 | 实际读的是什么 | 能证明什么 |
84
- | --- | --- | --- |
85
- | `[OK] 已重启:pid X → Y` | 进程表 | 有个进程起来了 —— **不**证明它加载了新代码 |
86
- | `[OK] 新代码已生效(instanceIds)` | `grep` **落盘**的 `state.json` | 几乎什么都不能证明:该字段是**持久化**的,上一版写进去之后一直留在文件里,所以这里**恒真** |
87
- | `磁盘上的插件版本 v`(原写作"已安装插件版本") | 读**磁盘**上 `package.json` | 磁盘是什么版本 —— 与进程**无关** |
88
36
 
89
- 踩过:升级窗口里磁盘 `16:11:06` 就已是 0.3.28,进程 `16:14:06` 才换。那三分钟里
90
- 上面几行**全是绿的**,但跑的还是旧代码。`VERSION` 是**启动时冻结**的常量,所以
91
- 只有**进程自述**才是硬证据 —— 而它只有 `/mesh/v1/health` 给得出。
92
-
93
- 现在脚本最后会真的去问进程:
94
-
95
- ```bash
96
- curl -fsS --max-time 3 http://127.0.0.1:45917/mesh/v1/health # 取 .version
97
37
  # 进程版本 ≠ 磁盘版本 → [WARN] 新代码**没**被加载,检查 plugins 挂载
98
38
  ```
99
39
 
@@ -384,24 +324,6 @@ sidecar 二进制(约 9MB gzip),缓存在 `~/.dsh/mesh/bin/`。
384
324
  (实测同输入连编两次逐字节相同),所以未改动的平台重编后 sha256 不变,**补新平台
385
325
  不会让已装的机器白重下 8.5MB**;用时间戳则每次发版全平台哈希都变。
386
326
 
387
- ### 为什么是"用户态"节点
388
-
389
- tsnet 不建 TUN 设备、不要 root、也不碰系统上装的 Tailscale,它跑在自己的用户态
390
- 网络栈里。代价是**宿主机路由不到 `100.x.y.z`**,所以 sidecar 必须在两个方向都代理:
391
-
392
- ```
393
- 入站:tailnet :45917 ──反代──▶ 127.0.0.1:45917 (并注入 X-Forwarded-For)
394
- 出站:插件 ──/__tsnet/fetch──▶ sidecar 用 tailnet 拨号
395
- ```
396
-
397
- 这也是 `discovery.js` 里对端记录多一个 `transport` 字段的原因:tailnet 对端自述的
398
- `host` 是它的**局域网** IP,跨互联网不可达,必须被实际观察到的 tailnet IP 覆盖。
399
-
400
- ### 整机一个节点
401
-
402
- 每个 sidecar 就是 tailnet 里的一个设备,所以**一台机器只有一个节点**。同机的多个
403
- DSH profile 通过 `~/.dsh/mesh/tsnet/rendezvous.json` 复用同一个 sidecar,不会重复
404
- 占用设备名额(免费版上限 100 台)。
405
327
 
406
328
  ### 用法
407
329
 
@@ -410,6 +332,11 @@ DSH profile 通过 `~/.dsh/mesh/tsnet/rendezvous.json` 复用同一个 sidecar
410
332
  1. 打开开关
411
333
  2. 粘贴 Tailscale 授权码(`tskey-auth-...`)—— **只需输入一次**,存进 `state.json`
412
334
  (权限 0600),重启不用再填
335
+ - 还没有授权码:先注册 / 登录 Tailscale(免费),再到
336
+ <https://console.tailscale.com/admin/settings/keys> 生成。
337
+ - **生成时必须勾 Reusable** —— 一次性码只能用一次,重启就会报 invalid key。
338
+ - 后台开了设备审批的,还要勾 Pre-approved。
339
+ - 插件里的「设置」直接给了这个地址,不用自己去后台翻。
413
340
  3. Headscale 用户另填「控制服务器地址」,官方用户留空
414
341
 
415
342
  节点名自动取机器名(`立朋-mac` → `dsh-mac`,`文超-win` → `dsh-win`),不用你填。
@@ -481,46 +408,6 @@ VPN,换网 MAC 就变;iOS / Android / macOS 现在默认按 SSID 使用随
481
408
 
482
409
  ---
483
410
 
484
- ## 实测验证状态
485
-
486
- 以下都在**真实 DSH host** 上跑出来(临时 DSH_HOME,未动你正在用的应用):
487
-
488
- | 项目 | 结果 |
489
- |---|---|
490
- | 配置装配进 profile | ✅ `--dump-config` 含本项目两行 |
491
- | 插件加载、`apply` 执行 | ✅ 挂载 5 个 UI 接口、注册 4 个工具 |
492
- | **两个真实 DSH 互相发现(仅扫描,组播全关)** | ✅ 双向,24 秒内(含启动竞态重试) |
493
- | 两个真实 DSH 互相发现(组播开) | ✅ 双向,1 秒内 |
494
- | **零配对派发任务** | ✅ `ok: true`,全程没有任何配对操作 |
495
- | **对端 agent 被唤醒** | ✅ 建了 `mesh-*` 会话,17 个事件,含任务提示词 + 线程 + 回派指令,`turn/start` → `assistant/attempt` |
496
- | **离线判定** | ✅ 杀掉对端后约 20 秒标记离线(ttl 20s) |
497
- | 固定端口被占用 → 回退 | ✅ 配置 45919、实际 63570 |
498
- | `requirePairing: true` 时 | ✅ 错误 token → 403;正确 token → 200 |
499
- | **首次启动询问名字** | ✅ 未命名时 `needsName=true`,输入框预填主机名 |
500
- | **改名立刻传播** | ✅ 改完 **2 秒内**对端就看到新名字(立即重新广播) |
501
- | **名字持久化** | ✅ 存 `state.json`,重启后仍是 `客厅的Mac` / `source=saved` |
502
- | 名字校验 | ✅ 空、含 `/`、超 32 字符均被拒 |
503
- | 配置优先 | ✅ 配置里写了 `machineName` 时改名返回 409,不静默覆盖 |
504
- | 重名检测 | ✅ 两端 `duplicateNames` 均正确列出 |
505
- | 客户端 bundle 被提供 | ✅ 出现在 `__DSH_BOOT__`,路由 200,内容与源码逐字节一致 |
506
- | UI 页面渲染 | ✅ 机器列表 / 任务记录两个 tab |
507
- | 不花你的 token | ✅ 测试环境无模型密钥,agent 止步于 `no API key` |
508
- | **`newSession` 强制新起会话** | ✅ 同一 thread 隔 8 秒发两条:带 `newSession` → 绑到两个不同 `mesh-*` 会话;**对照组不带 → 复用同一个**(证明差异确实来自这个标志) |
509
- | **能力名片双向交换** | ✅ 两个真实实例互相拿到对方完整 `runtimes`(node/python/go/docker/git/ffmpeg)+ CPU/内存/GPU |
510
- | **老版本对端向后兼容** | ✅ 对 0.3.18 与 0.3.24 的对端显示「能力未知」且不报错,其余功能照常 |
511
- | **同机两实例并存** | ✅ 两个 profile 同时在线,互不顶掉(指纹认领加了边界条件前会被互相删除) |
512
- | **探测失败可辨识 + 串行重试** | ✅ 自测里用「睡 4 秒再报版本」的假命令验证:首轮超时 → 串行重试拿到真值(7343ms) |
513
- | **Mesh 页面展示能力** | ✅ 每个运行时一枚徽章 + GPU + 规格,悬停给完整信息;三种「不知道」分开渲染 |
514
- | **客户端渲染(无浏览器)** | ✅ 12 项:假 module loader + 最小 react stub,遍历 `createElement` 返回树断言文案 |
515
-
516
- **没验证的**(如实说明):
517
- - 没在你**正在运行的** DSH Desktop 里验证 —— 需要重启应用,会掐断本次会话。
518
- 用 `dev-boot.mjs` 复现了真实主进程的模块解析行为来代替。
519
- - Windows 侧没跑(手上没那台机器)。代码跨平台,但 Windows 防火墙要放行 TCP 45917
520
- 和 UDP 45892。
521
- - 扫多端口(`scanPorts`)是我为了在同机测试才加的,真实两机场景用不到。
522
-
523
- ---
524
411
 
525
412
  ## 安装
526
413
 
@@ -717,42 +604,6 @@ agent 多出四个工具:
717
604
 
718
605
  ---
719
606
 
720
- ## 工作原理
721
-
722
- ### 唤醒:自包含实现,不依赖额外插件
723
-
724
- agent 没有事件循环,只在有回合时才思考。所以收到对端任务后,必须**建一个会话并让它跑起来**。
725
-
726
- DSH 提供了官方插件 `@deepseek-ai/dsh-webhook` 做这件事,但**本插件没有用它**,理由:
727
-
728
- 1. 它不在任何默认 bundle 里,靠补丁替用户插一行,会让"装一个插件"变成配置里两行,困惑
729
- 2. 更实际的问题:万一它已经被启用(比如你以后装了 GitHub webhook 插件),
730
- cordis 的 `provide` 遇到重名会直接抛错(`service "webhookRuntime" has been registered at <...>`),
731
- 而且那是在它的构造函数里,**本插件的安全网拦不住**
732
-
733
- 所以这里按官方 `createWebhookSession` 的做法自己走一遍,用到的都是 DSH 基础服务
734
- (桌面 profile 本来就全都有):
735
-
736
- ```
737
- ctx.permissionPresets.resolve / set 校验并设置权限 preset
738
- ctx.agentPresets.resolve / mount 解析并挂载 agent preset
739
- ctx.workspaceRegistry.create 建/取工作区
740
- ctx.agents.create 建 Agent
741
- ctx.sessionTitle.rename 给会话起名
742
- ctx.agentDefaultModel.currentSelection 取默认 provider/model
743
- agent.followup(createUserMessage(...)) ← 这一步才是"唤醒"
744
- ```
745
-
746
- 服务齐备时才启用(用 `ctx.inject([...])` 探测);缺任何一个就降级为"只收件不唤醒",
747
- 并在日志里说明缺了什么。**插件是自包含的,profile 里只多一行。**
748
-
749
- ### 为什么发现要两条路
750
-
751
- 我先只做了组播,后来加扫描,是因为组播在真实家庭网络里失败率比想象中高:
752
- AP isolation、Windows 防火墙默认策略、跨 VLAN,任何一个都能让它静默失效。
753
- 而"TCP 直连固定端口"只要网络通就能成。
754
-
755
- ---
756
607
 
757
608
  ## 配置项
758
609
 
@@ -990,189 +841,6 @@ DSH_HOME=/tmp/mesh-dsh ELECTRON_RUN_AS_NODE=1 \
990
841
  node lib/_selftest-discovery.mjs alpha 45900 9000 # 两个进程同时跑可验证互相发现
991
842
  ```
992
843
 
993
- ### ⚠️ 三个反复踩到的坑(改这个代码前请先读)
994
-
995
- **1. 改 schema 的 `.default()` 不等于改生效值。** `cordis.patch.yml` 里显式写了
996
- 的键会**覆盖** schema 默认值,用户 profile 里的 `cordis.patch.yml` 又是第三份。
997
- 所以改默认值时必须查三处:
998
-
999
- ```bash
1000
- grep -n "你要改的键" cordis.patch.yml ~/.dsh/profiles/*/cordis.patch.yml
1001
- ```
1002
-
1003
- 漏了的话现象是"代码改了、行为完全没变",极容易误判成代码没生效。
1004
-
1005
- **2. "探测失败"绝不能等同于"没有"。** 这个项目已经因此吃亏两次:
1006
-
1007
- - `execFile` 超时/失败一律降级成空 → 机器忙时名片报出"什么运行时都没装"
1008
- - 只有 `status` 没有原因 → 任务卡在 `dispatch-failed` 时无从查起(后来加了 `dispatchError`)
1009
-
1010
- 所以规矩是:**任何"我们没问出答案"的情况,都要和"答案是明确的否定"分开存**,
1011
- 并且要能被看见(`probeErrors` / `runtimesIncomplete` / `routeDecision` /
1012
- `dispatchError` 都是这条规矩的产物)。
1013
-
1014
- **3. 环境差异会伪装成功能故障。** 实测两次,两次都先怀疑错了方向:
1015
-
1016
- - Android 上**没有 `/tmp`** → `curl -o /tmp/...` 报 `(23) ... on write`,
1017
- 看着像网络问题,其实是根文件系统只读。对端命令一律用 `$TMPDIR`。
1018
- - **GUI 启动的 DSH 继承的 PATH 极简**(`/usr/bin:/bin:/usr/sbin:/sbin`),
1019
- Homebrew / `~/go/bin` / conda 全都不在 → 能力探测报"什么运行时都没装"。
1020
- 所以 `capabilities.js` 补全 PATH,`state().self.capabilityProbePath` 把实际
1021
- 用的 PATH 暴露出来。
1022
-
1023
- 教训:对端报"功能不对"时,**先确认那台机器的环境**(盘、PATH、shell),
1024
- 再怀疑代码。
1025
-
1026
- ### 能力名片(Placement 第 1 步)
1027
-
1028
- 每台设备启动后采集一次自己的能力并**挂在现有名片上**广播(不新增协议、
1029
- 不在心跳里探测):
1030
-
1031
- ```js
1032
- capabilities: {
1033
- os, arch, cpuCores, memMb,
1034
- runtimes: { node: "20.19", python: "3.12", go: "1.25", ... },
1035
- gpu: { present, name, vramMb } | null,
1036
- workspaceHints: ["~/projects"], // 家目录缩写成 ~,不带用户名
1037
- runtimesIncomplete: false, // true = 有探测项没探准,缺失不能当结论
1038
- capabilitiesAt: 1791999999999
1039
- }
1040
- ```
1041
-
1042
- 对面收到后净化(限长、封顶、剥控制字符)再存。**`null` 与 `{}` 语义不同**:
1043
- `null` = 还没报(老版本 / 刚开始采集 / **报来的东西被净化判为非法**)→ 该去问人;
1044
- `{}`(净化后的空壳)= 报过了确实没有 → 可以直接排除。
1045
- `runtimesIncomplete` 为真时同理不可用于硬门槛判断。
1046
-
1047
- #### ⚠️ `null` 有两种成因,而现有字段**都区分不了**(实测)
1048
-
1049
- `capabilities` 为 `null` 既可能是"对端**从来没有**这个字段"(老版本),也可能是
1050
- "对端报了、但内容非法被净化掉了"。两个坑:
1051
-
1052
- 1. **`capabilitiesStale` 不能用来区分。** `isCapabilityStale(null)` 返回的是
1053
- **`false`**(`lib/capabilities.js:510`:没报能力不是"过期",是"未知")。
1054
- 所以对 0.2.0 那台也会得到 `capabilitiesStale: false` —— 一个"看起来不陈旧、
1055
- 其实压根没这个字段"的**假阴性信号**。
1056
- 2. **净化会把两种成因合并成同一个 `null`。** 实测 `sanitizeCapabilities()`:
1057
- `undefined` / `null` / `"not-an-object"` / `42` **全部** → `null`。
1058
- 净化后的投影里已经不含"原始字段是否存在"的信息了。
1059
-
1060
- → Placement 想区分"**不支持**"和"**没采集完**",可靠判据是**版本**:
1061
- `version >= 0.3.25` 才保证名片里有 `capabilities` 字段(实测:0.3.25 起
1062
- `selfRecord` 含该字段,0.2.0 里出现次数为 **0**)。版本 `< 0.3.25` → 判"不支持",
1063
- 不要去问人、也不要当成"等它采集完"。
1064
-
1065
- > 注意版本判据的**前提**:它假设版本号和能力字节码**同步发布**。若将来给
1066
- > `0.2.x` 回填了 `capabilities` 字段,这条判据就会误报"不支持"。真要做到无懈可击,
1067
- > 得在接收侧留一个"原始名片里有没有这个 key"的布尔位再投影出去 —— 现在没有。
1068
-
1069
- #### ⚠️ `runtimes: {}` 也可能是**假的**(Windows 踩过)
1070
-
1071
- `runtimesIncomplete: false` 的语义是"所有探测都得到了**确定**答案,可以据此断言
1072
- 这台机器**没有**任何运行时"。但"确定没装"和"PATH 里找不到"在数据上长得一模一样 ——
1073
- `isUncertain()` 把 `ENOENT` 当作确定答案。只要 **PATH 本身是错的**,整批 `ENOENT`
1074
- 就会被翻译成"确定没装"。
1075
-
1076
- 实测:对端 `文超-win` 升到 0.3.28 后报回 `runtimes: {}` + `runtimesIncomplete: false`
1077
- —— 即在名片上宣称"确定没有任何运行时",**而它自己就跑在 Node 上**(DSH 是 Node 应用)。
1078
- 根因是 `extraPathDirs()` 当时**没有 Windows 分支**,补的全是 Unix 路径
1079
- (`/opt/homebrew/bin`、`/usr/local/bin`…),在 Windows 上等于没补。
1080
-
1081
- 三道防线(本次修复起,版本号未变,仍是 0.3.28):
1082
-
1083
- 1. `extraPathDirs()` 分平台。Windows 分支补 `%ProgramFiles%\nodejs`、`%APPDATA%\npm`、
1084
- `%LOCALAPPDATA%\Programs\Python`、`%ProgramFiles%\Git\cmd`、scoop/chocolatey shims 等;
1085
- 并且 **PATH 分隔符跟平台走**(Windows 是 `;`)—— 写死 `:` 会让整个 PATH 变成
1086
- 一个"目录名",比不补还糟。
1087
- 2. **形状守卫**:`runtimes` 为空**且**存在失败项 → 标 `runtimesIncomplete: true`
1088
- ("整批归零"的形状,几乎必定是 PATH 问题)。
1089
- 3. **补全生效判据**(最关键的一条):`extraPathDirs()` 在**这台机器上**一个存在的
1090
- 目录都加不进去 → 说明我们自己的兜底没做成 → 此时 **所有 ENOENT 结论都不可信**,
1091
- 照样标 `runtimesIncomplete: true`。
1092
-
1093
- ##### 判据为什么用"补全有没有生效",而不是"目录白名单"
1094
-
1095
- 一开始我写的是"主 PATH 里有没有本平台常见工具目录"(硬编码 `darwin`/`linux`/`android`
1096
- 三套根)。对端当场指出这会**假阳性**:它的 runtimes 实际住在
1097
- `/data/data/com.dsharnessmobile.shell/files/usr/bin`,**不在任何常见白名单里** ——
1098
- 白名单一旦遇到白名单之外的 prefix 就会误判"PATH 残缺"。
1099
-
1100
- 改成**自校验**式:问的不是"PATH 里有没有我认识的目录",而是
1101
- **"我们自己的兜底机制有没有真的加进一个存在的目录"**。这与平台布局无关,
1102
- 也不需要维护清单;Windows(`%ProgramFiles%\nodejs` 不存在时)和 Android/Termux
1103
- 都自然落到"补全没生效 → ENOENT 不可信",而 darwin/linux 正常机器落到"生效 → 可信"。
1104
-
1105
- ##### 为什么不是"有失败就报"
1106
-
1107
- 对端 hos 曾提议简化成"`errors.length > 0` → incomplete"。**这条会误报**,
1108
- 我拒绝了,理由是实测反例 —— 就是本机:
1109
-
1110
- | 机器 | runtimes | ENOENT 项 | 那些项真的没装吗 | 正确结论 |
1111
- | --- | --- | --- | --- | --- |
1112
- | 本机 darwin | 6 个(非空) | `rustc`、`adb` | **是**,`command -v` 也找不到 | `incomplete=false` ✅ |
1113
- | 文超-win | **0 个** | 全部 | 否 —— 它跑在 Node 上 | `incomplete=true` ✅ |
1114
- | 对端 Android | 3 个(非空) | 6 项 | **是**(它自查 `command -v` 确认) | `incomplete=false` ✅ |
1115
-
1116
- 按"有失败就报",本机会被误标成 incomplete(`rustc`/`adb` 真的没有),于是 Placement
1117
- 永远不敢断言"这台机器没装 rustc" —— **代价不是"谨慎",是让这个字段失去区分度**。
1118
-
1119
- > 这一行的第三个格曾反复过:对端先断言"我这台是活反例",我据此把 Android 改成
1120
- > 无条件 `incomplete=true`;**随后它自己跑了 `command -v`,确认那 6 个确实都没装,
1121
- > 于是撤回**。那条无条件改动是**假阳性**,已随本判据一起改掉。
1122
- > 教训:`command -v` 自查是**必要条件不是充分条件** —— `FOUND` 能证伪
1123
- > (一定有 ⇒ 真漏报),`absent` **只在 PATH 健全时才可下结论**,而这条自查用的
1124
- > 正是同一个 PATH 机制,所以它本身是**循环**的。另外它对 shell 生效,探针走的是
1125
- > node 子进程的 PATH,两者在异常环境下可能不同。
1126
-
1127
- ##### `probeFailCount`:让失败信号**能过网线**
1128
-
1129
- `probeErrors`(失败明细)**不上名片**(`sanitize` 不保留,它只在本地日志/UI 用)。
1130
- 后果是对端结构性看不到"这次探测失败过"—— 只能看到 `runtimes: {}` 和
1131
- `runtimesIncomplete`。旧投影里"3 项没探到"和"8 项全没探到"长得一模一样。
1132
- 所以新增 `probeFailCount`(数字)跟着名片走:旧对端没有该字段时按 `0` 处理。
1133
- (明细仍然不上网线 —— 只上一个计数,够对端判断可信度,又不放大协议面。)
1134
-
1135
- #### `gpu === null` 有**三种**成因,投影层区分不了
1136
-
1137
- | 成因 | 含义 |
1138
- | --- | --- |
1139
- | ① 对端没有 `capabilities` 字段(版本 < 0.3.25) | 不支持 |
1140
- | ② 有字段,但探测本身没给出结论(`nvidia-smi` ENOENT / 超时等) | 探测未果 |
1141
- | ③ 有字段,对端**明确报了** `present:false` | 对端说"没有",但…… |
1142
-
1143
- ③ 的特殊之处:`sanitizeCapabilities` 里 `const name = safeStr(raw.gpu.name,60); if (name) gpu = {...}`
1144
- —— **名字为空就把整块 gpu 丢掉**。也就是说对端想说"确定没有",经投影会被
1145
- **提升成"未知"**。方向与我们常防的"自家 bug 伪装成对端事实"(假阳性)**相反**:
1146
- 这是"对端事实被抹成未知"(假阴性→未知)。对 Placement 的影响是**保守**的
1147
- (不会误排除机器),但语义上 `null` 不再等于"不知道"。
1148
-
1149
- 根上已收口:解析函数**解析不出型号一律返回 `null`**(不再返回
1150
- `{present:false,name:""}`),所以成因 ③ 现在不可达。见下方 `parseMacGpu`。
1151
- 要真正区分三者,仍需要在接收侧保留"原始名片有没有这个 key / present 是什么"
1152
- 的额外位 —— 目前没有,与 `capabilities` 那条结论同源。
1153
-
1154
- 诊断:`/mesh/api/state` 的 `self.capabilities`(本机)与 `peers[].capabilities`
1155
- (对端);`self.capabilityProbePath` 是探测实际使用的 PATH。
1156
-
1157
- 回归脚本:
1158
-
1159
- ```bash
1160
- npm test # = check + 四个回归脚本(共 139 项,默认不碰网络)
1161
- npm run selftest # 52 项:发现/通道/会话键
1162
- npm run selftest:prompt # 10 项:任务提示词(回派目标必须是机器名)
1163
- npm run selftest:client # 12 项:客户端渲染(无需浏览器,见下)
1164
- npm run selftest:caps # 62 项:净化/GPU/过期/重试/名片兼容/认领边界
1165
- npm run selftest:newsession # 需要先跑起 dev 实例,见文件头注释
1166
- ```
1167
-
1168
- **客户端怎么在没有浏览器的情况下测**:这是个手写 bundle、没有构建步骤,安装里
1169
- 也没有 react-dom。但组件都是纯函数(不用 hook),`createElement` 的返回树就是普通
1170
- 对象 —— 所以 `_selftest-client.mjs` 用假的 `window.__ModuleLoader__` 把 factory
1171
- 抓出来,用最小 react stub 执行它,再直接调用组件、遍历返回树断言文案。这比"看代码
1172
- 觉得对"强:写这套测试时当场抓到一个真 bug(形状不对的 `runtimes` 会被渲染成一串
1173
- 乱码徽章,而不是干净降级)。
1174
-
1175
- ---
1176
844
 
1177
845
  ## 文件结构
1178
846
 
@@ -1194,6 +862,7 @@ dsh-plugin-mesh/
1194
862
  │ └── client.js # 浏览器侧:手写 bundle,无需打包工具
1195
863
  ├── dev-setup.sh # 隔离测试环境搭建
1196
864
  ├── dev-boot.mjs # 带模块解析器的测试启动器
865
+ ├── DESIGN.md # 设计原理与复盘(为什么这么设计、踩过哪些坑)
1197
866
  ├── Placement设计.md # 步骤 ③ 设计 + 实施记录
1198
867
  ├── 设备身份与多通道设计.md # 步骤 ① 设计
1199
868
  └── README.md
package/client/client.js CHANGED
@@ -25,6 +25,15 @@ window.__ModuleLoader__.load({
25
25
  const API = "/mesh/api";
26
26
  const inject = ["slots"];
27
27
 
28
+ /**
29
+ * 拿 Tailscale 授权码的地方。
30
+ *
31
+ * 为什么要在插件里直接给地址:跨互联网组网必须先有 Tailscale 账号 + 授权码,
32
+ * 而"Settings → Keys"这种描述等于让用户自己去后台翻。少一步算一步。
33
+ * 未登录时这个地址会自动跳到登录/注册页,所以一个链接同时覆盖"注册"和"取码"。
34
+ */
35
+ const TS_KEYS_URL = "https://console.tailscale.com/admin/settings/keys";
36
+
28
37
  // ─────────────────────── 数据 ───────────────────────
29
38
 
30
39
  function useMeshState(intervalMs) {
@@ -354,6 +363,7 @@ window.__ModuleLoader__.load({
354
363
  { style: { ...S.muted, marginTop: 8 } },
355
364
  "跨互联网也能互相发现和派任务,和局域网是同一套用法。",
356
365
  "不需要安装 Tailscale 客户端,也不需要装 Go —— sidecar 会按平台自动下载。",
366
+ tsnet.authKeySaved ? "" : "开启需要一个 Tailscale 授权码(免费注册),见下方「设置」。",
357
367
  ),
358
368
 
359
369
  // 需要登录时把授权链接摆在最显眼的位置,不用点开设置
@@ -389,11 +399,48 @@ window.__ModuleLoader__.load({
389
399
  }),
390
400
  h("button", { style: S.btnPrimary, onClick: saveAndStart, disabled: busy === "save" }, busy === "save" ? "处理中…" : tsnet.enabled ? "保存并重启" : "保存并启动"),
391
401
  ),
392
- h(
393
- "div",
394
- { style: { ...S.muted, marginTop: 6 } },
395
- tsnet.authKeySaved ? "✓ 授权码已保存在本机(state.json,权限 0600),只会在这里输入一次。" : "在 Tailscale 后台 Settings → Keys 生成,勾选 Reusable 与 Pre-approved。",
396
- ),
402
+ tsnet.authKeySaved
403
+ ? h(
404
+ "div",
405
+ { style: { ...S.muted, marginTop: 6 } },
406
+ "✓ 授权码已保存在本机(state.json,权限 0600),只会在这里输入一次。",
407
+ )
408
+ : h(
409
+ "div",
410
+ { style: { marginTop: 8, padding: "10px 12px", border: "1px solid var(--dsw-alias-border-secondary, #d5d8dc)", borderRadius: 8, fontSize: 13 } },
411
+ h("div", { style: { fontWeight: 600, marginBottom: 4 } }, "还没有授权码?两步:"),
412
+ h(
413
+ "div",
414
+ { style: { ...S.muted, marginBottom: 4 } },
415
+ "① 注册 / 登录 Tailscale 账号(免费)—— 打开下面的地址会让你先登录。",
416
+ ),
417
+ h(
418
+ "div",
419
+ { style: { ...S.muted, marginBottom: 6 } },
420
+ "② 在同一页面点 Generate auth key,把生成的 tskey-auth-… 粘到上面的输入框。",
421
+ ),
422
+ h(
423
+ "a",
424
+ {
425
+ href: TS_KEYS_URL,
426
+ target: "_blank",
427
+ rel: "noreferrer",
428
+ style: { color: "inherit", wordBreak: "break-all", textDecoration: "underline" },
429
+ },
430
+ TS_KEYS_URL,
431
+ ),
432
+ h(
433
+ "div",
434
+ { style: { ...S.muted, marginTop: 8 } },
435
+ "⚠️ 生成时必须勾选 Reusable(一次性授权码只能用一次,重启就会报 invalid key)。",
436
+ "如果你在 Tailscale 后台开启了设备审批,还要勾 Pre-approved。",
437
+ ),
438
+ h(
439
+ "div",
440
+ { style: { ...S.muted, marginTop: 6 } },
441
+ "授权码只在这里输入一次;之后放进本机 state.json(权限 0600),随时可以在这里替换。",
442
+ ),
443
+ ),
397
444
 
398
445
  h(
399
446
  "div",
@@ -952,7 +999,7 @@ window.__ModuleLoader__.load({
952
999
  // 也没有 react-dom,所以没有别的方式在无浏览器环境下验证渲染逻辑。
953
1000
  // 组件都是纯函数(CapabilityLine 不用 hook),拿 createElement 的返回树
954
1001
  // 直接走一遍就能断言文案与标记 —— 比"看代码觉得对"强得多。
955
- exports.__test = { CapabilityLine, PeerRow, MeshPage };
1002
+ exports.__test = { CapabilityLine, PeerRow, MeshPage, TsnetCard };
956
1003
  return module.exports;
957
1004
  },
958
1005
  });
@@ -138,7 +138,7 @@ test("apply() 注册两个槽位:侧栏图标 + 主面板", () => {
138
138
  assert.ok(regs.includes("main"), `主面板槽未注册:${JSON.stringify(regs)}`);
139
139
  });
140
140
 
141
- const { CapabilityLine, PeerRow } = mod.__test;
141
+ const { CapabilityLine, PeerRow, TsnetCard } = mod.__test;
142
142
 
143
143
  console.log("\n── CapabilityLine:三种「不知道」必须分开渲染 ──");
144
144
 
@@ -245,5 +245,62 @@ test("PeerRow 渲染出的文案里包含对端的能力", () => {
245
245
  assert.ok(txt.includes("go 1.25"), `机器卡片里应显示能力:${txt}`);
246
246
  });
247
247
 
248
+ console.log("\n── TsnetCard:用户不该自己去后台找授权码地址 ──");
249
+
250
+ const noop = () => {};
251
+ const tsnetOff = { enabled: false, authKeySaved: false, controlUrl: "", node: null, hostname: "", permissionPresetEffective: "" };
252
+
253
+ test("未配置时,卡片当场说明「需要授权码」而不是只留一个输入框", () => {
254
+ const txt = textOf(TsnetCard({ tsnet: tsnetOff, onChanged: noop })).join(" ");
255
+ assert.ok(txt.includes("授权码"), txt.slice(0, 200));
256
+ assert.ok(txt.includes("免费"), "应说明可以免费注册");
257
+ });
258
+
259
+ test("给出可直接点开的授权码页面地址", () => {
260
+ const el = TsnetCard({ tsnet: tsnetOff, onChanged: noop });
261
+ const txt = textOf(el).join(" ");
262
+ assert.ok(txt.includes("https://console.tailscale.com/admin/settings/keys"), "地址必须出现在可见文本里(Electron 里点不动也能复制)");
263
+ });
264
+
265
+ test("地址是可点链接且新窗口打开", () => {
266
+ const el = TsnetCard({ tsnet: tsnetOff, onChanged: noop });
267
+ const links = [];
268
+ (function walk(n) {
269
+ if (!n || typeof n !== "object") return;
270
+ if (Array.isArray(n)) return n.forEach(walk);
271
+ if (typeof n.type === "function") return walk(n.type(n.props));
272
+ if (n.props && n.props.href) links.push(n.props);
273
+ walk(n.children);
274
+ if (n.props && n.props.children !== undefined) walk(n.props.children);
275
+ })(el);
276
+ const hit = links.find((a) => a.href === "https://console.tailscale.com/admin/settings/keys");
277
+ assert.ok(hit, "应有指向授权码页面的 <a>");
278
+ assert.equal(hit.target, "_blank");
279
+ });
280
+
281
+ test("点明「必须勾选 Reusable」这个真实坑(一次性码重启就失效)", () => {
282
+ const txt = textOf(TsnetCard({ tsnet: tsnetOff, onChanged: noop })).join(" ");
283
+ assert.ok(txt.includes("Reusable"), txt.slice(0, 300));
284
+ assert.ok(txt.includes("一次性"), "应解释为什么必须 Reusable");
285
+ });
286
+
287
+ test("已经存过授权码时不再重复推销取码步骤,只提示已保存", () => {
288
+ // 注意要用 enabled:false —— 那才是"面板会展开"的状态(open 初值 = !enabled)。
289
+ // 用 enabled:true 测这条是假绿:面板默认收起,什么都断言得到。
290
+ const txt = textOf(
291
+ TsnetCard({ tsnet: { ...tsnetOff, enabled: false, authKeySaved: true }, onChanged: noop }),
292
+ ).join(" ");
293
+ assert.ok(txt.includes("已保存"), txt.slice(0, 300));
294
+ assert.ok(!txt.includes("console.tailscale.com"), "已配置后不该再占版面显示取码地址");
295
+ });
296
+
297
+ test("enabled 状态下设置面板默认收起(不占版面)", () => {
298
+ const txt = textOf(
299
+ TsnetCard({ tsnet: { ...tsnetOff, enabled: true, authKeySaved: true }, onChanged: noop }),
300
+ ).join(" ");
301
+ assert.ok(txt.includes("设置"), "应有「设置」按钮可以展开");
302
+ assert.ok(!txt.includes("console.tailscale.com"), "收起时不该显示取码步骤");
303
+ });
304
+
248
305
  console.log(`\n${failed === 0 ? "全部通过" : "有失败"}:${passed} 通过 / ${failed} 失败\n`);
249
306
  process.exit(failed === 0 ? 0 : 1);
package/lib/index.js CHANGED
@@ -44,7 +44,7 @@ import { tailnetFetch, tailnetOrigin } from "./tsnet/bridge.js";
44
44
  export const name = "dsh-plugin-mesh";
45
45
  export const inject = ["tools", "webServer"];
46
46
 
47
- const VERSION = "0.3.30";
47
+ const VERSION = "0.3.31";
48
48
  const RULE_ID = "mesh-inbound";
49
49
  const RULE_KIND = "mesh";
50
50
  const MAX_BODY = 256 * 1024;
package/llms.txt ADDED
@@ -0,0 +1,141 @@
1
+ # dsh-plugin-mesh
2
+
3
+ > DSH Mesh is a plugin for DeepSeek Harness (dsh) that discovers other dsh instances on the local network over UDP multicast or port scan, shows each peer's self-reported capabilities in a sidebar panel, and dispatches tasks between machines in both directions — over the LAN, or over an automatically downloaded userspace Tailscale (tsnet) sidecar when machines are not on the same network.
4
+
5
+ Canonical package: `dsh-plugin-mesh` (npm, MIT).
6
+ Repository: https://github.com/peng456/dsh-plugin-mesh
7
+ Showcase: https://peng456.github.io/dsh-plugin-mesh/
8
+ Primary documentation language is Chinese; this file is the English, machine-oriented entry point.
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ dsh plugin add dsh-plugin-mesh # 'desktop' profile: must run in DSH Desktop's own terminal
14
+ dsh plugin --profile web add dsh-plugin-mesh # any other profile: a normal terminal is fine
15
+ ```
16
+
17
+ From source instead: `git clone https://github.com/peng456/dsh-plugin-mesh && cd dsh-plugin-mesh && ./install.sh`
18
+
19
+ `dsh plugin --profile desktop ...` is rejected from a normal terminal by dsh itself (bin.js:29 — the desktop profile is managed exclusively by the Electron application). Use the app's built-in terminal, or `install.sh`.
20
+
21
+ **A restart of the dsh host is required after install** — the plugin loads at startup.
22
+
23
+ Verify after restart: `GET http://127.0.0.1:45917/mesh/v1/health` returns JSON containing `{"app":"dsh-mesh","machine":"<name>",...}`.
24
+
25
+ ## What it does at runtime
26
+
27
+ - Sends a JSON heartbeat to UDP multicast `239.255.42.99:45892` every `announceIntervalMs` (default 5000 ms) and listens on the same group.
28
+ - Serves a small HTTP peer API on TCP port 45917 (configurable via `port`).
29
+ - Optionally starts a bundled Go sidecar running a userspace Tailscale node (tsnet). No TUN device is created, so the host cannot route to `100.x.y.z`; all tailnet traffic is proxied through the sidecar. The binary is downloaded per-platform on first use and verified against checksums pinned in the plugin source.
30
+ - Auto-creates an agent session on the receiving machine when a task arrives, then routes that task to a new or reused session.
31
+
32
+ ## Tools registered (callable by the agent)
33
+
34
+ | Tool | Parameters | Purpose |
35
+ |---|---|---|
36
+ | `mesh_peers` | `includeOffline?: boolean` | List discovered peers: online state, address, OS, user, and the capabilities each peer reports. |
37
+ | `mesh_scan` | none | Actively scan the local subnet for mesh peers. Use when multicast is blocked. |
38
+ | `mesh_run` | `peer: string` (required), `task: string` (required), `thread?: string`, `noWake?: boolean`, `newSession?: boolean`, `workspace?: string` | Dispatch a task to another machine. Asynchronous — a successful call means "accepted", not "done". |
39
+ | `mesh_tasks` | none | Show recently received and sent mesh tasks. |
40
+
41
+ `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.
42
+
43
+ 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.
44
+
45
+ `newSession: true` forces a fresh session while keeping the same conversation key (i.e. it is still the same conversation, with a clean context).
46
+
47
+ ## Configuration
48
+
49
+ Override by id in the profile's `cordis.patch.yml`:
50
+
51
+ ```yaml
52
+ - id: mesh
53
+ config:
54
+ requirePairing: true
55
+ ```
56
+
57
+ **`config:` is replaced wholesale, not merged** (dsh's patch layer does `target[key] = value`). To add one key you must restate the keys you want to keep, or the others fall back to schema defaults.
58
+
59
+ | Key | Type | Default | Notes |
60
+ |---|---|---|---|
61
+ | `enabled` | boolean | `true` | |
62
+ | `machineName` | string | `""` | Human-readable name; empty = ask/derive from hostname |
63
+ | `port` | natural | `45917` | HTTP peer port |
64
+ | `announceIntervalMs` | natural | `5000` | Multicast heartbeat period |
65
+ | `peerTtlMs` | natural | `20000` | Peer marked offline after this silence |
66
+ | `requestTimeoutMs` | natural | `20000` | Per-request timeout |
67
+ | `useMulticast` | boolean | `true` | |
68
+ | `scanOnStart` | boolean | `true` | |
69
+ | `scanIntervalMs` | natural | `60000` | |
70
+ | `scanConcurrency` | natural | `64` | |
71
+ | `scanTimeoutMs` | natural | `800` | |
72
+ | `pingIntervalMs` | natural | `10000` | LAN health probe period |
73
+ | `tsnetProbeIntervalMs` | natural | `60000` | Tailnet health probe period |
74
+ | `requirePairing` | boolean | `false` | **Default off: the peer API accepts unauthenticated task POSTs** |
75
+ | `agentPreset` | string | `"standard"` | Agent preset for auto-created sessions |
76
+ | `permissionPreset` | string | `"workspace-write"` | Permission preset for auto-created sessions |
77
+ | `workspaceRoot` | string | `""` | |
78
+ | `tsnetEnabled` | boolean | `false` | |
79
+ | `tsnetAuthKey` | string | `""` | Tailscale auth key; must be reusable |
80
+ | `tsnetControlUrl` | string | `""` | |
81
+ | `tsnetHostname` | string | `""` | The plugin prefixes `dsh-`; do not include it yourself |
82
+ | `tsnetPermissionPreset` | string | `""` | Empty = same as `permissionPreset` |
83
+ | `maxWakesPerThread` | natural | `30` | Per-thread wake cap per window |
84
+ | `threadWindowMs` | natural | `3600000` | Window for the cap above |
85
+ | `threadCooldownMs` | natural | `5000` | Cooldown between session-creating wakes |
86
+ | `minTaskChars` | natural | `24` | Bodies shorter than this are not woken (inbox only) |
87
+
88
+ ## Tailnet setup (the only step that needs an external account)
89
+
90
+ Cross-network links require a free Tailscale account and an auth key. Create one at
91
+ <https://console.tailscale.com/admin/settings/keys> — that URL redirects to sign-up
92
+ if you are not signed in yet. The key **must be Reusable**; single-use keys fail
93
+ with `invalid key` on the next start. If device approval is enabled in the tailnet,
94
+ tick Pre-approved as well.
95
+
96
+ Set `tsnetEnabled: true` plus `tsnetAuthKey` in config, or paste the key once into the
97
+ Mesh panel's tailnet card — it is stored in `~/.dsh/mesh/state.json` (mode 0600) and
98
+ never needs re-entry. The plugin's UI links to the key page directly; do not tell users
99
+ to hunt for it.
100
+
101
+ ## Network and security facts
102
+
103
+ - Ports: TCP `45917` (peer HTTP), UDP `45892` (multicast group `239.255.42.99`).
104
+ - Discovery is intentionally public: any host on the same L2 network can see the machine and its self-reported card.
105
+ - With `requirePairing: false` (the default), **any host that can reach TCP 45917 can POST a task, which wakes an agent session** using `permissionPreset`. Enable `requirePairing` and share one secret between machines on untrusted networks. The token travels in a plain HTTP header — it guards against stray devices, not against a network sniffer.
106
+ - The shared secret is stored in `~/.dsh/mesh/state.json` (mode 0600) alongside `machineName`, the persisted `instanceIds`, and the tsnet auth key. It is never included in the multicast card.
107
+ - Persistent identity is a UUID per profile; the OS machine fingerprint is used only to reclaim a reinstalled device (same name, or the old record already offline). Two live instances on one physical machine are kept separate.
108
+ - Sidecar binaries are verified against sha256 checksums pinned in `lib/tsnet/checksums.js` — deliberately not fetched from the same release, so a hostile mirror cannot swap both.
109
+
110
+ ## Requirements
111
+
112
+ - A dsh host that can load cordis plugins with a client half (DSH Desktop, or `dsh web` + a profile).
113
+ - Node >= 20 for development. Peer `@deepseek-ai/*` packages are provided by the host and are not bundled.
114
+ - No Go toolchain and no Tailscale client are required by end users.
115
+
116
+ ## Development
117
+
118
+ ```bash
119
+ npm run check # version consistency + TDZ scan + syntax + loadability
120
+ npm test # = check + four regression suites (~138 assertions, network-free)
121
+ npm run selftest:caps # capability collection: sanitising, GPU parsing, retries, claim rules
122
+ npm run selftest:client # client bundle rendering without a browser
123
+ npm run selftest:prompt # task prompt generation
124
+ npm run build:sidecar # rebuild the Go tsnet sidecar (cross-platform)
125
+ ```
126
+
127
+ `AGENTS.md` in the repository root carries the operating guide for coding agents: hard constraints, known traps, and file map. Read it before changing this project.
128
+
129
+ ## Documentation map
130
+
131
+ - `AGENTS.md` — agent operating guide, constraints, traps (English)
132
+ - `README.en.md` — short English quickstart (English)
133
+ - `DESIGN.md` — design rationale, trade-offs and post-mortems (Chinese)
134
+ - `README.md` — full documentation, Chinese, includes design rationale and post-mortems
135
+ - `Placement设计.md` — placement design and implementation record (Chinese)
136
+ - `设备身份与多通道设计.md` — identity and multi-channel design (Chinese)
137
+ - `docs/index.html` — user-facing showcase, Chinese (GitHub Pages)
138
+
139
+ ## Contact
140
+
141
+ geekstartup@163.com · https://github.com/peng456/dsh-plugin-mesh/issues · npm: `dsh-plugin-mesh`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-mesh",
3
- "version": "0.3.30",
3
+ "version": "0.3.31",
4
4
  "type": "module",
5
5
  "description": "DSH Mesh:局域网自动发现同网段的 DSH 实例、显示每台机器上报的能力,并双向派发任务;可用内置的用户态 Tailscale 节点跨互联网组网。Discovers other DSH instances on the LAN, shows the capabilities each one reports, and dispatches tasks between machines in both directions, with an optional userspace Tailscale node for links across networks.",
6
6
  "license": "MIT",
@@ -36,6 +36,9 @@
36
36
  "./package.json": "./package.json"
37
37
  },
38
38
  "files": [
39
+ "README.en.md",
40
+ "AGENTS.md",
41
+ "llms.txt",
39
42
  "lib",
40
43
  "client",
41
44
  "sidecar",
@@ -56,13 +59,14 @@
56
59
  "selftest:caps": "node lib/_selftest-capabilities.mjs",
57
60
  "selftest:newsession": "node lib/_selftest-newsession.mjs",
58
61
  "test": "npm run check && npm run selftest && npm run selftest:prompt && npm run selftest:client && npm run selftest:caps",
59
- "check": "node scripts/check-version.mjs && node scripts/check-tdz.mjs && node --check lib/index.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/scan.js && node --check lib/tsnet/download.js && node --check lib/tsnet/manager.js && node --check lib/tsnet/bridge.js && node --check client/client.js && npm run check:loadable",
62
+ "check": "node scripts/check-version.mjs && node scripts/check-tdz.mjs && node --check lib/index.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/scan.js && node --check lib/tsnet/download.js && node --check lib/tsnet/manager.js && node --check lib/tsnet/bridge.js && node --check client/client.js && npm run check:loadable && npm run check:docs",
60
63
  "build:sidecar": "bash scripts/build-sidecar.sh",
61
64
  "verify:mirror": "node scripts/verify-lan-mirror.mjs",
62
65
  "check:loadable": "node scripts/check-loadable.mjs --allow-missing-runtime-dep",
63
66
  "check:deploy": "node scripts/check-loadable.mjs",
64
67
  "check:scope": "python3 tools/scopecheck.py lib/index.js",
65
- "prepublishOnly": "npm test && node scripts/check-tarball.mjs"
68
+ "prepublishOnly": "npm test && node scripts/check-tarball.mjs",
69
+ "check:docs": "node scripts/sync-llms.mjs"
66
70
  },
67
71
  "publishConfig": {
68
72
  "registry": "https://registry.npmjs.org/",
@@ -0,0 +1,54 @@
1
+ /**
2
+ * 让 `llms.txt` 和 `docs/llms.txt` 保持一致。
3
+ *
4
+ * 为什么需要它:`llms.txt` 是给 agent 的机器入口(llmstxt.org 约定)。它要被
5
+ * 两个地方拿到:
6
+ * · 仓库根 —— clone 下来的 agent 直接读本地文件
7
+ * · `docs/` —— 站点上 `https://<site>/llms.txt`,这是约定里 agent 会去找的路径
8
+ *
9
+ * 两份必须逐字节相同,否则 agent 会读到两个版本的"事实",而且**没人会察觉**
10
+ * (这项目已经栽过好几次"复制了一份、然后忘了同步")。所以改成一份源 + 校验:
11
+ *
12
+ * node scripts/sync-llms.mjs # 校验(默认,CI / npm run check 用)
13
+ * node scripts/sync-llms.mjs --write # 用根目录那份覆盖 docs/
14
+ */
15
+ import { readFileSync, writeFileSync, existsSync } from "node:fs";
16
+ import { join, dirname } from "node:path";
17
+ import { fileURLToPath } from "node:url";
18
+
19
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
20
+ const SRC = join(ROOT, "llms.txt");
21
+ const DST = join(ROOT, "docs", "llms.txt");
22
+
23
+ if (!existsSync(SRC)) {
24
+ console.error("✗ 找不到 llms.txt —— 它是给 agent 的机器入口,不能少");
25
+ process.exit(1);
26
+ }
27
+
28
+ const src = readFileSync(SRC, "utf8");
29
+
30
+ if (process.argv.includes("--write")) {
31
+ writeFileSync(DST, src);
32
+ console.log(`✓ 已同步 docs/llms.txt(${src.length} 字符)`);
33
+ process.exit(0);
34
+ }
35
+
36
+ if (!existsSync(DST)) {
37
+ console.error("✗ docs/llms.txt 不存在 —— 跑 `node scripts/sync-llms.mjs --write`");
38
+ process.exit(1);
39
+ }
40
+
41
+ const dst = readFileSync(DST, "utf8");
42
+ if (dst !== src) {
43
+ // 给出行数差异,别只丢一句"不一致"
44
+ const a = src.split("\n");
45
+ const b = dst.split("\n");
46
+ const firstDiff = a.findIndex((line, i) => line !== b[i]);
47
+ console.error(
48
+ `✗ docs/llms.txt 与 llms.txt 不一致(首个差异在根文件第 ${firstDiff + 1} 行)。\n` +
49
+ ` 两份都是 agent 会读的"事实来源",必须相同。\n` +
50
+ ` 修复:node scripts/sync-llms.mjs --write`,
51
+ );
52
+ process.exit(1);
53
+ }
54
+ console.log(`✓ llms.txt 与 docs/llms.txt 一致(${src.length} 字符)`);