dsh-plugin-mesh 0.5.0 → 0.5.2

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
@@ -27,6 +27,14 @@ import { brandString } from "@deepseek-ai/dsh-brand";
27
27
  import { MeshDiscovery, preferredAddress, lanIPv4Addresses, macForAddress, orderedEndpoints } from "./discovery.js";
28
28
  import { candidateAddresses, scanForPeers } from "./scan.js";
29
29
  import { machineFingerprint } from "./identity.js";
30
+ import {
31
+ profileDirFromModuleUrl,
32
+ isProfileDir,
33
+ chooseMeshRoot,
34
+ receiveWorkspaceDir,
35
+ legacyMeshDir,
36
+ copyLegacyFiles,
37
+ } from "./layout.js";
30
38
  import {
31
39
  startCapabilities,
32
40
  currentCapabilities,
@@ -51,7 +59,7 @@ import { tailnetFetch, tailnetOrigin } from "./tsnet/bridge.js";
51
59
  export const name = "dsh-plugin-mesh";
52
60
  export const inject = ["tools", "webServer"];
53
61
 
54
- const VERSION = "0.5.0";
62
+ const VERSION = "0.5.2";
55
63
  const RULE_ID = "mesh-inbound";
56
64
  const RULE_KIND = "mesh";
57
65
  const MAX_BODY = 256 * 1024;
@@ -87,6 +95,18 @@ let activeDiscovery = null;
87
95
  */
88
96
  const pendingByConv = new Map();
89
97
 
98
+ /**
99
+ * 宿主替用户派发过的 thread → 时间戳。
100
+ *
101
+ * 用途:会话里的 agent 看到「我派发了一个任务」,很可能自己再调一次 mesh_run,
102
+ * 对端就会收到两份。这里记一笔,mesh_run 命中同一 thread 且调用方正是被绑定的
103
+ * 那个会话时直接拒绝。
104
+ *
105
+ * 放模块级而不是 applyUnsafe 内部:`/mesh/api/send` 与 `mesh_run` 分属两个
106
+ * 注册函数,只有模块级才同时可见(踩过:声明在里面 → "hostDispatched is not defined")。
107
+ */
108
+ const hostDispatched = new Map();
109
+
90
110
  /**
91
111
  * 单个会话的排队上限。超过就**背压**:明确回一个"忙",而不是无脑排队。
92
112
  *
@@ -194,15 +214,56 @@ export const Config = z.object({
194
214
  * 突发建会话已由排队锁接管,冷却现在只是一层安全网,不需要那么长。
195
215
  */
196
216
  threadCooldownMs: z.natural().default(5000),
197
- /** 单条任务正文短于这个长度就只入箱不唤醒(挡掉 ping/ack 这类寒暄) */
198
- minTaskChars: z.natural().default(24),
217
+ /**
218
+ * 单条任务正文短于这个长度就只入箱不唤醒(挡掉 ping/ack 这类寒暄)。
219
+ *
220
+ * 默认从 24 降到 8:中文的信息密度远高于英文,24 字对中文太苛刻 ——
221
+ * 「查看你的硬件配置,已经网络环境」只有 15 字,是一条真实任务,却被静默
222
+ * 吞成 noted-only(真机反馈)。真正该挡的寒暄由 NOTICE_ONLY 正则负责,
223
+ * 长度闸门只留一个很小的地板值。
224
+ */
225
+ minTaskChars: z.natural().default(8),
199
226
  });
200
227
 
201
228
  // ───────────────────────── 本地状态(配对码) ─────────────────────────
202
229
 
230
+ /** 旧版共享目录:<DSH_HOME>/mesh。只用于迁移,不再写新状态。 */
231
+ function legacyRoot() {
232
+ return legacyMeshDir({ dshHome: process.env.DSH_HOME, homeDir: homedir() });
233
+ }
234
+
235
+ function migrateLegacyState(root) {
236
+ copyLegacyFiles(root, legacyRoot());
237
+ }
238
+
239
+ let cachedMeshRoot = "";
240
+
241
+ /** mesh 根目录:<profile>/mesh。 */
242
+ function meshRoot() {
243
+ if (cachedMeshRoot) return cachedMeshRoot;
244
+ const profileDir = currentProfileDir();
245
+ let root = chooseMeshRoot({
246
+ profileDir,
247
+ dshHome: process.env.DSH_HOME,
248
+ homeDir: homedir(),
249
+ });
250
+ try {
251
+ mkdirSync(root, { recursive: true, mode: 0o700 });
252
+ } catch {
253
+ root = chooseMeshRoot({ dshHome: process.env.DSH_HOME, homeDir: homedir() });
254
+ try {
255
+ mkdirSync(root, { recursive: true, mode: 0o700 });
256
+ } catch {
257
+ /* 交给后续读写报错 */
258
+ }
259
+ }
260
+ cachedMeshRoot = root;
261
+ migrateLegacyState(root);
262
+ return root;
263
+ }
264
+
203
265
  function stateDir() {
204
- const base = process.env.DSH_HOME || join(homedir(), ".dsh");
205
- return join(base, "mesh");
266
+ return meshRoot();
206
267
  }
