dsh-plugin-mesh 0.5.0 → 0.5.1
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/README.md +3 -2
- package/client/client.js +6410 -893
- package/cordis.patch.yml +3 -2
- package/lib/_rehearsal-peer.mjs +2 -1
- package/lib/_selftest-capabilities.mjs +3 -1
- package/lib/_selftest-client.mjs +6 -389
- package/lib/_selftest-layout.mjs +112 -0
- package/lib/_selftest-prompt.mjs +67 -1
- package/lib/_selftest-reply-route.mjs +12 -1
- package/lib/_selftest-workbench.mjs +728 -0
- package/lib/discovery.js +33 -3
- package/lib/index.js +246 -27
- package/lib/layout.js +128 -0
- package/lib/persist.js +4 -0
- package/lib/prompt.js +25 -7
- package/package.json +4 -3
- package/scripts/_selftest-release-plan.mjs +33 -2
- package/scripts/release-plan.mjs +19 -1
package/lib/discovery.js
CHANGED
|
@@ -22,6 +22,35 @@ export const MESH_GROUP = "239.255.42.99";
|
|
|
22
22
|
export const MESH_PORT = 45892;
|
|
23
23
|
export const APP_TAG = "dsh-mesh";
|
|
24
24
|
|
|
25
|
+
/** 带横线的 UUID 形态:opencode-mesh 冒名时用的 id 形状,dsh-mesh 自己从不产出。 */
|
|
26
|
+
const UUID_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* 这份自述记录*是不是*一个 dsh-mesh 对端。
|
|
30
|
+
*
|
|
31
|
+
* 为什么需要它:`app: "dsh-mesh"` 只是对方自报的一个字符串,不构成身份证明。
|
|
32
|
+
* 2026-10-21 实测到一台装在同机的 OpenCode.app 在 45918 上照抄了
|
|
33
|
+
* `/mesh/v1/health` 的形状,自报 `app: "dsh-mesh"`、`proto: "opencode-mesh"`、
|
|
34
|
+
* `version: "0.1.0"`、id 是带横线的 UUID、没有 capabilities —— 旧准入只查
|
|
35
|
+
* `app` 和 `id`,于是它被当成正经对端收进注册表,还进了快照。
|
|
36
|
+
*
|
|
37
|
+
* 三条判据都取「字段存在才校验」的宽容写法:`v` / `proto` 只有 live 记录里有
|
|
38
|
+
* (persist.js 的快照不存这两个字段),硬要求它们会把 restore 路径整条打死。
|
|
39
|
+
* 真正兜底的是 id 形态 —— `resolveInstanceId()` 用同一个正则校验自己,
|
|
40
|
+
* 所以同血统的对端不可能产出非 16 位十六进制的 id。
|
|
41
|
+
*/
|
|
42
|
+
export function looksLikeDshPeer(record) {
|
|
43
|
+
if (!record || record.app !== APP_TAG || !record.id) return false;
|
|
44
|
+
if (record.v !== undefined && record.v !== 2) return false;
|
|
45
|
+
if (record.proto !== undefined && record.proto !== "dsh-mesh") return false;
|
|
46
|
+
// 已经落盘的老快照里没有 v/proto(见 persist.js 的字段表),那条路径上只剩
|
|
47
|
+
// id 形态可判:dsh-mesh 自己用 randomBytes(8).toString("hex") 生成 id,
|
|
48
|
+
// 同血统的对端不可能产出带横线的 UUID。这里刻意只挡 UUID 形态,而不要求
|
|
49
|
+
// "必须是 16 位十六进制" —— 后者会误伤测试夹具和用户手填的旧 id。
|
|
50
|
+
if (UUID_ID_RE.test(String(record.id))) return false;
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
|
|
25
54
|
/** 「上次见过」缓存的保留期与条数上限:地址用不了那么久,也不该无限长。 */
|
|
26
55
|
const KNOWN_TTL_MS = 30 * 24 * 3600 * 1000;
|
|
27
56
|
const KNOWN_MAX = 200;
|
|
@@ -513,7 +542,7 @@ export class MeshDiscovery extends EventEmitter {
|
|
|
513
542
|
* @returns 是否造成可见变化
|
|
514
543
|
*/
|
|
515
544
|
note(record, sourceAddress, meta = {}) {
|
|
516
|
-
if (!record || record.
|
|
545
|
+
if (!looksLikeDshPeer(record) || record.id === this.#id) return false;
|
|
517
546
|
return this.#upsert(record, { address: sourceAddress ?? record.host ?? "?", ...meta });
|
|
518
547
|
}
|
|
519
548
|
|
|
@@ -535,7 +564,8 @@ export class MeshDiscovery extends EventEmitter {
|
|
|
535
564
|
const cutoff = now - KNOWN_TTL_MS;
|
|
536
565
|
for (const item of snapshot ?? []) {
|
|
537
566
|
const msg = item?.record;
|
|
538
|
-
|
|
567
|
+
// 快照同样要过准入:幽灵 peer 一旦落盘,会以离线行的形态躺满 KNOWN_TTL_MS。
|
|
568
|
+
if (!looksLikeDshPeer(msg) || msg.id === this.#id) continue;
|
|
539
569
|
const peerId = String(msg.id);
|
|
540
570
|
// 现网已经发现的,以现网为准,不写缓存
|
|
541
571
|
if (this.#peers.has(peerId)) continue;
|
|
@@ -594,7 +624,7 @@ export class MeshDiscovery extends EventEmitter {
|
|
|
594
624
|
* (verified=false),局域网一断就能直接拿去探,不必重新发现。
|
|
595
625
|
*/
|
|
596
626
|
noteTailnetCandidate(record, address, port) {
|
|
597
|
-
if (!record || record.
|
|
627
|
+
if (!looksLikeDshPeer(record) || record.id === this.#id) return false;
|
|
598
628
|
return this.#upsert(record, { address, transport: "tsnet", port, probe: false });
|
|
599
629
|
}
|
|
600
630
|
|
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.
|
|
62
|
+
const VERSION = "0.5.1";
|
|
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
|
-
/**
|
|
198
|
-
|
|
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
|
-
|
|
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
|
-
*
|
|
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
|
-
|
|
225
|
-
|
|
226
|
-
|
|
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
|
-
|
|
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 读到它,调试时能看清结果该送回哪里。
|
|
@@ -1555,7 +1707,7 @@ async function peerFetchEndpoint(ep, url, opts = {}) {
|
|
|
1555
1707
|
|
|
1556
1708
|
// ───────────────────────── 对端 HTTP 服务 ─────────────────────────
|
|
1557
1709
|
|
|
1558
|
-
function startPeerServer(ctx, { config, discovery, inbound, log, warn, waker, threadState, capFor, capOverrides, throttled, onHistoryChange }) {
|
|
1710
|
+
function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn, waker, threadState, capFor, capOverrides, throttled, onHistoryChange }) {
|
|
1559
1711
|
const send = (res, code, payload) => {
|
|
1560
1712
|
const body = Buffer.from(JSON.stringify(payload), "utf8");
|
|
1561
1713
|
res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Content-Length": body.length });
|
|
@@ -1626,7 +1778,7 @@ function startPeerServer(ctx, { config, discovery, inbound, log, warn, waker, th
|
|
|
1626
1778
|
log(`收到任务 ${task.id} 来自 ${task.from}${duplicate ? "(重复,忽略)" : ""}`);
|
|
1627
1779
|
if (!duplicate) {
|
|
1628
1780
|
try {
|
|
1629
|
-
handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled, onHistoryChange);
|
|
1781
|
+
handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled, onHistoryChange, outbound);
|
|
1630
1782
|
} catch (err) {
|
|
1631
1783
|
warn(`处理入站任务异常: ${err?.message ?? err}`);
|
|
1632
1784
|
}
|
|
@@ -1685,7 +1837,7 @@ function readJson(req) {
|
|
|
1685
1837
|
|
|
1686
1838
|
// ───────────────────────── agent 工具 ─────────────────────────
|
|
1687
1839
|
|
|
1688
|
-
function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState, onHistoryChange }) {
|
|
1840
|
+
function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState, hostDispatched, onHistoryChange }) {
|
|
1689
1841
|
const text = (v) => [{ type: "text", text: v }];
|
|
1690
1842
|
|
|
1691
1843
|
ctx.tools.register(
|
|
@@ -1806,6 +1958,16 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
|
|
|
1806
1958
|
originSession: exec?.agent?.session?.id ? String(exec.agent.session.id) : "",
|
|
1807
1959
|
};
|
|
1808
1960
|
|
|
1961
|
+
// 宿主已经替用户派发过这个 thread:同一个会话再调一次就是对端收两份。
|
|
1962
|
+
// 真机上 agent 看到会话里的「派发」很容易这么做,所以在入口挡住。
|
|
1963
|
+
if (payload.thread && hostDispatched.has(payload.thread)) {
|
|
1964
|
+
const bound = threadState.get(conversationKey({ fromMachine: target.machine, thread: payload.thread }))?.sessionId;
|
|
1965
|
+
const here = exec?.agent?.session?.id ? String(exec.agent.session.id) : "";
|
|
1966
|
+
if (bound && here && bound === here) {
|
|
1967
|
+
return "这条任务已经由宿主发出去(会话里已记录),不需要再调用 mesh_run。请直接告诉用户「等待回执」。";
|
|
1968
|
+
}
|
|
1969
|
+
}
|
|
1970
|
+
|
|
1809
1971
|
// Replies arrive from the target machine, so bind its inbound key
|
|
1810
1972
|
// before HTTP: the peer may reply before this request completes.
|
|
1811
1973
|
const replyKey = conversationKey({ fromMachine: target.machine, thread: payload.thread });
|
|
@@ -1872,7 +2034,7 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
|
|
|
1872
2034
|
|
|
1873
2035
|
// ───────────────────────── UI 接口(本地回环) ─────────────────────────
|
|
1874
2036
|
|
|
1875
|
-
function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, capFor, capOverrides, throttled, waker, onHistoryChange }) {
|
|
2037
|
+
function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, hostDispatched, capFor, capOverrides, throttled, waker, onHistoryChange }) {
|
|
1876
2038
|
const send = (res, code, payload) => {
|
|
1877
2039
|
const body = Buffer.from(JSON.stringify(payload), "utf8");
|
|
1878
2040
|
res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Content-Length": body.length });
|
|
@@ -2048,7 +2210,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2048
2210
|
throttled.delete(thread);
|
|
2049
2211
|
if (task) {
|
|
2050
2212
|
log(`用户将 thread "${thread}" 上限提高到 ${next},放行最新任务 ${lastId}`);
|
|
2051
|
-
handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled, onHistoryChange);
|
|
2213
|
+
handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled, onHistoryChange, outbound);
|
|
2052
2214
|
} else {
|
|
2053
2215
|
log(`用户将 thread "${thread}" 上限提高到 ${next}(未找到可重放的任务)`);
|
|
2054
2216
|
}
|
|
@@ -2268,6 +2430,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2268
2430
|
const target = found.peer;
|
|
2269
2431
|
|
|
2270
2432
|
const id = `t-${randomBytes(6).toString("hex")}`;
|
|
2433
|
+
let createdSessionId = "";
|
|
2271
2434
|
const payload = {
|
|
2272
2435
|
id,
|
|
2273
2436
|
from: `${machineOf(discovery)}/${safeUser()}`,
|
|
@@ -2277,7 +2440,63 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2277
2440
|
noWake: body?.noWake === true,
|
|
2278
2441
|
newSession: body?.newSession === true,
|
|
2279
2442
|
workspace: body?.workspace ? String(body.workspace) : "",
|
|
2443
|
+
// 页面手动派发时,UI 会带上「当前会话 id」,回执就能落回那个会话。
|
|
2444
|
+
// 不带的话宿主没有绑定可登记,对端回传只能新开一个 mesh-* 会话 ——
|
|
2445
|
+
// 这正是「手动派发后回执自己长出一个新会话」的原因。
|
|
2446
|
+
originSession: body?.originSession ? String(body.originSession) : "",
|
|
2280
2447
|
};
|
|
2448
|
+
|
|
2449
|
+
// 页面派发如果没填 thread,就自己生成一个。
|
|
2450
|
+
//
|
|
2451
|
+
// 「线程标识(可选)」留空时,payload.thread 是空串 → 没有绑定键 →
|
|
2452
|
+
// 对端按提示词里的兜底(thread 填任务 id)回执 → 我们这边算出的键完全对不上,
|
|
2453
|
+
// 只能新开会话。真机复测就是这样:回执的 thread 是 t-xxxx(对方任务 id)。
|
|
2454
|
+
if (!payload.thread) {
|
|
2455
|
+
payload.thread = `ui-${id}`;
|
|
2456
|
+
}
|
|
2457
|
+
|
|
2458
|
+
// 页面派发时**预建一个会话**,回执才有地方可去。
|
|
2459
|
+
//
|
|
2460
|
+
// 只靠 UI 传当前会话不够:Mesh 面板拿不到 selection 时 sessionId 是空的,
|
|
2461
|
+
// 绑定整段被跳过,回执就只能新开会话(真机反馈「mac 没有预先生成会话」)。
|
|
2462
|
+
// 这里在宿主侧兜底:还没绑定、但有 thread、且唤醒能力可用 → 先建一个空会话。
|
|
2463
|
+
if (!payload.originSession && payload.thread && waker?.ready) {
|
|
2464
|
+
try {
|
|
2465
|
+
payload.originSession = await createIdleSession(
|
|
2466
|
+
waker,
|
|
2467
|
+
config,
|
|
2468
|
+
{ id, from: payload.from, thread: payload.thread, toMachine: target.machine, transport: target.transport },
|
|
2469
|
+
warn,
|
|
2470
|
+
// 格式(用户指定):第一行「向 X 发送的消息」→ 原文 → 末行「等待 X 回复」。
|
|
2471
|
+
// 末行同时承担「别在本机执行」的职责:只写「等待回复」是状态描述,
|
|
2472
|
+
// agent 仍会把上面的原文当任务执行,必须让它明确知道别动手。
|
|
2473
|
+
{ text: `向 ${target.machine} 发送的消息 如下:\n${task}\n———\n[Mesh 已派发 → ${target.machine}/${id}] 现在什么都不用做:不要调用任何工具、不要回派,回一句「等待回执」即可。` },
|
|
2474
|
+
);
|
|
2475
|
+
createdSessionId = payload.originSession;
|
|
2476
|
+
} catch (err) {
|
|
2477
|
+
warn(`预建会话失败(回执将新建会话):${err?.message ?? err}`);
|
|
2478
|
+
}
|
|
2479
|
+
}
|
|
2480
|
+
|
|
2481
|
+
// 与 mesh_run 相同的登记:必须在 HTTP **之前**绑定,因为对端可能先回执。
|
|
2482
|
+
const replyKey = conversationKey({ fromMachine: target.machine, thread: payload.thread });
|
|
2483
|
+
if (replyKey && payload.originSession) {
|
|
2484
|
+
if (pendingByConv.has(replyKey)) {
|
|
2485
|
+
return send(res, 409, { ok: false, error: "此 thread 正在建立会话,请稍后重试" });
|
|
2486
|
+
}
|
|
2487
|
+
const previous = threadState.get(replyKey);
|
|
2488
|
+
if (previous?.sessionId && previous.sessionId !== payload.originSession) {
|
|
2489
|
+
return send(res, 409, { ok: false, error: "该 thread 已绑定另一会话,请换一个 thread" });
|
|
2490
|
+
}
|
|
2491
|
+
threadState.set(replyKey, { ...previous, wakesAt: previous?.wakesAt ?? [], sessionId: payload.originSession });
|
|
2492
|
+
saveThreads(threadState);
|
|
2493
|
+
hostDispatched.set(payload.thread, Date.now());
|
|
2494
|
+
// 顺手清理过期条目,别让它无限增长
|
|
2495
|
+
for (const [t, at] of hostDispatched) {
|
|
2496
|
+
if (Date.now() - at > 3600_000) hostDispatched.delete(t);
|
|
2497
|
+
}
|
|
2498
|
+
}
|
|
2499
|
+
|
|
2281
2500
|
try {
|
|
2282
2501
|
const r = await peerFetch(target, "/mesh/v1/task", {
|
|
2283
2502
|
method: "POST",
|
|
@@ -2289,7 +2508,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2289
2508
|
outbound.push({ ...payload, toMachine: target.machine, at: new Date().toISOString(), ok: r.ok, status: r.status });
|
|
2290
2509
|
onHistoryChange?.();
|
|
2291
2510
|
if (outbound.length > MAX_HISTORY) outbound.shift();
|
|
2292
|
-
return send(res, r.ok ? 200 : 502, { ok: r.ok, id, error: rb?.error });
|
|
2511
|
+
return send(res, r.ok ? 200 : 502, { ok: r.ok, id, sessionId: payload.originSession || "", error: rb?.error });
|
|
2293
2512
|
} catch (err) {
|
|
2294
2513
|
return send(res, 502, { ok: false, error: String(err?.message ?? err) });
|
|
2295
2514
|
}
|
package/lib/layout.js
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mesh 目录布局。
|
|
3
|
+
*
|
|
4
|
+
* 每个 DSH profile 根目录下有一个 `mesh/`:
|
|
5
|
+
*
|
|
6
|
+
* <profile>/mesh/
|
|
7
|
+
* state.json 本 profile 的身份、配对码、tsnet 设置
|
|
8
|
+
* threads.json conversationId ↔ 本地 session 绑定
|
|
9
|
+
* sessions/
|
|
10
|
+
* <sessionId>/ 该会话的工作目录(cwd)
|
|
11
|
+
*
|
|
12
|
+
* 为什么按 profile 而不是按 DSH_HOME:同一个 DSH_HOME 下可能跑多个 profile
|
|
13
|
+
* (desktop / meshtest / 不同账号),state.json 里的配对码是信任边界,不能
|
|
14
|
+
* 跨 profile 共享。按 profile 分目录后,每个 profile 有自己的配对码与会话工作区。
|
|
15
|
+
*
|
|
16
|
+
* 例外:tsnet 的 sidecar 仍是整机一个 tailnet 节点,继续放在共享目录,
|
|
17
|
+
* 不在本模块的职责内(见 lib/tsnet/manager.js)。
|
|
18
|
+
*/
|
|
19
|
+
import { basename, join, resolve } from "node:path";
|
|
20
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
21
|
+
import { fileURLToPath } from "node:url";
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 从 import.meta.url 推导 profile 根目录。
|
|
25
|
+
*
|
|
26
|
+
* 插件被 DSH 加载时路径是:
|
|
27
|
+
* <profileDir>/node_modules/dsh-plugin-mesh/lib/index.js
|
|
28
|
+
* 从 lib/index.js 往上三层正好是 profileDir。
|
|
29
|
+
* 开发目录(如 <repo>/lib/index.js)会推到 repo 的上级,由 isProfileDir 再确认。
|
|
30
|
+
*/
|
|
31
|
+
export function profileDirFromModuleUrl(moduleUrl) {
|
|
32
|
+
try {
|
|
33
|
+
const dir = resolve(fileURLToPath(new URL("../../..", moduleUrl)));
|
|
34
|
+
return dir && basename(dir) ? dir : "";
|
|
35
|
+
} catch {
|
|
36
|
+
return "";
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* profile 根目录的判据:package.json 里有 dsh.profile。
|
|
42
|
+
*
|
|
43
|
+
* 不用「目录存在」当判据:开发目录也有一堆 package.json,但那是插件/仓库,
|
|
44
|
+
* 不是 DSH profile。写错位置的后果是把 mesh/ 建到仓库根目录。
|
|
45
|
+
*/
|
|
46
|
+
export function isProfileDir(dir) {
|
|
47
|
+
if (!dir) return false;
|
|
48
|
+
try {
|
|
49
|
+
// Windows 上手工编辑过的 package.json 可能带 BOM;JSON.parse 不认。
|
|
50
|
+
const raw = readFileSync(join(dir, "package.json"), "utf8").replace(/^\uFEFF/, "");
|
|
51
|
+
const pkg = JSON.parse(raw);
|
|
52
|
+
return Boolean(pkg?.dsh?.profile);
|
|
53
|
+
} catch {
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 选择 mesh 根目录。只做路径计算,不创建目录。
|
|
60
|
+
*
|
|
61
|
+
* 优先级:profileDir/mesh > DSH_HOME/mesh > ~/.dsh/mesh。
|
|
62
|
+
*/
|
|
63
|
+
export function chooseMeshRoot({ profileDir = "", dshHome = "", homeDir = "" } = {}) {
|
|
64
|
+
if (profileDir) return join(profileDir, "mesh");
|
|
65
|
+
const base = dshHome || join(homeDir || ".", ".dsh");
|
|
66
|
+
return join(base, "mesh");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** 每个会话的独立工作目录:<meshRoot>/sessions/<safeSessionId>。 */
|
|
70
|
+
export function sessionDirFor(meshRoot, sessionId) {
|
|
71
|
+
return join(meshRoot, "sessions", safeSegment(sessionId));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* 收到的 mesh 任务统一使用的**唯一**工作区(每个 DSH profile 一个)。
|
|
76
|
+
*
|
|
77
|
+
* 为什么不再按 session 分目录:每来一条任务就在 `sessions/<uuid>` 下新开一个
|
|
78
|
+
* 工作区,工作区数量会爆炸(用户原话:「工作区太多了」)。mesh 任务多数是
|
|
79
|
+
* 看一眼、回一句,本来不需要独立目录。
|
|
80
|
+
*
|
|
81
|
+
* 前提是**按 profile 隔离**:路径挂在 <profile>/mesh 下,desktop / web / meshtest
|
|
82
|
+
* 各有各的,互不干扰。
|
|
83
|
+
*
|
|
84
|
+
* 代价:同一 profile 内并发任务共用一个 cwd,文件会互相看见;确实要隔离时
|
|
85
|
+
* 用 task.workspace 指定独立目录(resolveWorkspace 已优先)。
|
|
86
|
+
*/
|
|
87
|
+
export function receiveWorkspaceDir(meshRoot) {
|
|
88
|
+
return join(meshRoot, "mesh-receive-task");
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function safeSegment(id) {
|
|
92
|
+
const s = String(id ?? "").trim();
|
|
93
|
+
return s.replace(/[^a-zA-Z0-9._-]/g, "_").slice(0, 120) || "session";
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** 旧版状态目录:<DSH_HOME>/mesh。只用于迁移,不用于新状态。 */
|
|
97
|
+
export function legacyMeshDir({ dshHome = "", homeDir = "" } = {}) {
|
|
98
|
+
const base = dshHome || join(homeDir || ".", ".dsh");
|
|
99
|
+
return join(base, "mesh");
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** 新状态文件是否已存在(迁移判据)。 */
|
|
103
|
+
export function hasState(meshRoot) {
|
|
104
|
+
return existsSync(join(meshRoot, "state.json"));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* 把旧共享目录里的状态文件复制到新 mesh 根。
|
|
109
|
+
*
|
|
110
|
+
* 只复制不删除;目标已存在或源不存在就跳过,所以幂等、可回退。
|
|
111
|
+
* 返回实际复制的文件名(测试/日志用)。
|
|
112
|
+
*/
|
|
113
|
+
export function copyLegacyFiles(root, legacy, names = ["state.json", "threads.json"]) {
|
|
114
|
+
if (!root || !legacy || resolve(root) === resolve(legacy)) return [];
|
|
115
|
+
const copied = [];
|
|
116
|
+
for (const name of names) {
|
|
117
|
+
const src = join(legacy, name);
|
|
118
|
+
const dst = join(root, name);
|
|
119
|
+
if (existsSync(dst) || !existsSync(src)) continue;
|
|
120
|
+
try {
|
|
121
|
+
writeFileSync(dst, readFileSync(src), { mode: 0o600 });
|
|
122
|
+
copied.push(name);
|
|
123
|
+
} catch {
|
|
124
|
+
/* 迁移失败不阻塞启动;下次启动再试 */
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return copied;
|
|
128
|
+
}
|
package/lib/persist.js
CHANGED
|
@@ -105,6 +105,10 @@ export function toPeerSnapshot(peers) {
|
|
|
105
105
|
user: String(p.user ?? ""),
|
|
106
106
|
profile: String(p.profile ?? ""),
|
|
107
107
|
version: String(p.version ?? ""),
|
|
108
|
+
// 协议版本与 proto 也要落盘:否则 restore() 只剩 id 形态一条判据,
|
|
109
|
+
// 挡不住"自报 app:dsh-mesh 的同协议第三方"(2026-10-21 实测的幽灵 peer)。
|
|
110
|
+
...(Number(p.v) ? { v: Number(p.v) } : {}),
|
|
111
|
+
...(p.proto ? { proto: String(p.proto) } : {}),
|
|
108
112
|
// 设备级 lastSeen 不在 health 记录里,用端点时间还原;这里给 ts 兜底
|
|
109
113
|
ts: Number(p.ts) || 0,
|
|
110
114
|
port: Number(p.port) || 0,
|