dsh-plugin-mesh 0.5.8 → 0.5.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -19,7 +19,19 @@ import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
19
19
  import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
20
20
  import { join, basename, isAbsolute, resolve } from "node:path";
21
21
  import { fileURLToPath } from "node:url";
22
- import { homedir, hostname, userInfo, platform, arch } from "node:os";
22
+ import {
23
+ homedir,
24
+ hostname,
25
+ userInfo,
26
+ platform,
27
+ arch,
28
+ loadavg,
29
+ cpus,
30
+ freemem,
31
+ totalmem,
32
+ release as osRelease,
33
+ uptime,
34
+ } from "node:os";
23
35
  import z from "@deepseek-ai/schemastery";
24
36
  import { defineTool } from "@deepseek-ai/dsh-tools";
25
37
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
@@ -58,6 +70,14 @@ import {
58
70
  import { buildPrompt } from "./prompt.js";
59
71
  import { matchLeadingMentions, buildAtPrompt } from "./at-mention.js";
60
72
  import { resolvePairing } from "./pairing.js";
73
+ import {
74
+ approvePeer,
75
+ isReplyToOutbound,
76
+ needsApproval,
77
+ normalizeApproved,
78
+ peerOfTask,
79
+ revokePeer,
80
+ } from "./approval.js";
61
81
  import {
62
82
  applyMeshSwitch,
63
83
  describeMeshSwitch,
@@ -88,7 +108,7 @@ import {
88
108
  export const name = "dsh-plugin-mesh";
89
109
  export const inject = ["tools", "webServer"];
90
110
 
91
- const VERSION = "0.5.8";
111
+ const VERSION = "0.5.10";
92
112
  // 诊断用:进程启动时间 + 入口真实路径。磁盘上的版本**不在这里缓存** ——
93
113
  // 升级之后进程还跑旧代码,版本号必须现读磁盘才能立刻反映出来(真踩过:
94
114
  // 磁盘升到 0.5.1,进程还在 0.5.0,界面显示 0.5.0)。
@@ -221,6 +241,18 @@ export const Config = z.object({
221
241
  */
222
242
  requirePairing: z.boolean().default(false),
223
243
 
244
+ /**
245
+ * 陌生设备第一次派活时,本机要不要先点一次「允许」。默认 **true**。
246
+ *
247
+ * 为什么默认开:默认零配置意味着同一网段里谁连得上 45917 都能让本机开一个
248
+ * agent 会话。对"自己家三台电脑"这是方便;对"公司 / 合租 / 咖啡厅"就是敞着门。
249
+ * 原来的答案是"你去开配对码",但那是个设置项,没人会主动打开。
250
+ *
251
+ * 只问**第一次**:允许过之后写进 state.json 的 approvedPeers,同一台设备不再问。
252
+ * 开了 requirePairing 就不再重复问 —— 配对码是更强的信任动作。
253
+ */
254
+ requireApproval: z.boolean().default(true),
255
+
224
256
  /** 对端任务在本机新建会话时用的 agent preset */
225
257
  agentPreset: z.string().default("standard"),
226
258
  /** 对端任务在本机新建会话时的权限;默认不给 danger-full-access */
@@ -513,6 +545,53 @@ function pairingPinned(config) {
513
545
  return pairingState(config).pinned;
514
546
  }
515
547
 
548
+ /**
549
+ * 本机信任过的设备(state.json 的 `approvedPeers`)。
550
+ *
551
+ * 和配对码的区别:配对码是"同一个密钥",对整网生效;这张表是"这台机器点过
552
+ * 一次允许",逐台生效。第一次派活的确认闸门(见 lib/approval.js)就靠它。
553
+ */
554
+ function approvedPeers() {
555
+ return normalizeApproved(loadState().approvedPeers);
556
+ }
557
+
558
+ /** 记下一台被允许的设备;写盘失败不该让"允许"这个动作本身失败。 */
559
+ function rememberApprovedPeer(peer) {
560
+ try {
561
+ const next = approvePeer(approvedPeers(), peer, new Date().toISOString());
562
+ saveState({ approvedPeers: next });
563
+ return next;
564
+ } catch {
565
+ return approvedPeers();
566
+ }
567
+ }
568
+
569
+ /** 撤销一台设备的信任;写盘失败时返回原列表,界面据返回值刷新。 */
570
+ function forgetApprovedPeer(target) {
571
+ try {
572
+ const next = revokePeer(approvedPeers(), target);
573
+ saveState({ approvedPeers: next });
574
+ return next;
575
+ } catch {
576
+ return approvedPeers();
577
+ }
578
+ }
579
+
580
+ /**
581
+ * 这条入站任务要不要先等本机点一次「允许」。
582
+ *
583
+ * 只看信任层:配置开关、配对码是否已开、这台设备是否已在 approvedPeers 里。
584
+ * 路由与闸门(太短/寒暄/限速)是另一层,不在这里判断。
585
+ */
586
+ function inboundNeedsApproval(config, task) {
587
+ return needsApproval({
588
+ config,
589
+ approved: approvedPeers(),
590
+ peer: peerOfTask(task),
591
+ pairingRequired: pairingRequired(config),
592
+ });
593
+ }
594
+
516
595
  /**
517
596
  * 解析 tailnet 的**有效通道列表**(多 tailnet)。
518
597
  *
@@ -1412,13 +1491,17 @@ async function dispatchTaskToPeer(
1412
1491
  const notWoken = NOT_WOKEN_STATUS.has(String(rb?.status ?? ""))
1413
1492
  ? { status: String(rb.status), reason: String(rb?.routeDecision ?? "") }
1414
1493
  : null;
1494
+ // 对端第一次收到这台机器的活:它要点一次「允许」才执行(202)。
1495
+ // 这不是失败 —— 送达了,只是在等人。界面要能看出这个中间态。
1496
+ const pendingApproval = r.status === 202 && rb?.pendingApproval === true;
1415
1497
  outbound.push({
1416
1498
  ...payload,
1417
1499
  toMachine: target.machine,
1418
1500
  at: new Date().toISOString(),
1419
1501
  ok: r.ok,
1420
1502
  status: r.status,
1421
- remoteStatus: rb?.status ?? "",
1503
+ remoteStatus: pendingApproval ? "needs-approval" : (rb?.status ?? ""),
1504
+ ...(pendingApproval ? { noted: true, note: "等对端点一次「允许」" } : {}),
1422
1505
  ...(notWoken ? { noted: true, note: notWoken.reason } : {}),
1423
1506
  });
1424
1507
  onHistoryChange?.();
@@ -1433,7 +1516,7 @@ async function dispatchTaskToPeer(
1433
1516
  (r.status === 403 ? "(对端开启了 requirePairing 且两端配对码不一致 —— 在「配对码」里对齐)" : ""),
1434
1517
  };
1435
1518
  }
1436
- return { ok: true, id, status: r.status, noted: notWoken };
1519
+ return { ok: true, id, status: r.status, noted: notWoken, pendingApproval };
1437
1520
  } catch (err) {
1438
1521
  outbound.push({
1439
1522
  ...payload,
@@ -2764,6 +2847,25 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
2764
2847
  if (inbound.length > MAX_HISTORY) inbound.shift();
2765
2848
  }
2766
2849
  log(`收到任务 ${task.id} 来自 ${task.from}${duplicate ? "(重复,忽略)" : ""}`);
2850
+ // 信任闸门:陌生设备第一次派活,先存着,等本机点一次「允许」。
2851
+ //
2852
+ // 回执不算:同一台机器 + 同一个 thread 上我们确实往外派过任务,那这条
2853
+ // 就是对方在回答案,不是新活儿 —— 对回执再要一次确认会把整条回路卡死。
2854
+ const replyFromPeer = isReplyToOutbound(task, outbound);
2855
+ if (!replyFromPeer && inboundNeedsApproval(config, task)) {
2856
+ task.status = "needs-approval";
2857
+ task.routeDecision = `等待本机确认:还没有允许「${peerOfTask(task).machine || task.sourceAddress || "未知设备"}」`;
2858
+ onHistoryChange?.();
2859
+ log(`任务 ${task.id} 来自未允许的设备 ${task.from},等本机确认后才执行`);
2860
+ return send(res, 202, {
2861
+ ok: true,
2862
+ id: task.id,
2863
+ pendingApproval: true,
2864
+ status: "needs-approval",
2865
+ from: task.from,
2866
+ message: "对端还没允许这台机器,等本机确认后才会执行",
2867
+ });
2868
+ }
2767
2869
  if (!duplicate) {
2768
2870
  try {
2769
2871
  handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled, onHistoryChange, outbound);
@@ -3254,6 +3356,8 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
3254
3356
  // 界面开关一改就得立刻反映出来(端到端测试就是在这抓到过一次 stale)。
3255
3357
  requirePairing: pairingRequired(config),
3256
3358
  requirePairingPinned: pairingPinned(config),
3359
+ // 陌生设备首次派活是否要本机点一次「允许」(默认开)
3360
+ requireApproval: config.requireApproval !== false,
3257
3361
  useMulticast: config.useMulticast !== false,
3258
3362
  scanOnStart: config.scanOnStart !== false,
3259
3363
  scanIntervalMs: config.scanIntervalMs,
@@ -3282,6 +3386,22 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
3282
3386
  switch: meshSwitch ? meshSwitch.status() : null,
3283
3387
  peers: discovery.peers(),
3284
3388
  duplicateNames: duplicateNames(),
3389
+ // 陌生设备第一次派活时留下的待确认项(本机点「允许」后才执行)
3390
+ approvals: inbound
3391
+ .filter((t) => t.status === "needs-approval")
3392
+ .slice(-10)
3393
+ .reverse()
3394
+ .map((t) => ({
3395
+ id: t.id,
3396
+ from: t.from,
3397
+ fromMachine: t.fromMachine || "",
3398
+ address: t.sourceAddress || "",
3399
+ task: String(t.task || "").slice(0, 400),
3400
+ receivedAt: t.receivedAt || "",
3401
+ human: t.human === true,
3402
+ })),
3403
+ // 已经点过「允许」的设备:界面可以列出并撤销
3404
+ approvedPeers: approvedPeers(),
3285
3405
  inbound: inbound.slice(-30).reverse(),
3286
3406
  outbound: outbound.slice(-30).reverse(),
3287
3407
  // 被限速挡下的 thread:给页面渲染"是否提高上限"的提示
@@ -3300,6 +3420,43 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
3300
3420
  };
3301
3421
 
3302
3422
  route("/mesh/api/state", (_req, res) => send(res, 200, state()));
3423
+
3424
+ /**
3425
+ * 演示用的一次性快照:本机的**真实**系统数据。
3426
+ *
3427
+ * 为什么需要它:核心价值是"派活出去、结果回来",但体验它需要第二台机器。
3428
+ * 没有第二台机器的人只能看到一个空面板 —— 然后用脚投票。这个接口给
3429
+ * 「看演示」提供真实数字(而不是硬编码的假数据),让单机用户也能看到
3430
+ * 一次完整的「派发 → 在跑 → 结果」长什么样。
3431
+ *
3432
+ * 只读、不含任何秘密(没有配对码、没有路径)。演示本身在客户端里跑,
3433
+ * 不会建会话、不会花 token、不会写收件箱。
3434
+ */
3435
+ route("/mesh/api/demo", (_req, res) => {
3436
+ const caps = currentCapabilities() ?? {};
3437
+ const cores = Number(caps.cpuCores) || cpus().length || 0;
3438
+ const memMb = Number(caps.memMb) || Math.round(totalmem() / 1024 / 1024);
3439
+ send(res, 200, {
3440
+ ok: true,
3441
+ demo: true,
3442
+ machine: identity.name || hostname(),
3443
+ at: new Date().toISOString(),
3444
+ platform: platform(),
3445
+ release: osRelease(),
3446
+ arch: arch() || caps.arch || "",
3447
+ hostname: hostname(),
3448
+ cpuModel: caps.cpuModel || cpus()[0]?.model || "",
3449
+ cpuCores: cores,
3450
+ memTotalGb: Math.round((memMb / 1024) * 10) / 10,
3451
+ memFreeGb: Math.round((freemem() / 1024 ** 3) * 10) / 10,
3452
+ load1: Math.round(loadavg()[0] * 100) / 100,
3453
+ uptimeHours: Math.round((uptime() / 3600) * 10) / 10,
3454
+ runtimes: Object.entries(caps.runtimes ?? {})
3455
+ .slice(0, 4)
3456
+ .map(([name, version]) => ({ name, version: String(version) })),
3457
+ capabilitySummary: summarizeCapabilities(caps),
3458
+ });
3459
+ });
3303
3460
  // 只读诊断:UI 的「诊断」卡片用它;与 /mesh/v1/diagnostics 同一份数据。
3304
3461
  route("/mesh/api/diagnostics", (_req, res) => send(res, 200, diagnostics()));
3305
3462
 
@@ -3579,6 +3736,58 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
3579
3736
  return send(res, 200, { ok: true, requirePairing: want });
3580
3737
  });
3581
3738
 
3739
+ /**
3740
+ * 陌生设备第一次派活:本机点「允许」或「拒绝」。
3741
+ *
3742
+ * body: `{ id: string, action: "allow" | "deny" }`
3743
+ *
3744
+ * 允许 = 把这台设备写进 state.json 的 approvedPeers,并**立刻**执行那条
3745
+ * 被扣下的任务(它一直躺在收件箱里,状态 needs-approval);拒绝 = 只把记录
3746
+ * 标成 rejected,不执行。两者都不改用户的配置文件。
3747
+ */
3748
+ post("/mesh/api/approval", async (req, res) => {
3749
+ const body = await readJson(req);
3750
+ const id = String(body?.id ?? "").trim();
3751
+ const action = String(body?.action ?? "").trim();
3752
+ if (!id || (action !== "allow" && action !== "deny")) {
3753
+ return send(res, 400, { ok: false, error: "需要 id 与 action(allow / deny)" });
3754
+ }
3755
+ const rec = inbound.find((t) => t.id === id);
3756
+ if (!rec) return send(res, 404, { ok: false, error: "这条派发已经不在收件箱里(可能已处理)" });
3757
+ if (rec.status !== "needs-approval") {
3758
+ return send(res, 409, { ok: false, error: `这条派发当前是「${rec.status}」,不需要再确认` });
3759
+ }
3760
+ const peer = peerOfTask(rec);
3761
+ if (action === "deny") {
3762
+ rec.status = "rejected";
3763
+ rec.routeDecision = "本机拒绝:未信任这台设备";
3764
+ onHistoryChange?.();
3765
+ log(`已拒绝来自 ${rec.from} 的派发 ${rec.id}`);
3766
+ return send(res, 200, { ok: true, action, id });
3767
+ }
3768
+ rememberApprovedPeer(peer);
3769
+ rec.status = "accepted";
3770
+ rec.routeDecision = `已允许「${peer.machine || peer.address}」,开始处理`;
3771
+ onHistoryChange?.();
3772
+ log(`已允许 ${peer.machine || peer.address},继续处理 ${rec.id}`);
3773
+ try {
3774
+ handleInboundTask(ctx, rec, inbound, config, log, warn, waker, threadState, capFor, throttled, onHistoryChange, outbound);
3775
+ } catch (err) {
3776
+ warn(`允许后处理入站任务异常: ${err?.message ?? err}`);
3777
+ }
3778
+ return send(res, 200, { ok: true, action, id, from: rec.from, machine: peer.machine });
3779
+ });
3780
+
3781
+ /** 撤销一台设备的信任:下次它再派活会重新问一遍。 */
3782
+ post("/mesh/api/approval/revoke", async (req, res) => {
3783
+ const body = await readJson(req);
3784
+ const target = String(body?.machine ?? body?.address ?? "").trim();
3785
+ if (!target) return send(res, 400, { ok: false, error: "machine 必填" });
3786
+ const next = forgetApprovedPeer(target);
3787
+ log(`已撤销对「${target}」的信任(剩 ${next.length} 台)`);
3788
+ return send(res, 200, { ok: true, approvedPeers: next });
3789
+ });
3790
+
3582
3791
  /**
3583
3792
  * 界面上的「一键关闭」。
3584
3793
  *
@@ -4002,6 +4211,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4002
4211
  sessionId: originSession || createdSessionId,
4003
4212
  error: result.error,
4004
4213
  ...(result.noted ? { noted: true, reason: result.noted.reason } : {}),
4214
+ ...(result.pendingApproval ? { pendingApproval: true } : {}),
4005
4215
  });
4006
4216
  });
4007
4217
 
package/llms.txt CHANGED
@@ -34,6 +34,20 @@ Verify after restart: `GET http://127.0.0.1:45917/mesh/v1/health` returns JSON c
34
34
  - 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
35
  - 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
36
  - 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.
38
+ - `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
+ - `/mesh/api/state` additionally exposes `config.requireApproval`, `approvals[]` (pending first-contact tasks) and `approvedPeers[]` (`{machine,address,at}`).
40
+
41
+ ## Usage patterns (agent to agent)
42
+
43
+ What this is for: one agent hands a task to another agent on a different machine, and the result comes back. The receiving agent decides how to do it; the sender only states the outcome.
44
+
45
+ - **Compile on the PC** — “Pull the latest code, build the Windows target, send me the artifact and any errors.” The peer agent runs the build and returns the artifact path, exit code and error summary.
46
+ - **Deploy and verify on Android** — “Install the build I just made on the Android device, launch it, send a screenshot and the logs.” The peer installs, launches, screenshots and returns key log lines.
47
+ - **Plugin adaptation** — “On the Windows box, install the latest build, restart, and confirm `/mesh/v1/health` reports the new version.” The peer upgrades, restarts, probes health and reports the version.
48
+ - **Chains** — the receiving agent can call `mesh_run` itself to hand the next step to a third machine (compile on B, deploy on C), and the consolidated result is dispatched back to the origin. No central scheduler: each hop is just another `mesh_run`.
49
+
50
+ These are outcomes, not a fixed feature list: the peer agent can run any command it has permission for.
37
51
 
38
52
  ## Tools registered (callable by the agent)
39
53
 
@@ -138,6 +152,7 @@ Override by id in the profile's `cordis.patch.yml`:
138
152
  | `pingIntervalMs` | natural | `10000` | LAN health probe period |
139
153
  | `tsnetProbeIntervalMs` | natural | `60000` | Tailnet health probe period |
140
154
  | `requirePairing` | boolean | `false` | **Default off: the peer API accepts unauthenticated task POSTs.** Setting it `true` here pins pairing on; otherwise the Mesh panel's pairing switch (persisted in `state.json`) decides |
155
+ | `requireApproval` | boolean | `true` | First task from an unknown machine is held as `needs-approval` until the owner clicks Allow. Set `false` to restore fully unattended dispatch. Ignored (no prompt) when pairing is on |
141
156
  | `agentPreset` | string | `"standard"` | Agent preset for auto-created sessions |
142
157
  | `permissionPreset` | string | `"workspace-write"` | Permission preset for auto-created sessions |
143
158
  | `workspaceRoot` | string | `""` | |
@@ -175,7 +190,8 @@ Outbound dispatch tries LAN first, then each tailnet channel in order.
175
190
 
176
191
  - Ports: TCP `45917` (peer HTTP), UDP `45892` (multicast group `239.255.42.99`).
177
192
  - Discovery is intentionally public: any host on the same L2 network can see the machine and its self-reported card.
178
- - With `requirePairing: false` (the default), **any host that can reach TCP 45917 can POST a task, which wakes an agent session** using `permissionPreset`. Turn on the pairing switch in the Mesh panel (immediate, no restart) or set `requirePairing: true`, and make both machines share one secret, on untrusted networks. The token travels in a plain HTTP header — it guards against stray devices, not against a network sniffer.
193
+ - With `requireApproval: true` (the default) a first task from an unknown machine does **not** wake anything: it is held for local approval. Once approved, later tasks from that machine run unattended. Set `requireApproval: false` to get fully unattended dispatch (the pre-0.6 behaviour).
194
+ - With `requirePairing: false` (the default) there is still no cryptographic authentication of the sender: the trust decision is per-machine, made by the owner, not by a shared secret. On untrusted networks turn on the pairing switch in the Mesh panel (immediate, no restart) or set `requirePairing: true`, and make both machines share one secret. The token travels in a plain HTTP header — it guards against stray devices, not against a network sniffer.
179
195
  - 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.
180
196
  - 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.
181
197
  - 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.
@@ -203,11 +219,13 @@ npm run build:sidecar # rebuild the Go tsnet sidecar (cross-platform)
203
219
 
204
220
  - `AGENTS.md` — agent operating guide, constraints, traps (English)
205
221
  - `README.en.md` — short English quickstart (English)
222
+ - `README.md` — user-facing entry (Chinese): what it gives you, 5-minute start, safety, FAQ
223
+ - `docs/DESIGN-NOTES.md` — the old long-form README: multicast/scan/firewall details, tsnet, identity, full config table, security model, limits, development
206
224
  - `DESIGN.md` — design rationale, trade-offs and post-mortems (Chinese)
207
- - `README.md` — full documentation, Chinese, includes design rationale and post-mortems
208
225
  - `Placement设计.md` — placement design and implementation record (Chinese)
209
226
  - `设备身份与多通道设计.md` — identity and multi-channel design (Chinese)
210
227
  - `docs/index.html` — user-facing showcase, Chinese (GitHub Pages)
228
+ - `docs/demo.html` — 60-second animated walkthrough (schematic; connects to nothing)
211
229
 
212
230
  ## Contact
213
231
 
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "dsh-plugin-mesh",
3
- "version": "0.5.8",
3
+ "version": "0.5.10",
4
4
  "type": "module",
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.",
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",
7
7
  "author": "peng456 (https://github.com/peng456)",
8
8
  "keywords": [
@@ -11,14 +11,14 @@
11
11
  "deepseek-harness",
12
12
  "dsh-desktop",
13
13
  "mesh",
14
- "lan",
15
- "multicast",
16
- "discovery",
17
14
  "remote",
15
+ "multi-machine",
16
+ "long-task",
17
+ "second-machine",
18
+ "lan",
18
19
  "tailscale",
19
- "tsnet",
20
20
  "tailnet",
21
- "wireguard"
21
+ "discovery"
22
22
  ],
23
23
  "homepage": "https://github.com/peng456/dsh-plugin-mesh#readme",
24
24
  "repository": {
@@ -68,7 +68,8 @@
68
68
  "selftest:osinfo": "node lib/_selftest-osinfo.mjs",
69
69
  "selftest:update": "node lib/_selftest-update.mjs",
70
70
  "selftest:upgrade": "node lib/_selftest-upgrade.mjs",
71
- "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: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:update && npm run selftest:upgrade",
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:update && npm run selftest:upgrade",
72
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/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",
73
74
  "build:sidecar": "bash scripts/build-sidecar.sh",
74
75
  "verify:mirror": "node scripts/verify-lan-mirror.mjs",
@@ -26,17 +26,62 @@ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
26
26
  const files = ["lib/index.js", "lib/discovery.js", "lib/conversation.js", "lib/identity.js", "lib/update.js", "lib/upgrade.js"];
27
27
  let problems = 0;
28
28
 
29
- /** 逐行计算花括号深度(粗略:不解析字符串/模板串,够用) */
29
+ /**
30
+ * 去掉 `//` 行注释。只认行首或「代码分隔符之后的 //」—— `http://` 这类
31
+ * 字符串里的双斜杠不能被当成注释,否则整行后面的 `{` 会被吞掉、深度从此错位。
32
+ * (Windows 的 CRLF checkout 曾把这个问题放大成"只有 Windows 报错"。)
33
+ */
34
+ function stripLineComment(line) {
35
+ return line.replace(/(^|[\s;{(,=])\/\/.*$/, "$1");
36
+ }
37
+
38
+ /** 去掉单行字符串/模板串的内容:里面的标识符和花括号都不算代码。 */
39
+ function stripStrings(line) {
40
+ return line
41
+ .replace(/'(?:\\.|[^'\\])*'/g, '""')
42
+ .replace(/"(?:\\.|[^"\\])*"/g, '""')
43
+ .replace(/`(?:\\.|[^`\\])*`/g, '""');
44
+ }
45
+
46
+ /**
47
+ * 逐行计算花括号深度(粗略:块注释/字符串/行注释都先剥掉)。
48
+ *
49
+ * 必须做这些剥离:JSDoc 里的 `{{...}}`、URL 里的 `//`、字符串里的花括号都会
50
+ * 让朴素计数错位,而错位之后 TDZ 检查要么漏报、要么在别的行上误报。
51
+ * 行尾的 `\r` 先去掉:CRLF 会让 `/.*$/` 的匹配位置与 LF 不同。
52
+ */
30
53
  function depths(lines) {
31
54
  const out = [];
32
55
  let d = 0;
33
- for (const line of lines) {
34
- out.push(d);
35
- const code = line.replace(/\/\/.*$/, "");
56
+ let inBlock = false;
57
+ for (const raw of lines) {
58
+ let code = raw.replace(/\r$/, "");
59
+ if (inBlock) {
60
+ const end = code.indexOf("*/");
61
+ if (end === -1) {
62
+ out.push(d);
63
+ continue;
64
+ }
65
+ code = code.slice(end + 2);
66
+ inBlock = false;
67
+ }
68
+ for (;;) {
69
+ const start = code.indexOf("/*");
70
+ if (start === -1) break;
71
+ const end = code.indexOf("*/", start + 2);
72
+ if (end === -1) {
73
+ code = code.slice(0, start);
74
+ inBlock = true;
75
+ break;
76
+ }
77
+ code = code.slice(0, start) + code.slice(end + 2);
78
+ }
79
+ code = stripStrings(stripLineComment(code));
36
80
  for (const ch of code) {
37
81
  if (ch === "{") d += 1;
38
82
  else if (ch === "}") d -= 1;
39
83
  }
84
+ out.push(d);
40
85
  }
41
86
  return out;
42
87
  }
@@ -55,14 +100,14 @@ for (const rel of files) {
55
100
  seen.add(key);
56
101
 
57
102
  const D = depth[i];
58
- // 前面不能是 `.` —— `st.secret` / `msg.host` 这类属性访问不是变量引用
59
- const re = new RegExp(`(?<![.\\w$])${name.replace(/\$/g, "\\$")}\\b`);
103
+ // 前面不能是 `.`(属性访问);后面不能是 `:`(对象 key 不是变量引用)。
104
+ const re = new RegExp(`(?<![.\\w$])${name.replace(/\$/g, "\\$")}\\b(?!\\s*:)`);
60
105
  for (let j = i - 1; j >= 0; j -= 1) {
61
106
  if (depth[j] < D) break; // 出了这个块
62
107
  if (depth[j] > D) continue; // 内层块,不同作用域
63
- const text = lines[j];
108
+ const text = lines[j].replace(/\r$/, "");
64
109
  if (/^\s*(\/\/|\*|\/\*)/.test(text)) continue;
65
- if (re.test(text)) {
110
+ if (re.test(stripStrings(text))) {
66
111
  console.error(`✗ ${rel}:${j + 1} 在声明前使用了 '${name}'(声明在 ${i + 1} 行,同属深度 ${D} 的块)`);
67
112
  problems += 1;
68
113
  break;