207
268
 
208
269
  function statePath() {
@@ -214,18 +275,25 @@ function threadsPath() {
214
275
  }
215
276
 
216
277
  /**
217
- * 本插件所在的 profile 名,从真实加载路径推导。
278
+ * 本插件所在的 profile 名与根目录。
218
279
  *
219
- * 插件被加载时路径形如:
220
- * <profileDir>/node_modules/dsh-plugin-mesh/lib/index.js
221
- * 往上三层正好是 profile 目录,取 basename 即 profile 名。
280
+ * 开发目录(不是 DSH profile)会被 isProfileDir 拒绝,退回到 DSH_PROFILE /
281
+ * DSH_HOME 推导,避免把 mesh/ 建到仓库根目录。
222
282
  */
283
+ function currentProfileDir() {
284
+ const fromPath = profileDirFromModuleUrl(import.meta.url);
285
+ if (fromPath && isProfileDir(fromPath)) return fromPath;
286
+ const profile = String(process.env.DSH_PROFILE ?? "").trim();
287
+ if (!profile) return "";
288
+ const home = process.env.DSH_HOME || join(homedir(), ".dsh");
289
+ const fromEnv = join(home, "profiles", profile);
290
+ return isProfileDir(fromEnv) ? fromEnv : "";
291
+ }
292
+
223
293
  function currentProfileName() {
224
- try {
225
- return basename(fileURLToPath(new URL("../../..", import.meta.url))) || "default";
226
- } catch {
227
- return "default";
228
- }
294
+ const dir = currentProfileDir();
295
+ if (dir) return basename(dir) || "default";
296
+ return String(process.env.DSH_PROFILE ?? "").trim() || "default";
229
297
  }
230
298
 
231
299
  /**
@@ -602,7 +670,7 @@ function applyUnsafe(ctx, config) {
602
670
  const waker = { ready: false, ctx: undefined };
603
671
 
604
672
  // 1) 先起对端 HTTP(拿到真实端口),再开始发现
605
- startPeerServer(ctx, { config, discovery, inbound, log, warn, waker, threadState, capFor, capOverrides, throttled, onHistoryChange: scheduleHistorySave })
673
+ startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn, waker, threadState, capFor, capOverrides, throttled, onHistoryChange: scheduleHistorySave })
606
674
  .then(async (port) => {
607
675
  discovery.setPort(port);
608
676
 
@@ -707,10 +775,10 @@ function applyUnsafe(ctx, config) {
707
775
  setupInbound(ctx, config, log, warn, waker);
708
776
 
709
777
  // 3) agent 工具
710
- registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState, onHistoryChange: scheduleHistorySave });
778
+ registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState, hostDispatched, onHistoryChange: scheduleHistorySave });
711
779
 
712
780
  // 4) UI 接口
713
- registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, capFor, capOverrides, throttled, waker, onHistoryChange: scheduleHistorySave });
781
+ registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, hostDispatched, capFor, capOverrides, throttled, waker, onHistoryChange: scheduleHistorySave });
714
782
 
715
783
  ctx.effect(() => () => {
716
784
  discovery.stop();
@@ -828,8 +896,8 @@ async function wakeAgent(waker, config, task, warn = () => {}) {
828
896
  warn(`本机 DSH 的 agentPresets 没有 standingKeyFor(版本较旧?),已跳过;继续尝试建会话`);
829
897
  }
830
898
 
831
- const workspace = await c.workspaceRegistry.create(resolveWorkspace(config));
832
899
  const sessionId = brandString(`mesh-${randomUUID()}`);
900
+ const workspace = await c.workspaceRegistry.create(resolveWorkspace(config, sessionId));
833
901
  const selection = c.agentDefaultModel.currentSelection();
834
902
 
835
903
  const handle = await c.agents.create({
@@ -884,6 +952,72 @@ async function wakeAgent(waker, config, task, warn = () => {}) {
884
952
  return sessionId;
885
953
  }
886
954
 
955
+ /**
956
+ * 只建一个**空**会话(不注入任何提示、不启动一轮 agent),供「派发时预建会话」用。
957
+ *
958
+ * 为什么要预建:页面手动派发时,回执需要一个已存在的会话可以注入。只靠 UI 传
959
+ * 当前会话 id 不够 —— 面板拿不到 selection 时那个 id 是空的,绑定就被整段跳过,
960
+ * 回执只能新开一个会话(真机反馈「mac 没有预先生成会话」)。
961
+ *
962
+ * 为什么不直接复用 wakeAgent:那会在派发时就注入一条提示、立刻烧一轮 token。
963
+ * 预建只需要「会话存在且可注入」,等回执真的回来了再让 agent 开跑。
964
+ */
965
+ async function createIdleSession(waker, config, task, warn = () => {}, announce = null) {
966
+ const c = waker.ctx;
967
+ const preset = await c.agentPresets.resolve(config.agentPreset);
968
+ if (typeof c.agentPresets.standingKeyFor === "function") {
969
+ await c.agentPresets.standingKeyFor(preset.id);
970
+ }
971
+ const sessionId = brandString(`mesh-${randomUUID()}`);
972
+ const workspace = await c.workspaceRegistry.create(resolveWorkspace(config, sessionId));
973
+ const selection = c.agentDefaultModel.currentSelection();
974
+ const handle = await c.agents.create({
975
+ sessionId,
976
+ meta: { cwd: workspace.path, agentPreset: preset.id },
977
+ agentOptions: {
978
+ provider: selection.provider,
979
+ model: selection.model,
980
+ ...(selection.reasoningEffort === undefined ? {} : { reasoningEffort: selection.reasoningEffort }),
981
+ },
982
+ setup: async (agentCtx) => {
983
+ await c.agentPresets.mount(agentCtx, preset.id);
984
+ },
985
+ });
986
+ let attached = false;
987
+ try {
988
+ await workspace.attachSession(sessionId);
989
+ attached = true;
990
+ c.permissionPresets.set(handle.agent.session, permissionPresetFor(config, task));
991
+ c.sessionTitle.rename(handle.agent.session, `Mesh 派发 ${String(task.thread || task.id).slice(0, 16)} → ${task.toMachine || "对端"}`);
992
+ if (announce?.text) {
993
+ // 消息必须可见,而可见的文字 agent 也读得到 —— DSH 的用户气泡是纯文本
994
+ // 渲染(white-space: pre-wrap),没有 markdown/注释可以藏字;而
995
+ // session.append 无论在建会话后还是 setup 里写,都会让 agent loop 跑起来
996
+ // (setup 里写甚至会让 create 直接失败)。
997
+ // 所以调用方在正文末尾拼一行极短说明:已派发、等待回执、无需在本机执行。
998
+ // 少了这行,agent 会把原文当成本地任务直接执行(真机反馈)。
999
+ handle.agent.followup(
1000
+ createUserMessage({ content: [{ type: "text", text: announce.text }], source: { kind: "user" } }),
1001
+ );
1002
+ }
1003
+ } catch (err) {
1004
+ if (attached) {
1005
+ try {
1006
+ await workspace.detachSession(sessionId);
1007
+ } catch {
1008
+ /* 回滚失败不覆盖原始错误 */
1009
+ }
1010
+ }
1011
+ try {
1012
+ await handle.dispose();
1013
+ } catch {
1014
+ /* 同上 */
1015
+ }
1016
+ throw err;
1017
+ }
1018
+ return sessionId;
1019
+ }
1020
+
887
1021
  /**
888
1022
  * 把一条入站任务喂进一个**已存在但已结束**的会话,而不是新建一个。
889
1023
  *
@@ -967,9 +1101,16 @@ async function wakeAgentOrResume(waker, config, task, resumeSessionId, warn = ()
967
1101
  return wakeAgent(waker, config, task, warn);
968
1102
  }
969
1103
 
970
- function resolveWorkspace(config) {
1104
+ function resolveWorkspace(config, sessionId) {
971
1105
  if (config.workspaceRoot && isAbsolute(config.workspaceRoot)) return config.workspaceRoot;
972
- return resolve(homedir());
1106
+ // 每个 profile 一个 mesh-receive-task 工作区:既按实例隔离,又不会按会话爆炸。
1107
+ const dir = receiveWorkspaceDir(meshRoot());
1108
+ try {
1109
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
1110
+ } catch {
1111
+ /* 交给 workspaceRegistry.create 报错 */
1112
+ }
1113
+ return dir;
973
1114
  }
