dsh-plugin-mesh 0.5.7 → 0.5.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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";
@@ -46,9 +58,26 @@ import {
46
58
  } from "./capabilities.js";
47
59
  import { conversationKey, replyTarget } from "./conversation.js";
48
60
  import { buildDiagnostics, entryInfo, readPackageVersion } from "./diagnostics.js";
49
- import { buildUpdateReport, fetchLatestVersion, pluginDirFromUrl } from "./update.js";
61
+ import { buildUpdateReport, compareVersions, fetchLatestVersion, pluginDirFromUrl } from "./update.js";
62
+ import {
63
+ clearUpgradeMarker,
64
+ installUpdate,
65
+ readUpgradeMarker,
66
+ requestHostReload,
67
+ requestHostRestart,
68
+ trustedControlRequest,
69
+ } from "./upgrade.js";
50
70
  import { buildPrompt } from "./prompt.js";
71
+ import { matchLeadingMentions, buildAtPrompt } from "./at-mention.js";
51
72
  import { resolvePairing } from "./pairing.js";
73
+ import {
74
+ approvePeer,
75
+ isReplyToOutbound,
76
+ needsApproval,
77
+ normalizeApproved,
78
+ peerOfTask,
79
+ revokePeer,
80
+ } from "./approval.js";
52
81
  import {
53
82
  applyMeshSwitch,
54
83
  describeMeshSwitch,
@@ -79,14 +108,13 @@ import {
79
108
  export const name = "dsh-plugin-mesh";
80
109
  export const inject = ["tools", "webServer"];
81
110
 
82
- const VERSION = "0.5.7";
83
- // 诊断用:进程启动时间、入口真实路径、**磁盘上** package.json 的版本。
84
- // 这三样放一起才能回答"现在跑的到底是哪份代码" —— 只看 state.json 或重启日志
85
- // 都答不了(真踩过:磁盘升到 0.5.1,进程还在 0.5.0,界面显示 0.5.0)。
111
+ const VERSION = "0.5.9";
112
+ // 诊断用:进程启动时间 + 入口真实路径。磁盘上的版本**不在这里缓存** ——
113
+ // 升级之后进程还跑旧代码,版本号必须现读磁盘才能立刻反映出来(真踩过:
114
+ // 磁盘升到 0.5.1,进程还在 0.5.0,界面显示 0.5.0)。
86
115
  const PROCESS_STARTED_AT = Date.now() - Math.round(process.uptime() * 1000);
87
116
  const ENTRY_INFO = entryInfo(import.meta.url);
88
- const DISK_VERSION = readPackageVersion(import.meta.url);
89
- /** 本插件的安装目录:界面生成「升级命令」时直接用它,不让人再猜 <PLUGIN> 是什么。 */
117
+ /** 本插件的安装目录:一键升级要在这里替换文件,手工命令也用它填路径。 */
90
118
  const PLUGIN_DIR = pluginDirFromUrl(import.meta.url);
91
119
  /** 一次性取文件用的 nonce:进程每次启动都换,写进日志给运维/agent 取。 */
92
120
  const FILE_TRANSFER_NONCE = randomBytes(9).toString("base64url");
@@ -213,6 +241,18 @@ export const Config = z.object({
213
241
  */
214
242
  requirePairing: z.boolean().default(false),
215
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
+
216
256
  /** 对端任务在本机新建会话时用的 agent preset */
217
257
  agentPreset: z.string().default("standard"),
218
258
  /** 对端任务在本机新建会话时的权限;默认不给 danger-full-access */
@@ -220,6 +260,15 @@ export const Config = z.object({
220
260
  /** 对端任务新建会话的工作目录;留空用用户主目录 */
221
261
  workspaceRoot: z.string().default(""),
222
262
 
263
+ // ── 聊天窗口 @ 派发 ──
264
+ /**
265
+ * 聊天窗口里 `@` 一台在线机器后,发送时把这段正文直接派发过去(默认开)。
266
+ *
267
+ * 关掉后 `@` 只当普通文本:想自己决定派不派、或者让本机 agent 用 mesh_run
268
+ * 时用它。识别规则只有一条 —— **消息开头**的 @机器名(见 lib/at-mention.js)。
269
+ */
270
+ atDispatch: z.boolean().default(true),
271
+
223
272
  // ── 互联网自组网(Tailscale / tsnet)──
224
273
  //
225
274
  // 开启后插件会自动下载一个用户态 Tailscale 节点(sidecar)并加入 tailnet,
@@ -496,6 +545,53 @@ function pairingPinned(config) {
496
545
  return pairingState(config).pinned;
497
546
  }
498
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
+
499
595
  /**
500
596
  * 解析 tailnet 的**有效通道列表**(多 tailnet)。
501
597
  *
@@ -854,7 +950,7 @@ function applyUnsafe(ctx, config) {
854
950
  const diagnosticsPayload = () =>
855
951
  buildDiagnostics({
856
952
  version: VERSION,
857
- packageVersion: DISK_VERSION,
953
+ packageVersion: readPackageVersion(import.meta.url),
858
954
  entry: ENTRY_INFO.path,
859
955
  entryMtimeMs: ENTRY_INFO.mtimeMs,
860
956
  startedAt: PROCESS_STARTED_AT,
@@ -1234,6 +1330,9 @@ function applyUnsafe(ctx, config) {
1234
1330
  // 4) UI 接口
1235
1331
  registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, hostDispatched, capFor, capOverrides, throttled, waker, onHistoryChange: scheduleHistorySave, diagnostics: diagnosticsPayload, meshSwitch });
1236
1332
 
1333
+ // 5) 聊天窗口 @ 设备:消息以 @机器名 开头时,发送即派发到那台机器
1334
+ registerAtMentions(ctx, { discovery, identity, config, outbound, threadState, hostDispatched, log, warn, onHistoryChange: scheduleHistorySave, meshSwitch });
1335
+
1237
1336
  ctx.effect(() => () => {
1238
1337
  // 卸载时一并收干净:定时器、对端端口、tailnet sidecar。
1239
1338
  // 一键关闭只是"暂停",卸载才是"拆走"。
@@ -1297,6 +1396,292 @@ function findPeersByName(discovery, name) {
1297
1396
  );
1298
1397
  }
1299
1398
 
1399
+ /**
1400
+ * 对端「收下了但没唤醒 agent」的入站状态。
1401
+ *
1402
+ * 这三种都不算投递失败(消息在收件箱里),但**用户会以为任务跑了** ——
1403
+ * 聊天窗口 @ 派发要把它们翻成一句人话(见 at-mention.js 的 buildAtPrompt)。
1404
+ */
1405
+ const NOT_WOKEN_STATUS = new Set(["noted-only", "stored-only", "throttled"]);
1406
+
1407
+ /**
1408
+ * 在「同名时优先选唯一在线的那台」规则下解析一个派发目标。
1409
+ *
1410
+ * `/mesh/api/send`、`mesh_run` 和聊天窗口 @ 三条路共用同一套判断 —— 名字是
1411
+ * 用户手填的,可能重复,随便挑一台就会把任务派到错的机器上。
1412
+ *
1413
+ * @returns {{ peer: object } | { error: string }} 失败时 `error` 是给人看的中文原因。
1414
+ */
1415
+ function resolvePeerTarget(discovery, name) {
1416
+ const matches = findPeersByName(discovery, name);
1417
+ if (matches.length === 0) return { error: `找不到机器 ${name}` };
1418
+ if (matches.length > 1) {
1419
+ // 重名时优先选**唯一在线**的那台:对端重启后 instanceId 变了,旧记录要等
1420
+ // keepMs 才过期,此时目标是明确的。只有"在线的也不止一台"才需要用户指定。
1421
+ const online = matches.filter((p) => p.online);
1422
+ if (online.length === 1) return { peer: online[0] };
1423
+ return { error: `名字 "${name}" 匹配到 ${matches.length} 台机器,请用 <ip>:<port> 指定` };
1424
+ }
1425
+ return { peer: matches[0] };
1426
+ }
1427
+
1428
+ /**
1429
+ * 宿主替用户派发一条任务到某台机器(`/mesh/api/send` 与聊天窗口 @ 共用)。
1430
+ *
1431
+ * 与 `mesh_run` 的差别只在入口:这里不拼提示词、不做工具参数校验,只负责
1432
+ * 「先绑定会话键 → HTTP 派发 → 记流水」。绑定必须在 HTTP **之前**,因为对端
1433
+ * 可能先回执;失败也保留绑定(超时不等于没送到)。
1434
+ *
1435
+ * @param {object} deps 需要 discovery / config / outbound / threadState / onHistoryChange。
1436
+ * @param {object} input target、task、thread、originSession、noWake、newSession、workspace。
1437
+ * @returns {Promise<{ ok: boolean, id: string, error?: string, conflict?: string }>}
1438
+ */
1439
+ async function dispatchTaskToPeer(
1440
+ { discovery, config, outbound, threadState, hostDispatched, onHistoryChange },
1441
+ input,
1442
+ ) {
1443
+ const target = input.target;
1444
+ const id = input.id ? String(input.id) : `t-${randomBytes(6).toString("hex")}`;
1445
+ const payload = {
1446
+ id,
1447
+ from: `${machineOf(discovery)}/${safeUser()}`,
1448
+ fromMachine: machineOf(discovery),
1449
+ task: String(input.task ?? ""),
1450
+ thread: String(input.thread ?? ""),
1451
+ noWake: input.noWake === true,
1452
+ newSession: input.newSession === true,
1453
+ workspace: input.workspace ? String(input.workspace) : "",
1454
+ originSession: input.originSession ? String(input.originSession) : "",
1455
+ // 人手动派发的(聊天窗口 @ / Mesh 面板「派发任务」)。
1456
+ // 对端据此跳过"太短 / 纯寒暄"闸门 —— 那道闸门是给 agent 互刷准备的,
1457
+ // 不是用来吞掉人敲的一句「看下磁盘」的。
1458
+ human: input.human === true,
1459
+ };
1460
+ // 没给 thread 就自己生成一个:没有 thread → 没有会话键 → 对端回执只能新开会话。
1461
+ if (!payload.thread) payload.thread = `ui-${id}`;
1462
+
1463
+ const replyKey = conversationKey({ fromMachine: target.machine, thread: payload.thread });
1464
+ if (replyKey && payload.originSession) {
1465
+ if (pendingByConv.has(replyKey)) {
1466
+ return { ok: false, id, conflict: "pending", error: "此 thread 正在建立会话,请稍后重试" };
1467
+ }
1468
+ const previous = threadState.get(replyKey);
1469
+ if (previous?.sessionId && previous.sessionId !== payload.originSession) {
1470
+ return { ok: false, id, conflict: "bound", error: "该 thread 已绑定另一会话,请换一个 thread" };
1471
+ }
1472
+ threadState.set(replyKey, { ...previous, wakesAt: previous?.wakesAt ?? [], sessionId: payload.originSession });
1473
+ saveThreads(threadState);
1474
+ hostDispatched.set(payload.thread, Date.now());
1475
+ // 顺手清理过期条目,别让它无限增长
1476
+ for (const [thread, at] of hostDispatched) {
1477
+ if (Date.now() - at > 3600_000) hostDispatched.delete(thread);
1478
+ }
1479
+ }
1480
+
1481
+ try {
1482
+ const r = await peerFetch(target, "/mesh/v1/task", {
1483
+ method: "POST",
1484
+ headers: { "Content-Type": "application/json", "X-Dsh-Mesh-Token": currentSecret() },
1485
+ body: JSON.stringify(payload),
1486
+ timeoutMs: input.timeoutMs ?? config.requestTimeoutMs,
1487
+ });
1488
+ const rb = await r.json().catch(() => ({}));
1489
+ // 对端"收下了但没唤醒 agent"要能看出来。旧版本对端不回 status,
1490
+ // 这时只能当"已派发"(绝不倒过来假装失败 —— 送达是事实)。
1491
+ const notWoken = NOT_WOKEN_STATUS.has(String(rb?.status ?? ""))
1492
+ ? { status: String(rb.status), reason: String(rb?.routeDecision ?? "") }
1493
+ : null;
1494
+ // 对端第一次收到这台机器的活:它要点一次「允许」才执行(202)。
1495
+ // 这不是失败 —— 送达了,只是在等人。界面要能看出这个中间态。
1496
+ const pendingApproval = r.status === 202 && rb?.pendingApproval === true;
1497
+ outbound.push({
1498
+ ...payload,
1499
+ toMachine: target.machine,
1500
+ at: new Date().toISOString(),
1501
+ ok: r.ok,
1502
+ status: r.status,
1503
+ remoteStatus: pendingApproval ? "needs-approval" : (rb?.status ?? ""),
1504
+ ...(pendingApproval ? { noted: true, note: "等对端点一次「允许」" } : {}),
1505
+ ...(notWoken ? { noted: true, note: notWoken.reason } : {}),
1506
+ });
1507
+ onHistoryChange?.();
1508
+ if (outbound.length > MAX_HISTORY) outbound.shift();
1509
+ if (!r.ok) {
1510
+ return {
1511
+ ok: false,
1512
+ id,
1513
+ status: r.status,
1514
+ error:
1515
+ String(rb?.error ?? `HTTP ${r.status}`) +
1516
+ (r.status === 403 ? "(对端开启了 requirePairing 且两端配对码不一致 —— 在「配对码」里对齐)" : ""),
1517
+ };
1518
+ }
1519
+ return { ok: true, id, status: r.status, noted: notWoken, pendingApproval };
1520
+ } catch (err) {
1521
+ outbound.push({
1522
+ ...payload,
1523
+ toMachine: target.machine,
1524
+ at: new Date().toISOString(),
1525
+ ok: false,
1526
+ error: String(err?.message ?? err),
1527
+ });
1528
+ onHistoryChange?.();
1529
+ if (outbound.length > MAX_HISTORY) outbound.shift();
1530
+ return { ok: false, id, error: err?.name === "TimeoutError" ? "派发超时(对方可能仍在处理)" : String(err?.message ?? err) };
1531
+ }
1532
+ }
1533
+
1534
+ /**
1535
+ * 聊天窗口 @ 设备:消息以 @机器名 开头时,把正文直接派发到那台机器。
1536
+ *
1537
+ * 与 `/mesh/api/send` 走同一份派发实现,只是入口不同:用户在 composer 里
1538
+ * 打 @、从菜单里选中在线设备,发送时就等于把这句正文交给了那台机器。
1539
+ * 识别规则与失败文案在 lib/at-mention.js(纯逻辑,单测覆盖)。
1540
+ *
1541
+ * 三条必须守住的边界:
1542
+ * 1. 只认**消息开头**的 @;正文中间的 @ 不自动派发(多半是"提到某台机器")。
1543
+ * 2. 派发失败必须说出来,并且明确"没有在本机执行" —— 静默失败会让人以为
1544
+ * 任务已经在对面跑了,或者让 agent 顺手在本机把远端任务执行一遍。
1545
+ * 3. 同一条消息只派发一次:pre-step 在某些路径上会拿到同一批 claimed 消息,
1546
+ * 按 message.id 记账即可(改写后的正文里已经没有 @ 了,但重试路径拿到的
1547
+ * 仍是原始消息)。
1548
+ */
1549
+ function registerAtMentions(
1550
+ ctx,
1551
+ { discovery, identity, config, outbound, threadState, hostDispatched, log, warn, onHistoryChange, meshSwitch },
1552
+ ) {
1553
+ // 派发依赖集中一份:dispatchTaskToPeer 与 /mesh/api/send 用同一组入参。
1554
+ const deps = { discovery, config, outbound, threadState, hostDispatched, onHistoryChange };
1555
+ if (config.atDispatch === false) {
1556
+ log("聊天窗口 @ 派发已关闭(config.atDispatch = false)");
1557
+ return;
1558
+ }
1559
+ if (typeof ctx?.on !== "function") {
1560
+ log("聊天窗口 @ 派发未启用:本机 DSH 没有 agent/pre-step 事件");
1561
+ return;
1562
+ }
1563
+
1564
+ /** 已派发过的消息 id(上限 200 条,只用来挡 pre-step 的重复投喂)。 */
1565
+ const handled = new Set();
1566
+ const markHandled = (id) => {
1567
+ if (!id) return;
1568
+ handled.add(id);
1569
+ if (handled.size > 200) handled.delete(handled.values().next().value);
1570
+ };
1571
+
1572
+ /** 目前已知的机器名(含离线):mention 必须先命中一个已知名字。 */
1573
+ const knownNames = () =>
1574
+ [...new Set([identity.name, ...discovery.peers().map((p) => String(p?.machine ?? "").trim())])].filter(Boolean);
1575
+
1576
+ /**
1577
+ * 处理一条消息:认出开头的 @目标 → 派发 → 返回改写后的消息(没有目标时返回 null)。
1578
+ *
1579
+ * @returns {Promise<object|null>} 改写后的消息;null = 这条消息不需要动。
1580
+ */
1581
+ async function dispatchMessage(message, agent, signal) {
1582
+ const head = Array.isArray(message?.content) ? message.content[0] : undefined;
1583
+ if (!head || head.type !== "text" || typeof head.text !== "string") return null;
1584
+ const parsed = matchLeadingMentions(head.text, knownNames());
1585
+ if (parsed.mentions.length === 0) return null;
1586
+ if (message.id && handled.has(message.id)) return null;
1587
+
1588
+ const originSession = agent?.session?.id ? String(agent.session.id) : "";
1589
+ const results = [];
1590
+ const body = parsed.body;
1591
+ for (const mention of parsed.mentions) {
1592
+ if (signal?.aborted) break;
1593
+ if (!body) {
1594
+ results.push({ machine: mention.machine, error: "消息里只有 @ 设备名,没有正文" });
1595
+ continue;
1596
+ }
1597
+ const found = resolvePeerTarget(discovery, mention.machine);
1598
+ if (found.error) {
1599
+ results.push({ machine: mention.machine, error: found.error });
1600
+ continue;
1601
+ }
1602
+ const target = found.peer;
1603
+ if (String(target.machine) === identity.name) {
1604
+ results.push({ machine: target.machine, error: "这就是本机,不需要跨机派发" });
1605
+ continue;
1606
+ }
1607
+ if (!target.online) {
1608
+ results.push({ machine: target.machine, error: "这台机器当前离线" });
1609
+ continue;
1610
+ }
1611
+ if (meshSwitch && meshSwitch.status().all) {
1612
+ results.push({ machine: target.machine, error: "本机 mesh 已全部关闭(局域网 + 互联网)" });
1613
+ continue;
1614
+ }
1615
+ const id = `t-${randomBytes(6).toString("hex")}`;
1616
+ const result = await dispatchTaskToPeer(deps, {
1617
+ id,
1618
+ target,
1619
+ task: body,
1620
+ // 每条 @ 派发各自一个 thread:回执落回这个会话,不同机器/不同条不串线。
1621
+ thread: `at-${id}`,
1622
+ originSession,
1623
+ // 交互式发送要等人:不能因为一条通道挂着就把用户这一轮卡满 20 秒。
1624
+ timeoutMs: Math.min(Number(config.requestTimeoutMs) || 8000, 8000),
1625
+ // 聊天窗口里的话是人敲的:对端不该用"太短/寒暄"闸门把它吞成「仅记录」。
1626
+ human: true,
1627
+ });
1628
+ if (result.ok && result.noted) {
1629
+ results.push({
1630
+ machine: target.machine,
1631
+ id: result.id,
1632
+ note: result.noted.reason || result.noted.status || "对端没有唤醒 agent",
1633
+ });
1634
+ } else if (result.ok) {
1635
+ results.push({ machine: target.machine, id: result.id });
1636
+ } else {
1637
+ results.push({ machine: target.machine, error: result.error || "派发失败" });
1638
+ }
1639
+ }
1640
+
1641
+ markHandled(message.id);
1642
+ const summary = results
1643
+ .map((r) => (r.id ? `${r.machine}(${r.id})` : `${r.machine} 未派发:${r.error}`))
1644
+ .join(";");
1645
+ log(`聊天窗口 @ 派发:${summary}`);
1646
+ return {
1647
+ ...message,
1648
+ content: [{ type: "text", text: buildAtPrompt({ body, results }) }, ...message.content.slice(1)],
1649
+ };
1650
+ }
1651
+
1652
+ ctx.on(
1653
+ "agent/pre-step",
1654
+ async ({ agent, messages, signal }, next) => {
1655
+ const decision = await next();
1656
+ if (!decision || decision.kind === "reject" || !Array.isArray(decision.messages)) return decision;
1657
+ let changed = false;
1658
+ const rewritten = [];
1659
+ for (const message of decision.messages) {
1660
+ if (message?.role !== "user" || message?.source?.kind !== "user") {
1661
+ rewritten.push(message);
1662
+ continue;
1663
+ }
1664
+ let replaced = null;
1665
+ try {
1666
+ replaced = await dispatchMessage(message, agent, signal);
1667
+ } catch (err) {
1668
+ // 派发出错不能让这一轮直接失败:消息原样放行,把原因留在日志里。
1669
+ warn(`聊天窗口 @ 派发出错(消息未改写):${err?.message ?? err}`);
1670
+ }
1671
+ if (replaced) {
1672
+ rewritten.push(replaced);
1673
+ changed = true;
1674
+ } else {
1675
+ rewritten.push(message);
1676
+ }
1677
+ }
1678
+ return changed ? { ...decision, messages: rewritten } : decision;
1679
+ },
1680
+ { prepend: true },
1681
+ );
1682
+ log("聊天窗口 @ 设备已就绪(消息以 @机器名 开头时,发送即派发到那台机器)");
1683
+ }
1684
+
1300
1685
  // ───────────────────────── 入站唤醒(自包含) ─────────────────────────
1301
1686
 
1302
1687
  /**
@@ -1618,18 +2003,28 @@ const NOTICE_ONLY = /^\s*(?:\[?(?:ping|pong|ack|ok|roger|hello|hi|hey)\]?|收到
1618
2003
  * @param {(thread: string) => number} capFor 取该 thread 的生效上限(含用户手动提高的覆盖值)
1619
2004
  * @returns {{wake: true} | {wake: false, kind: string, reason: string}}
1620
2005
  */
1621
- function classifyInbound(task, threadState, config, now, capFor, { canInject = false } = {}) {
2006
+ function classifyInbound(task, threadState, config, now, capFor, { canInject = false, humanReply = false } = {}) {
1622
2007
  const body = String(task.task ?? "").trim();
2008
+ // 人手动派发的(聊天窗口 @ 设备 / 面板「派发任务」),以及**它们的回执**,
2009
+ // 不适用下面两道内容闸门:闸门是给 agent 互刷 ping/ack 用的,不是用来吞掉
2010
+ // 人敲的一句话(「看下磁盘」4 个字)或它的答案的。
2011
+ const humanTask = task.human === true;
2012
+ const bypassGates = humanTask || humanReply;
1623
2013
 
1624
2014
  // 1) 显式豁免:发送方声明"这条只回执,别开跑"
1625
- if (task.noWake === true) return { wake: false, kind: "noWake", reason: "发送方标记 noWake" };
2015
+ //
2016
+ // 例外:这是**人发起的派发**的回执(humanReply)。人性的期待是"我 @ 了它、
2017
+ // 它会答",而对端 agent 常把自己的结果也标成"回执"→ noWake → 被扣在收件箱
2018
+ // (2026-10-30 真机:dshgo-dsh 的机器状态回报停在 noted-only,会话里看不到)。
2019
+ // 回执本身就是用户问题的答案,必须投递。
2020
+ if (task.noWake === true && !humanReply) return { wake: false, kind: "noWake", reason: "发送方标记 noWake" };
1626
2021
 
1627
2022
  // 2) 内容闸门:太短或纯寒暄
1628
2023
  const minChars = config.minTaskChars ?? 24;
1629
- if (body.length < minChars) {
2024
+ if (!bypassGates && body.length < minChars) {
1630
2025
  return { wake: false, kind: "short", reason: `正文仅 ${body.length} 字符 < minTaskChars(${minChars})` };
1631
2026
  }
1632
- if (NOTICE_ONLY.test(body)) return { wake: false, kind: "notice", reason: "纯寒暄/回执内容" };
2027
+ if (!bypassGates && NOTICE_ONLY.test(body)) return { wake: false, kind: "notice", reason: "纯寒暄/回执内容" };
1633
2028
 
1634
2029
  // 3) 限速:同一**会话**在滑动窗口内的自动唤醒次数(不是终身配额)
1635
2030
  //
@@ -1688,9 +2083,11 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
1688
2083
  // (2026-10-21 手动派发实测:一轮几十条)。
1689
2084
  if (task?.thread) {
1690
2085
  const from = String(task.fromMachine || String(task.from || "").split("/")[0] || "");
1691
- task.isReply = (outbound ?? []).some(
1692
- (o) => String(o.toMachine || "") === from && String(o.thread || "") === String(task.thread),
1693
- );
2086
+ const sameThread = (o) => String(o.toMachine || "") === from && String(o.thread || "") === String(task.thread);
2087
+ task.isReply = (outbound ?? []).some(sameThread);
2088
+ // 人发起的派发(聊天窗口 @ / 面板手动派发)的回执:即使发送方标了 noWake,
2089
+ // 也要投递回会话 —— 那是用户等着的答案,不是可以静默丢掉的寒暄。
2090
+ task.humanReply = task.isReply && (outbound ?? []).some((o) => sameThread(o) && o.human === true);
1694
2091
  }
1695
2092
  const rec = inbound.find((t) => t.id === task.id);
1696
2093
  // 记下"回信地址",与"本机用哪个会话处理"是两件事。对端可以 GET
@@ -1720,7 +2117,10 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
1720
2117
  // 冷却对它照常生效(因为确实要建会话)。
1721
2118
  const canInject = task.newSession !== true && !!liveSession(knownSessionId);
1722
2119
 
1723
- const verdict = classifyInbound(task, threadState, config, now, capFor, { canInject });
2120
+ if (task.noWake === true && task.humanReply === true) {
2121
+ log(`任务 ${task.id} 标了 noWake,但它是人发起派发的回执:照常投递到会话`);
2122
+ }
2123
+ const verdict = classifyInbound(task, threadState, config, now, capFor, { canInject, humanReply: task.humanReply === true });
1724
2124
  if (!verdict.wake) {
1725
2125
  if (rec) {
1726
2126
  rec.status = verdict.kind === "cap" ? "throttled" : "noted-only";
@@ -2432,6 +2832,9 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
2432
2832
  noWake: body.noWake === true,
2433
2833
  newSession: body.newSession === true,
2434
2834
  workspace: body.workspace ? String(body.workspace) : "",
2835
+ // 人手动派发(聊天窗口 @ / 面板「派发任务」)。旧版本发送方不带这个字段,
2836
+ // 缺省 false —— 对它们保持原来的闸门行为。
2837
+ human: body.human === true,
2435
2838
  receivedAt: new Date().toISOString(),
2436
2839
  sourceAddress: origin.address,
2437
2840
  transport: origin.transport,
@@ -2444,6 +2847,25 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
2444
2847
  if (inbound.length > MAX_HISTORY) inbound.shift();
2445
2848
  }
2446
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
+ }
2447
2869
  if (!duplicate) {
2448
2870
  try {
2449
2871
  handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled, onHistoryChange, outbound);
@@ -2451,7 +2873,16 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
2451
2873
  warn(`处理入站任务异常: ${err?.message ?? err}`);
2452
2874
  }
2453
2875
  }
2454
- return send(res, 200, { ok: true, id: task.id, duplicate });
2876
+ // 路由结论同步可见:闸门类拦截(太短/寒暄/限速/唤醒不可用)在
2877
+ // handleInboundTask 里是**同步**写进记录的,所以这里已经能读到;
2878
+ // 派发成功是异步的,此时通常还是 accepted,发送方按"已派发"处理即可。
2879
+ return send(res, 200, {
2880
+ ok: true,
2881
+ id: task.id,
2882
+ duplicate,
2883
+ status: task.status,
2884
+ routeDecision: task.routeDecision ?? "",
2885
+ });
2455
2886
  }
2456
2887
 
2457
2888
  return send(res, 404, { ok: false, error: "not found" });
@@ -2846,23 +3277,8 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2846
3277
  : send(res, 405, { ok: false, error: `method ${req.method} not allowed; use POST` }),
2847
3278
  );
2848
3279
 
2849
- /** 返回 { peer } 或 { error },避免撞名时静默挑错机器 */
2850
- const findPeer = (name) => {
2851
- const matches = findPeersByName(discovery, name);
2852
- if (matches.length === 0) return { error: `找不到机器 ${name}` };
2853
- if (matches.length > 1) {
2854
- // 重名时优先选**唯一在线**的那台。
2855
- //
2856
- // 典型场景:对端重启后 instanceId 变了(旧版插件不持久化 id),旧记录
2857
- // 要等 keepMs 才过期,于是同名两条、其中一条在线。此时目标是明确的 ——
2858
- // 离线那条要么是同一台机器的残留,要么本来就派不过去。只有"在线的也
2859
- // 不止一台"才真的需要用户用 <ip>:<port> 指明。
2860
- const online = matches.filter((p) => p.online);
2861
- if (online.length === 1) return { peer: online[0] };
2862
- return { error: `名字 "${name}" 匹配到 ${matches.length} 台机器,请用 <ip>:<port> 指定` };
2863
- }
2864
- return { peer: matches[0] };
2865
- };
3280
+ /** 返回 { peer } 或 { error },避免撞名时静默挑错机器(规则见模块级 resolvePeerTarget) */
3281
+ const findPeer = (name) => resolvePeerTarget(discovery, name);
2866
3282
 
2867
3283
  /** 重名检测:名字是人手填的,撞名会让 mesh_run --peer 有歧义 */
2868
3284
  /**
@@ -2898,6 +3314,9 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2898
3314
  const channelViews = tailnetChannels.map((c) => tailnetChannelView(c, tailnetNodes.get(c.id) ?? null));
2899
3315
  // 兼容旧界面:node / hostname / authKeySaved 取"第一条启用的通道"
2900
3316
  const primary = channelViews.find((c) => c.enabled) ?? channelViews[0] ?? null;
3317
+ // 磁盘版本**每次现读**:装好新版本但没重启时,这个接口要立刻显示"磁盘已是新版",
3318
+ // 否则界面会一直按启动时的常量说"没有更新"。
3319
+ const diskVersion = readPackageVersion(import.meta.url);
2901
3320
  return {
2902
3321
  ok: true,
2903
3322
  self: {
@@ -2914,8 +3333,8 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2914
3333
  version: VERSION,
2915
3334
  // 磁盘上的版本 vs 本进程加载的版本。两者不一致 = 升级了但没重启,
2916
3335
  // 界面要明说"重启后生效",否则用户会拿旧行为当新版本的 bug 报上来。
2917
- diskVersion: DISK_VERSION,
2918
- versionDrift: !!DISK_VERSION && DISK_VERSION !== VERSION,
3336
+ diskVersion,
3337
+ versionDrift: !!diskVersion && diskVersion !== VERSION,
2919
3338
  secret: currentSecret(),
2920
3339
  // 本机的能力名片(对端看到的也是这一份)。**本机直接读采集缓存**,
2921
3340
  // 不走网络 —— 和 mac 一样,"自己的信息"没必要绕一圈。
@@ -2937,6 +3356,8 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2937
3356
  // 界面开关一改就得立刻反映出来(端到端测试就是在这抓到过一次 stale)。
2938
3357
  requirePairing: pairingRequired(config),
2939
3358
  requirePairingPinned: pairingPinned(config),
3359
+ // 陌生设备首次派活是否要本机点一次「允许」(默认开)
3360
+ requireApproval: config.requireApproval !== false,
2940
3361
  useMulticast: config.useMulticast !== false,
2941
3362
  scanOnStart: config.scanOnStart !== false,
2942
3363
  scanIntervalMs: config.scanIntervalMs,
@@ -2965,6 +3386,22 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2965
3386
  switch: meshSwitch ? meshSwitch.status() : null,
2966
3387
  peers: discovery.peers(),
2967
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(),
2968
3405
  inbound: inbound.slice(-30).reverse(),
2969
3406
  outbound: outbound.slice(-30).reverse(),
2970
3407
  // 被限速挡下的 thread:给页面渲染"是否提高上限"的提示
@@ -2983,6 +3420,43 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2983
3420
  };
2984
3421
 
2985
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
+ });
2986
3460
  // 只读诊断:UI 的「诊断」卡片用它;与 /mesh/v1/diagnostics 同一份数据。
2987
3461
  route("/mesh/api/diagnostics", (_req, res) => send(res, 200, diagnostics()));
2988
3462
 
@@ -3000,6 +3474,32 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
3000
3474
  const UPDATE_OK_TTL_MS = 30 * 60 * 1000;
3001
3475
  const UPDATE_FAIL_TTL_MS = 60 * 1000;
3002
3476
  let updateCache = null;
3477
+ /** 升级完成后的「待生效」标记:进程仍是旧代码,界面据它给重启/重载而不是再装一次。 */
3478
+ const upgradeMarkerPath = () => join(stateDir(), "upgrade.json");
3479
+ const pendingUpgradeFrom = (diskVersion) => {
3480
+ if (!diskVersion || compareVersions(diskVersion, VERSION) !== 1) return null;
3481
+ const marker = readUpgradeMarker(upgradeMarkerPath());
3482
+ if (marker && marker.version === diskVersion) {
3483
+ return {
3484
+ version: diskVersion,
3485
+ previous: String(marker.previous || VERSION),
3486
+ at: String(marker.at || ""),
3487
+ restartRequired: marker.restartRequired === true,
3488
+ reloadRequired: marker.reloadRequired === true,
3489
+ inferred: false,
3490
+ };
3491
+ }
3492
+ // 没有标记但磁盘比进程新 = 手工装过(或标记没写成),只能保守地提示重启。
3493
+ return {
3494
+ version: diskVersion,
3495
+ previous: VERSION,
3496
+ at: "",
3497
+ restartRequired: true,
3498
+ reloadRequired: false,
3499
+ inferred: true,
3500
+ };
3501
+ };
3502
+
3003
3503
  route("/mesh/api/update", async (req, res) => {
3004
3504
  const force = /[?&]force=1(?:&|$)/.test(String(req.url || ""));
3005
3505
  const now = Date.now();
@@ -3009,13 +3509,23 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
3009
3509
  return send(res, 200, { ...updateCache.report, cached: true });
3010
3510
  }
3011
3511
  }
3512
+ // 磁盘版本**每次现读**:装好新版本但没重启时,这里必须立刻反映磁盘上的版本。
3513
+ const diskVersion = readPackageVersion(import.meta.url);
3514
+ const marker = readUpgradeMarker(upgradeMarkerPath());
3515
+ if (marker && marker.version === VERSION) {
3516
+ clearUpgradeMarker(upgradeMarkerPath()); // 已经重启生效
3517
+ } else if (marker && marker.version !== diskVersion) {
3518
+ clearUpgradeMarker(upgradeMarkerPath()); // 磁盘被回滚或手工改过,标记已失效
3519
+ }
3520
+ const pendingUpgrade = pendingUpgradeFrom(diskVersion);
3012
3521
  // 5 秒:主页是首屏,等不起更久;两源合计最坏也就 10 秒。
3013
3522
  const latest = await fetchLatestVersion({ timeoutMs: 5000 });
3014
3523
  const report = buildUpdateReport({
3015
3524
  current: VERSION,
3016
- diskVersion: DISK_VERSION,
3525
+ diskVersion,
3017
3526
  latest,
3018
3527
  pluginDir: PLUGIN_DIR,
3528
+ pendingUpgrade,
3019
3529
  now: Date.now(),
3020
3530
  });
3021
3531
  updateCache = { at: Date.now(), report };
@@ -3023,6 +3533,78 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
3023
3533
  send(res, 200, report);
3024
3534
  });
3025
3535
 
3536
+ /**
3537
+ * 一键升级(写操作,POST + 同源回环守卫)。
3538
+ *
3539
+ * 顺序:下载新包 → sha512 校验 → 解包到 staging → 真实 import 可加载检查
3540
+ * → 备份旧目录 → 原子替换。任何一步失败都保留旧版;只有 ok:true 且
3541
+ * installed:true 才代表磁盘已换新(进程仍跑旧代码,需重启或重载界面)。
3542
+ */
3543
+ let upgradeRunning = false;
3544
+ post("/mesh/api/upgrade", async (req, res) => {
3545
+ if (!trustedControlRequest(req)) {
3546
+ return send(res, 403, { ok: false, error: "升级接口只接受同源回环请求" });
3547
+ }
3548
+ if (upgradeRunning) return send(res, 409, { ok: false, error: "已经有一次升级在进行中" });
3549
+ const body = await readJson(req);
3550
+ const version = String(body?.version ?? "").trim();
3551
+ const diskVersion = readPackageVersion(import.meta.url);
3552
+ // 磁盘已经是目标版本:不重复下载/覆盖,直接按"已装好"回报。
3553
+ if (diskVersion === version && compareVersions(version, VERSION) === 1) {
3554
+ const pendingUpgrade = pendingUpgradeFrom(diskVersion);
3555
+ return send(res, 200, {
3556
+ ok: true,
3557
+ installed: false,
3558
+ upToDate: true,
3559
+ version,
3560
+ changed: null,
3561
+ restartRequired: pendingUpgrade ? pendingUpgrade.restartRequired : true,
3562
+ reloadRequired: pendingUpgrade ? pendingUpgrade.reloadRequired : false,
3563
+ });
3564
+ }
3565
+ upgradeRunning = true;
3566
+ try {
3567
+ const report = await installUpdate({
3568
+ version,
3569
+ current: VERSION,
3570
+ pluginDir: PLUGIN_DIR,
3571
+ markerPath: upgradeMarkerPath(),
3572
+ log,
3573
+ });
3574
+ updateCache = null; // 下一次 /update 重新读磁盘版本
3575
+ if (!report.ok) warn(`升级失败(${report.stage || "?"}):${report.error}`);
3576
+ send(res, 200, report);
3577
+ } finally {
3578
+ upgradeRunning = false;
3579
+ }
3580
+ });
3581
+
3582
+ /**
3583
+ * 重启宿主,让新装好的宿主半生效。
3584
+ *
3585
+ * 走 DSH Desktop 自带的 `desktopSettingsController.restart()`(原生确认 + 有序
3586
+ * relaunch,和切换 profile 同一条路);没有这个入口的宿主返回 mode:"manual",
3587
+ * 让界面明确告诉用户手动重启 —— 不用 shell 脚本,也就没有重启循环那类风险。
3588
+ */
3589
+ post("/mesh/api/upgrade/restart", async (req, res) => {
3590
+ if (!trustedControlRequest(req)) {
3591
+ return send(res, 403, { ok: false, error: "重启接口只接受同源回环请求" });
3592
+ }
3593
+ if (upgradeRunning) return send(res, 409, { ok: false, error: "升级还没结束,稍后再重启" });
3594
+ send(res, 200, await requestHostRestart(ctx));
3595
+ });
3596
+
3597
+ /**
3598
+ * 重载渲染器,让只改了 client 的新版本生效(不重启宿主)。
3599
+ * DSH Desktop 有内置入口;其它宿主返回 mode:"self",由页面自己 reload。
3600
+ */
3601
+ post("/mesh/api/upgrade/reload", async (req, res) => {
3602
+ if (!trustedControlRequest(req)) {
3603
+ return send(res, 403, { ok: false, error: "重载接口只接受同源回环请求" });
3604
+ }
3605
+ send(res, 200, requestHostReload(ctx));
3606
+ });
3607
+
3026
3608
  /**
3027
3609
  * 用户决定提高某个 thread 的限速上限。
3028
3610
  *
@@ -3154,6 +3736,58 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
3154
3736
  return send(res, 200, { ok: true, requirePairing: want });
3155
3737
  });
3156
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
+
3157
3791
  /**
3158
3792
  * 界面上的「一键关闭」。
3159
3793
  *
@@ -3518,88 +4152,67 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
3518
4152
  const target = found.peer;
3519
4153
 
3520
4154
  const id = `t-${randomBytes(6).toString("hex")}`;
3521
- let createdSessionId = "";
3522
- const payload = {
3523
- id,
3524
- from: `${machineOf(discovery)}/${safeUser()}`,
3525
- fromMachine: machineOf(discovery),
3526
- task,
3527
- thread: body?.thread ? String(body.thread) : "",
3528
- noWake: body?.noWake === true,
3529
- newSession: body?.newSession === true,
3530
- workspace: body?.workspace ? String(body.workspace) : "",
3531
- // 页面手动派发时,UI 会带上「当前会话 id」,回执就能落回那个会话。
3532
- // 不带的话宿主没有绑定可登记,对端回传只能新开一个 mesh-* 会话 ——
3533
- // 这正是「手动派发后回执自己长出一个新会话」的原因。
3534
- originSession: body?.originSession ? String(body.originSession) : "",
3535
- };
3536
-
3537
4155
  // 页面派发如果没填 thread,就自己生成一个。
3538
4156
  //
3539
- // 「线程标识(可选)」留空时,payload.thread 是空串 → 没有绑定键 →
3540
- // 对端按提示词里的兜底(thread 填任务 id)回执 → 我们这边算出的键完全对不上,
3541
- // 只能新开会话。真机复测就是这样:回执的 thread 是 t-xxxx(对方任务 id)。
3542
- if (!payload.thread) {
3543
- payload.thread = `ui-${id}`;
3544
- }
4157
+ // 「线程标识(可选)」留空时没有绑定键 → 对端按提示词里的兜底(thread 填任务 id)
4158
+ // 回执 → 我们这边算出的键完全对不上,只能新开会话。真机复测就是这样:
4159
+ // 回执的 thread 是 t-xxxx(对方任务 id)。
4160
+ const thread = body?.thread ? String(body.thread) : `ui-${id}`;
4161
+ let originSession = body?.originSession ? String(body.originSession) : "";
4162
+ let createdSessionId = "";
3545
4163
 
3546
4164
  // 页面派发时**预建一个会话**,回执才有地方可去。
3547
4165
  //
3548
4166
  // 只靠 UI 传当前会话不够:Mesh 面板拿不到 selection 时 sessionId 是空的,
3549
4167
  // 绑定整段被跳过,回执就只能新开会话(真机反馈「mac 没有预先生成会话」)。
3550
4168
  // 这里在宿主侧兜底:还没绑定、但有 thread、且唤醒能力可用 → 先建一个空会话。
3551
- if (!payload.originSession && payload.thread && waker?.ready) {
4169
+ if (!originSession && waker?.ready) {
3552
4170
  try {
3553
- payload.originSession = await createIdleSession(
4171
+ originSession = await createIdleSession(
3554
4172
  waker,
3555
4173
  config,
3556
- { id, from: payload.from, thread: payload.thread, toMachine: target.machine, transport: target.transport },
4174
+ {
4175
+ id,
4176
+ from: `${machineOf(discovery)}/${safeUser()}`,
4177
+ thread,
4178
+ toMachine: target.machine,
4179
+ transport: target.transport,
4180
+ },
3557
4181
  warn,
3558
4182
  // 格式(用户指定):第一行「向 X 发送的消息」→ 原文 → 末行「等待 X 回复」。
3559
4183
  // 末行同时承担「别在本机执行」的职责:只写「等待回复」是状态描述,
3560
4184
  // agent 仍会把上面的原文当任务执行,必须让它明确知道别动手。
3561
4185
  { text: `向 ${target.machine} 发送的消息 如下:\n${task}\n———\n[Mesh 已派发 → ${target.machine}/${id}] 现在什么都不用做:不要调用任何工具、不要回派,回一句「等待回执」即可。` },
3562
4186
  );
3563
- createdSessionId = payload.originSession;
4187
+ createdSessionId = originSession;
3564
4188
  } catch (err) {
3565
4189
  warn(`预建会话失败(回执将新建会话):${err?.message ?? err}`);
3566
4190
  }
3567
4191
  }
3568
4192
 
3569
- // 与 mesh_run 相同的登记:必须在 HTTP **之前**绑定,因为对端可能先回执。
3570
- const replyKey = conversationKey({ fromMachine: target.machine, thread: payload.thread });
3571
- if (replyKey && payload.originSession) {
3572
- if (pendingByConv.has(replyKey)) {
3573
- return send(res, 409, { ok: false, error: "此 thread 正在建立会话,请稍后重试" });
3574
- }
3575
- const previous = threadState.get(replyKey);
3576
- if (previous?.sessionId && previous.sessionId !== payload.originSession) {
3577
- return send(res, 409, { ok: false, error: "该 thread 已绑定另一会话,请换一个 thread" });
3578
- }
3579
- threadState.set(replyKey, { ...previous, wakesAt: previous?.wakesAt ?? [], sessionId: payload.originSession });
3580
- saveThreads(threadState);
3581
- hostDispatched.set(payload.thread, Date.now());
3582
- // 顺手清理过期条目,别让它无限增长
3583
- for (const [t, at] of hostDispatched) {
3584
- if (Date.now() - at > 3600_000) hostDispatched.delete(t);
3585
- }
3586
- }
3587
-
3588
- try {
3589
- const r = await peerFetch(target, "/mesh/v1/task", {
3590
- method: "POST",
3591
- headers: { "Content-Type": "application/json", "X-Dsh-Mesh-Token": currentSecret() },
3592
- body: JSON.stringify(payload),
3593
- timeoutMs: config.requestTimeoutMs,
3594
- });
3595
- const rb = await r.json().catch(() => ({}));
3596
- outbound.push({ ...payload, toMachine: target.machine, at: new Date().toISOString(), ok: r.ok, status: r.status });
3597
- onHistoryChange?.();
3598
- if (outbound.length > MAX_HISTORY) outbound.shift();
3599
- return send(res, r.ok ? 200 : 502, { ok: r.ok, id, sessionId: payload.originSession || "", error: rb?.error });
3600
- } catch (err) {
3601
- return send(res, 502, { ok: false, error: String(err?.message ?? err) });
3602
- }
4193
+ const result = await dispatchTaskToPeer(
4194
+ { discovery, config, outbound, threadState, hostDispatched, onHistoryChange },
4195
+ {
4196
+ id,
4197
+ target,
4198
+ task,
4199
+ thread,
4200
+ originSession,
4201
+ noWake: body?.noWake === true,
4202
+ newSession: body?.newSession === true,
4203
+ workspace: body?.workspace ? String(body.workspace) : "",
4204
+ human: true,
4205
+ },
4206
+ );
4207
+ if (!result.ok && result.conflict) return send(res, 409, { ok: false, error: result.error });
4208
+ return send(res, result.ok ? 200 : 502, {
4209
+ ok: result.ok,
4210
+ id: result.id,
4211
+ sessionId: originSession || createdSessionId,
4212
+ error: result.error,
4213
+ ...(result.noted ? { noted: true, reason: result.noted.reason } : {}),
4214
+ ...(result.pendingApproval ? { pendingApproval: true } : {}),
4215
+ });
3603
4216
  });
3604
4217
 
3605
4218
  post("/mesh/api/probe", async (req, res) => {
@@ -3940,5 +4553,5 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
3940
4553
  };
3941
4554
  ctx.effect(() => ctx.webServer.registerUpgrade({ path: "/mesh/api/ssh/ws", handler: sshUpgrade }));
3942
4555
 
3943
- log("UI 接口已挂载: /mesh/api/state|diagnostics|update|refresh|secret|send|probe|web-url|web-panel|ssh");
4556
+ log("UI 接口已挂载: /mesh/api/state|diagnostics|update|upgrade|upgrade/restart|upgrade/reload|refresh|secret|send|probe|web-url|web-panel|ssh");
3944
4557
  }