974
1115
 
975
1116
 
@@ -1053,7 +1194,18 @@ function classifyInbound(task, threadState, config, now, capFor, { canInject = f
1053
1194
  * 收到对端任务:会话键命中且会话仍活跃就复用,否则新建,
1054
1195
  * 最后才新建会话。复用是为了避免"每条消息都从零重新探索上下文"。
1055
1196
  */
1056
- function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled, onHistoryChange) {
1197
+ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled, onHistoryChange, outbound) {
1198
+ // ── 这条入站是「回执」还是「新任务」? ──
1199
+ //
1200
+ // 判据:同一台机器 + 同一个 thread 上,我们确实往外派过任务。
1201
+ // 是回执的话,提示词要明确禁止再回派,否则两边会互相回执形成循环
1202
+ // (2026-10-21 手动派发实测:一轮几十条)。
1203
+ if (task?.thread) {
1204
+ const from = String(task.fromMachine || String(task.from || "").split("/")[0] || "");
1205
+ task.isReply = (outbound ?? []).some(
1206
+ (o) => String(o.toMachine || "") === from && String(o.thread || "") === String(task.thread),
1207
+ );
1208
+ }
1057
1209
  const rec = inbound.find((t) => t.id === task.id);
1058
1210
  // 记下"回信地址",与"本机用哪个会话处理"是两件事。对端可以 GET
1059
1211
  // /mesh/v1/tasks 读到它,调试时能看清结果该送回哪里。
@@ -1094,10 +1246,14 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
1094
1246
  // 只有"撞上限"值得提示用户去提高上限;寒暄/冷却/过短都是正常拦截
1095
1247
  if (verdict.kind === "cap") {
1096
1248
  const k = String(task.thread || "").trim();
1097
- const entry = throttled.get(k) ?? { taskIds: [], firstAt: now, lastAt: now, cap: capFor(k) };
1249
+ const entry = throttled.get(k) ?? { taskIds: [], firstAt: now, lastAt: now, cap: capFor(key), key };
1250
+ // The ledger and the cap override are keyed by conversationKey (machine +
1251
+ // thread), not by the bare thread label the UI displays. Remember it so
1252
+ // "/mesh/api/throttle/raise" can write the override under the right key.
1253
+ entry.key = key || entry.key || "";
1098
1254
  entry.taskIds.push(task.id);
1099
1255
  entry.lastAt = now;
1100
- entry.cap = capFor(k);
1256
+ entry.cap = capFor(entry.key || k);
1101
1257
  throttled.set(k, entry);
1102
1258
  warn(`任务 ${task.id} 因限速未唤醒(${verdict.reason});可在 Mesh 页面提高 ${k} 的上限`);
1103
1259
  } else {
@@ -1449,6 +1605,9 @@ async function runScan({ discovery, config, log, warn, signal, reason = "扫描"
1449
1605
  const ports = scanPortList(discovery, config);
1450
1606
  let lanFound = 0;
1451
1607
 
1608
+ if (addresses.length === 0) {
1609
+ warn(`${reason}: 没有可扫描的地址(检查 scanRanges 是否合法 / 网卡是否存在)`);
1610
+ }
1452
1611
  if (addresses.length > 0) {
1453
1612
  log(`${reason}: 探测 ${addresses.length} 个地址的 ${ports.join("/")} 端口…`);
1454
1613
  const started = Date.now();
@@ -1501,8 +1660,15 @@ async function pingKnownPeers({ discovery, config, warn }) {
1501
1660
  // 通道立刻探一次**,让它尽快有个真实状态而不是停在"未探测"。
1502
1661
  const tsnetInterval = Math.max(config.pingIntervalMs, config.tsnetProbeIntervalMs ?? 60000);
1503
1662
  const targets = endpoints.filter((ep) => {
1504
- if (ep.verified === false) return true; // 还没验证过,尽快探一次
1505
1663
  const interval = ep.transport === "tsnet" ? tsnetInterval : config.pingIntervalMs;
1664
+ if (ep.verified === false) {
1665
+ // 首次立刻探一次;失败后按通道节奏重试,并尊重 markEndpoint 记下
1666
+ // 的冷却时间。原来的 `return true` 让未验证端点每个 ping tick 都
1667
+ // 被探一次(默认 10s),完全绕过 tsnetProbeIntervalMs(60s)。
1668
+ if (!ep.lastFailAt) return true;
1669
+ if (Number(ep.downUntil ?? 0) > now) return false;
1670
+ return now - Number(ep.lastFailAt ?? 0) >= interval;
1671
+ }
1506
1672
  return now - Number(ep.lastSeen ?? 0) >= interval;
1507
1673
  });
1508
1674
  if (targets.length === 0) return;
@@ -1555,7 +1721,7 @@ async function peerFetchEndpoint(ep, url, opts = {}) {
1555
1721
 
1556
1722
  // ───────────────────────── 对端 HTTP 服务 ─────────────────────────
1557
1723
 
1558
- function startPeerServer(ctx, { config, discovery, inbound, log, warn, waker, threadState, capFor, capOverrides, throttled, onHistoryChange }) {
1724
+ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn, waker, threadState, capFor, capOverrides, throttled, onHistoryChange }) {
1559
1725
  const send = (res, code, payload) => {
1560
1726
  const body = Buffer.from(JSON.stringify(payload), "utf8");
1561
1727
  res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Content-Length": body.length });
@@ -1626,7 +1792,7 @@ function startPeerServer(ctx, { config, discovery, inbound, log, warn, waker, th
1626
1792
  log(`收到任务 ${task.id} 来自 ${task.from}${duplicate ? "(重复,忽略)" : ""}`);
1627
1793
  if (!duplicate) {
1628
1794
  try {
1629
- handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled, onHistoryChange);
1795
+ handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled, onHistoryChange, outbound);
1630
1796
  } catch (err) {
1631
1797
  warn(`处理入站任务异常: ${err?.message ?? err}`);
1632
1798
  }
@@ -1685,7 +1851,7 @@ function readJson(req) {
1685
1851
 
1686
1852
  // ───────────────────────── agent 工具 ─────────────────────────
1687
1853
 
1688
- function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState, onHistoryChange }) {
1854
+ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState, hostDispatched, onHistoryChange }) {
1689
1855
  const text = (v) => [{ type: "text", text: v }];
1690
1856
 
1691
1857
  ctx.tools.register(
@@ -1806,6 +1972,16 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
1806
1972
  originSession: exec?.agent?.session?.id ? String(exec.agent.session.id) : "",
1807
1973
  };
1808
1974
 
1975
+ // 宿主已经替用户派发过这个 thread:同一个会话再调一次就是对端收两份。
1976
+ // 真机上 agent 看到会话里的「派发」很容易这么做,所以在入口挡住。
1977
+ if (payload.thread && hostDispatched.has(payload.thread)) {
1978
+ const bound = threadState.get(conversationKey({ fromMachine: target.machine, thread: payload.thread }))?.sessionId;
1979
+ const here = exec?.agent?.session?.id ? String(exec.agent.session.id) : "";
1980
+ if (bound && here && bound === here) {
1981
+ return "这条任务已经由宿主发出去(会话里已记录),不需要再调用 mesh_run。请直接告诉用户「等待回执」。";
1982
+ }
1983
+ }
1984
+
1809
1985
  // Replies arrive from the target machine, so bind its inbound key
1810
1986
  // before HTTP: the peer may reply before this request completes.
1811
1987
  const replyKey = conversationKey({ fromMachine: target.machine, thread: payload.thread });
@@ -1872,7 +2048,7 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
1872
2048
 
1873
2049
  // ───────────────────────── UI 接口(本地回环) ─────────────────────────
1874
2050
 
1875
- function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, capFor, capOverrides, throttled, waker, onHistoryChange }) {
2051
+ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, hostDispatched, capFor, capOverrides, throttled, waker, onHistoryChange }) {
1876
2052
  const send = (res, code, payload) => {
1877
2053
  const body = Buffer.from(JSON.stringify(payload), "utf8");
1878
2054
  res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Content-Length": body.length });
@@ -1895,6 +2071,21 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
1895
2071
  }),
1896
2072
  );
1897
2073
 
2074
+ /**
2075
+ * POST-only wrapper for state-changing routes.
2076
+ *
2077
+ * Without this a GET (an <img>, a link prefetch, or any local process) can
2078
+ * trigger mutations. "/mesh/api/pairing" was the worst: readJson() returns
2079
+ * null for a body-less GET, `body?.enabled === true` becomes false, and the
2080
+ * empty result was persisted as "pairing disabled" -- a fail-open.
2081
+ */
2082
+ const post = (path, handler) =>
2083
+ route(path, (req, res) =>
2084
+ req.method === "POST"
2085
+ ? handler(req, res)
2086
+ : send(res, 405, { ok: false, error: `method ${req.method} not allowed; use POST` }),
2087
+ );
2088
+
1898
2089
  /** 返回 { peer } 或 { error },避免撞名时静默挑错机器 */
1899
2090
  const findPeer = (name) => {
1900
2091
  const matches = findPeersByName(discovery, name);
@@ -2010,7 +2201,8 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2010
2201
  cap: v.cap,
2011
2202
  defaultCap: config.maxWakesPerThread ?? 0,
2012
2203
  windowMs: config.threadWindowMs ?? 3600000,
2013
- overridden: capOverrides.has(thread),
2204
+ key: v.key || thread,
2205
+ overridden: capOverrides.has(v.key || thread),
2014
2206
  firstAt: new Date(v.firstAt).toISOString(),
2015
2207
  lastAt: new Date(v.lastAt).toISOString(),
2016
2208
  })),
@@ -2025,20 +2217,21 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2025
2217
  * 提高后立刻放行**最近被挡的那一条**(对话的最新一环),其余仍留在收件箱 ——
2026
2218
  * 一次性全部重放会造成一个新的突发,反而失去限速的意义。
2027
2219
  */
2028
- route("/mesh/api/throttle/raise", async (req, res) => {
2220
+ post("/mesh/api/throttle/raise", async (req, res) => {
2029
2221
  const body = await readJson(req);
2030
2222
  const thread = String(body?.thread ?? "").trim();
2031
2223
  if (!thread) return send(res, 400, { ok: false, error: "thread 必填" });
2032
2224
  const entry = throttled.get(thread);
2033
2225
  if (!entry) return send(res, 404, { ok: false, error: `thread "${thread}" 当前没有被限速` });
2034
2226
 
2035
- const current = capFor(thread);
2227
+ const capKey = entry.key || thread;
2228
+ const current = capFor(capKey);
2036
2229
  const requested = Number(body?.cap);
2037
2230
  // 默认在当前基础上翻倍(至少 +10),也可由调用方指定
2038
2231
  const next = Number.isFinite(requested) && requested > current
2039
2232
  ? Math.floor(requested)
2040
2233
  : Math.max(current + 10, current * 2);
2041
- capOverrides.set(thread, next);
2234
+ capOverrides.set(capKey, next);
2042
2235
  // 必须显式传入,否则 saveThreads 会从磁盘读回旧值、把手动提高冲掉
2043
2236
  saveThreads(threadState, capOverrides);
2044
2237
 
@@ -2048,7 +2241,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2048
2241
  throttled.delete(thread);
2049
2242
  if (task) {
2050
2243
  log(`用户将 thread "${thread}" 上限提高到 ${next},放行最新任务 ${lastId}`);
2051
- handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled, onHistoryChange);
2244
+ handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled, onHistoryChange, outbound);
2052
2245
  } else {
2053
2246
  log(`用户将 thread "${thread}" 上限提高到 ${next}(未找到可重放的任务)`);
2054
2247
  }
@@ -2062,7 +2255,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2062
2255
  });
2063
2256
 
2064
2257
  /** 用户选择"忽略":清掉提示,不改上限。任务仍留在收件箱。 */
2065
- route("/mesh/api/throttle/dismiss", async (req, res) => {
2258
+ post("/mesh/api/throttle/dismiss", async (req, res) => {
2066
2259
  const body = await readJson(req);
2067
2260
  const thread = String(body?.thread ?? "").trim();
2068
2261
  if (!thread) return send(res, 400, { ok: false, error: "thread 必填" });
@@ -2073,7 +2266,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2073
2266
  });
2074
2267
 
2075
2268
  // 首次启动的"起名"接口:存进 state.json,并立刻重新广播
2076
- route("/mesh/api/name", async (req, res) => {
2269
+ post("/mesh/api/name", async (req, res) => {
2077
2270
  const body = await readJson(req);
2078
2271
  let name;
2079
2272
  try {
@@ -2096,12 +2289,12 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2096
2289
  send(res, 200, { ok: true, name, previous });
2097
2290
  });
2098
2291
 
2099
- route("/mesh/api/refresh", (_req, res) => {
2292
+ post("/mesh/api/refresh", (_req, res) => {
2100
2293
  discovery.announceNow();
2101
2294
  send(res, 200, { ok: true });
2102
2295
  });
2103
2296
 
2104
- route("/mesh/api/scan", async (_req, res) => {
2297
+ post("/mesh/api/scan", async (_req, res) => {
2105
2298
  try {
2106
2299
  const result = await runScan({ discovery, config, log, warn, reason: "手动扫描" });
2107
2300
  send(res, 200, { ok: true, ...result, peers: discovery.peers() });
@@ -2121,9 +2314,12 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2121
2314
  * 程序去改它风险太大(YAML 注释会被吃掉)。这也是 tsnet 开关一直在用的做法。
2122
2315
  * 配置里写死 requirePairing: true 的情况仍然优先(部署方能强制)。
2123
2316
  */
2124
- route("/mesh/api/pairing", async (req, res) => {
2317
+ post("/mesh/api/pairing", async (req, res) => {
2125
2318
  const body = await readJson(req);
2126
- const want = body?.enabled === true;
2319
+ if (typeof body?.enabled !== "boolean") {
2320
+ return send(res, 400, { ok: false, error: "enabled 必须是布尔值" });
2321
+ }
2322
+ const want = body.enabled;
2127
2323
  if (pairingPinned(config)) {
2128
2324
  return send(res, 409, {
2129
2325
  ok: false,
@@ -2135,7 +2331,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2135
2331
  return send(res, 200, { ok: true, requirePairing: want });
2136
2332
  });
2137
2333
 
2138
- route("/mesh/api/secret", async (req, res) => {
2334
+ post("/mesh/api/secret", async (req, res) => {
2139
2335
  const body = await readJson(req);
2140
2336
  const secret = String(body?.secret ?? "").trim();
2141
2337
  if (secret.length < 16) return send(res, 400, { ok: false, error: "配对码至少 16 个字符" });
@@ -2159,7 +2355,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2159
2355
  * 授权码存进 state.json(0600),所以**只需要输入一次**,重启不用再填。
2160
2356
  * 授权码传空串表示"不改动已保存的值",避免界面回显后又被空值覆盖。
2161
2357
  */
2162
- route("/mesh/api/tsnet/config", async (req, res) => {
2358
+ post("/mesh/api/tsnet/config", async (req, res) => {
2163
2359
  const body = await readJson(req);
2164
2360
  const patch = {};
2165
2361
  if (typeof body?.authKey === "string" && body.authKey.trim()) patch.tsnetAuthKey = body.authKey.trim();
@@ -2184,7 +2380,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2184
2380
  });
2185
2381
 
2186
2382
  /** 启动(或按最新配置重启)tailnet 节点。 */
2187
- route("/mesh/api/tsnet/start", async (_req, res) => {
2383
+ post("/mesh/api/tsnet/start", async (_req, res) => {
2188
2384
  if (tailnetNode) {
2189
2385
  const old = tailnetNode;
2190
2386
  tailnetNode = null;
@@ -2210,7 +2406,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2210
2406
  * 进程仍在跑、rendezvous 也没清)。不传参数即按归属判断:自己拉起的关掉,
2211
2407
  * 复用别人的只注销自己的 forward。
2212
2408
  */
2213
- route("/mesh/api/tsnet/stop", async (_req, res) => {
2409
+ post("/mesh/api/tsnet/stop", async (_req, res) => {
2214
2410
  const node = tailnetNode;
2215
2411
  tailnetNode = null;
2216
2412
  if (node) await node.stop().catch(() => {});
@@ -2218,7 +2414,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2218
2414
  });
2219
2415
 
2220
2416
  /** 清掉节点身份重新登录(授权码失效 / 换账号时用)。 */
2221
- route("/mesh/api/tsnet/relogin", async (_req, res) => {
2417
+ post("/mesh/api/tsnet/relogin", async (_req, res) => {
2222
2418
  if (!tailnetNode) return send(res, 409, { ok: false, error: "互联网组网未启动" });
2223
2419
  try {
2224
2420
  await tailnetNode.relogin();
@@ -2230,7 +2426,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2230
2426
  });
2231
2427
 
2232
2428
  /** 重新下载 sidecar 二进制(下载损坏或换平台时用)。 */
2233
- route("/mesh/api/tsnet/reinstall", async (_req, res) => {
2429
+ post("/mesh/api/tsnet/reinstall", async (_req, res) => {
2234
2430
  if (!tailnetNode) return send(res, 409, { ok: false, error: "互联网组网未启动" });
2235
2431
  try {
2236
2432
  const r = await tailnetNode.reinstallBinary();
@@ -2241,7 +2437,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2241
2437
  });
2242
2438
 
2243
2439
  /** 只扫 tailnet,不扫局域网。 */
2244
- route("/mesh/api/tsnet/scan", async (_req, res) => {
2440
+ post("/mesh/api/tsnet/scan", async (_req, res) => {
2245
2441
  const before = new Set(discovery.peers().map((p) => p.id));
2246
2442
  const result = await scanTailnet({
2247
2443
  discovery,
@@ -2258,7 +2454,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2258
2454
  });
2259
2455
  });
2260
2456
 
2261
- route("/mesh/api/send", async (req, res) => {
2457
+ post("/mesh/api/send", async (req, res) => {
2262
2458
  const body = await readJson(req);
2263
2459
  const peerName = String(body?.peer ?? "").trim();
2264
2460
  const task = String(body?.task ?? "").trim();
@@ -2268,6 +2464,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2268
2464
  const target = found.peer;
2269
2465
 
2270
2466
  const id = `t-${randomBytes(6).toString("hex")}`;
2467
+ let createdSessionId = "";
2271
2468
  const payload = {
2272
2469
  id,
2273
2470
  from: `${machineOf(discovery)}/${safeUser()}`,
@@ -2277,7 +2474,63 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2277
2474
  noWake: body?.noWake === true,
2278
2475
  newSession: body?.newSession === true,
2279
2476
  workspace: body?.workspace ? String(body.workspace) : "",
2477
+ // 页面手动派发时,UI 会带上「当前会话 id」,回执就能落回那个会话。
2478
+ // 不带的话宿主没有绑定可登记,对端回传只能新开一个 mesh-* 会话 ——
2479
+ // 这正是「手动派发后回执自己长出一个新会话」的原因。
2480
+ originSession: body?.originSession ? String(body.originSession) : "",
2280
2481
  };
2482
+
2483
+ // 页面派发如果没填 thread,就自己生成一个。
2484
+ //
2485
+ // 「线程标识(可选)」留空时,payload.thread 是空串 → 没有绑定键 →
2486
+ // 对端按提示词里的兜底(thread 填任务 id)回执 → 我们这边算出的键完全对不上,
2487
+ // 只能新开会话。真机复测就是这样:回执的 thread 是 t-xxxx(对方任务 id)。
2488
+ if (!payload.thread) {
2489
+ payload.thread = `ui-${id}`;
2490
+ }
2491
+
2492
+ // 页面派发时**预建一个会话**,回执才有地方可去。
2493
+ //
2494
+ // 只靠 UI 传当前会话不够:Mesh 面板拿不到 selection 时 sessionId 是空的,
2495
+ // 绑定整段被跳过,回执就只能新开会话(真机反馈「mac 没有预先生成会话」)。
2496
+ // 这里在宿主侧兜底:还没绑定、但有 thread、且唤醒能力可用 → 先建一个空会话。
2497
+ if (!payload.originSession && payload.thread && waker?.ready) {
2498
+ try {
2499
+ payload.originSession = await createIdleSession(
2500
+ waker,
2501
+ config,
2502
+ { id, from: payload.from, thread: payload.thread, toMachine: target.machine, transport: target.transport },
2503
+ warn,
2504
+ // 格式(用户指定):第一行「向 X 发送的消息」→ 原文 → 末行「等待 X 回复」。
2505
+ // 末行同时承担「别在本机执行」的职责:只写「等待回复」是状态描述,
2506
+ // agent 仍会把上面的原文当任务执行,必须让它明确知道别动手。
2507
+ { text: `向 ${target.machine} 发送的消息 如下:\n${task}\n———\n[Mesh 已派发 → ${target.machine}/${id}] 现在什么都不用做:不要调用任何工具、不要回派,回一句「等待回执」即可。` },
2508
+ );
2509
+ createdSessionId = payload.originSession;
2510
+ } catch (err) {
2511
+ warn(`预建会话失败(回执将新建会话):${err?.message ?? err}`);
2512
+ }
2513
+ }
2514
+
2515
+ // 与 mesh_run 相同的登记:必须在 HTTP **之前**绑定,因为对端可能先回执。
2516
+ const replyKey = conversationKey({ fromMachine: target.machine, thread: payload.thread });
2517
+ if (replyKey && payload.originSession) {
2518
+ if (pendingByConv.has(replyKey)) {
2519
+ return send(res, 409, { ok: false, error: "此 thread 正在建立会话,请稍后重试" });
2520
+ }
2521
+ const previous = threadState.get(replyKey);
2522
+ if (previous?.sessionId && previous.sessionId !== payload.originSession) {
2523
+ return send(res, 409, { ok: false, error: "该 thread 已绑定另一会话,请换一个 thread" });
2524
+ }
2525
+ threadState.set(replyKey, { ...previous, wakesAt: previous?.wakesAt ?? [], sessionId: payload.originSession });
2526
+ saveThreads(threadState);
2527
+ hostDispatched.set(payload.thread, Date.now());
2528
+ // 顺手清理过期条目,别让它无限增长
2529
+ for (const [t, at] of hostDispatched) {
2530
+ if (Date.now() - at > 3600_000) hostDispatched.delete(t);
2531
+ }
2532
+ }
2533
+
2281
2534
  try {
2282
2535
  const r = await peerFetch(target, "/mesh/v1/task", {
2283
2536
  method: "POST",
@@ -2289,13 +2542,13 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2289
2542
  outbound.push({ ...payload, toMachine: target.machine, at: new Date().toISOString(), ok: r.ok, status: r.status });
2290
2543
  onHistoryChange?.();
2291
2544
  if (outbound.length > MAX_HISTORY) outbound.shift();
2292
- return send(res, r.ok ? 200 : 502, { ok: r.ok, id, error: rb?.error });
2545
+ return send(res, r.ok ? 200 : 502, { ok: r.ok, id, sessionId: payload.originSession || "", error: rb?.error });
2293
2546
  } catch (err) {
2294
2547
  return send(res, 502, { ok: false, error: String(err?.message ?? err) });
2295
2548
  }
2296
2549
  });
2297
2550
 
2298
- route("/mesh/api/probe", async (req, res) => {
2551
+ post("/mesh/api/probe", async (req, res) => {
2299
2552
  const body = await readJson(req);
2300
2553
  const found = findPeer(String(body?.peer ?? "").trim());
2301
2554
  if (found.error) return send(res, 404, { ok: false, error: found.error });