dsh-plugin-mesh 0.4.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 +6415 -863
- 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 -337
- package/lib/_selftest-layout.mjs +112 -0
- package/lib/_selftest-persist.mjs +195 -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 +181 -6
- package/lib/index.js +316 -27
- package/lib/layout.js +128 -0
- package/lib/persist.js +153 -0
- package/lib/prompt.js +25 -7
- package/package.json +5 -3
- package/scripts/_selftest-release-plan.mjs +33 -2
- package/scripts/release-plan.mjs +19 -1
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,
|
|
@@ -39,13 +47,19 @@ import {
|
|
|
39
47
|
import { conversationKey, replyTarget } from "./conversation.js";
|
|
40
48
|
import { buildPrompt } from "./prompt.js";
|
|
41
49
|
import { resolvePairing } from "./pairing.js";
|
|
50
|
+
import {
|
|
51
|
+
loadTaskHistory,
|
|
52
|
+
saveTaskHistory,
|
|
53
|
+
loadPeerSnapshot,
|
|
54
|
+
savePeerSnapshot,
|
|
55
|
+
} from "./persist.js";
|
|
42
56
|
import { TsnetNode } from "./tsnet/manager.js";
|
|
43
57
|
import { tailnetFetch, tailnetOrigin } from "./tsnet/bridge.js";
|
|
44
58
|
|
|
45
59
|
export const name = "dsh-plugin-mesh";
|
|
46
60
|
export const inject = ["tools", "webServer"];
|
|
47
61
|
|
|
48
|
-
const VERSION = "0.
|
|
62
|
+
const VERSION = "0.5.1";
|
|
49
63
|
const RULE_ID = "mesh-inbound";
|
|
50
64
|
const RULE_KIND = "mesh";
|
|
51
65
|
const MAX_BODY = 256 * 1024;
|
|
@@ -81,6 +95,18 @@ let activeDiscovery = null;
|
|
|
81
95
|
*/
|
|
82
96
|
const pendingByConv = new Map();
|
|
83
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
|
+
|
|
84
110
|
/**
|
|
85
111
|
* 单个会话的排队上限。超过就**背压**:明确回一个"忙",而不是无脑排队。
|
|
86
112
|
*
|
|
@@ -188,15 +214,56 @@ export const Config = z.object({
|
|
|
188
214
|
* 突发建会话已由排队锁接管,冷却现在只是一层安全网,不需要那么长。
|
|
189
215
|
*/
|
|
190
216
|
threadCooldownMs: z.natural().default(5000),
|
|
191
|
-
/**
|
|
192
|
-
|
|
217
|
+
/**
|
|
218
|
+
* 单条任务正文短于这个长度就只入箱不唤醒(挡掉 ping/ack 这类寒暄)。
|
|
219
|
+
*
|
|
220
|
+
* 默认从 24 降到 8:中文的信息密度远高于英文,24 字对中文太苛刻 ——
|
|
221
|
+
* 「查看你的硬件配置,已经网络环境」只有 15 字,是一条真实任务,却被静默
|
|
222
|
+
* 吞成 noted-only(真机反馈)。真正该挡的寒暄由 NOTICE_ONLY 正则负责,
|
|
223
|
+
* 长度闸门只留一个很小的地板值。
|
|
224
|
+
*/
|
|
225
|
+
minTaskChars: z.natural().default(8),
|
|
193
226
|
});
|
|
194
227
|
|
|
195
228
|
// ───────────────────────── 本地状态(配对码) ─────────────────────────
|
|
196
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
|
+
|
|
197
265
|
function stateDir() {
|
|
198
|
-
|
|
199
|
-
return join(base, "mesh");
|
|
266
|
+
return meshRoot();
|
|
200
267
|
}
|
|
201
268
|
|
|
202
269
|
function statePath() {
|
|
@@ -208,18 +275,25 @@ function threadsPath() {
|
|
|
208
275
|
}
|
|
209
276
|
|
|
210
277
|
/**
|
|
211
|
-
* 本插件所在的 profile
|
|
278
|
+
* 本插件所在的 profile 名与根目录。
|
|
212
279
|
*
|
|
213
|
-
*
|
|
214
|
-
*
|
|
215
|
-
* 往上三层正好是 profile 目录,取 basename 即 profile 名。
|
|
280
|
+
* 开发目录(不是 DSH profile)会被 isProfileDir 拒绝,退回到 DSH_PROFILE /
|
|
281
|
+
* DSH_HOME 推导,避免把 mesh/ 建到仓库根目录。
|
|
216
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
|
+
|
|
217
293
|
function currentProfileName() {
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
return "default";
|
|
222
|
-
}
|
|
294
|
+
const dir = currentProfileDir();
|
|
295
|
+
if (dir) return basename(dir) || "default";
|
|
296
|
+
return String(process.env.DSH_PROFILE ?? "").trim() || "default";
|
|
223
297
|
}
|
|
224
298
|
|
|
225
299
|
/**
|
|
@@ -461,6 +535,30 @@ function applyUnsafe(ctx, config) {
|
|
|
461
535
|
|
|
462
536
|
const inbound = [];
|
|
463
537
|
const outbound = [];
|
|
538
|
+
|
|
539
|
+
// ── 任务记录的持久化 ──
|
|
540
|
+
//
|
|
541
|
+
// 这两个数组原来是纯内存态(上限各 200 条),重启即清空 —— 排查"刚才到底
|
|
542
|
+
// 派发了什么"只能去翻会话记录。启动时捞回上次的记录,之后每次增删延时落盘。
|
|
543
|
+
const restoredHistory = loadTaskHistory(stateDir());
|
|
544
|
+
if (restoredHistory.inbound.length > 0) inbound.push(...restoredHistory.inbound);
|
|
545
|
+
if (restoredHistory.outbound.length > 0) outbound.push(...restoredHistory.outbound);
|
|
546
|
+
if (inbound.length > 0 || outbound.length > 0) {
|
|
547
|
+
log(
|
|
548
|
+
`已恢复重启前的任务记录:收件 ${inbound.length} 条 / 发件 ${outbound.length} 条` +
|
|
549
|
+
(restoredHistory.savedAt ? `(快照 ${new Date(restoredHistory.savedAt).toISOString()})` : ""),
|
|
550
|
+
);
|
|
551
|
+
}
|
|
552
|
+
let historyTimer = null;
|
|
553
|
+
/** 延时落盘:一次密集来包可能连推好几条,没必要每条都写一次磁盘。 */
|
|
554
|
+
const scheduleHistorySave = () => {
|
|
555
|
+
if (historyTimer) return;
|
|
556
|
+
historyTimer = setTimeout(() => {
|
|
557
|
+
historyTimer = null;
|
|
558
|
+
saveTaskHistory(stateDir(), inbound, outbound);
|
|
559
|
+
}, 500);
|
|
560
|
+
historyTimer.unref?.();
|
|
561
|
+
};
|
|
464
562
|
/**
|
|
465
563
|
* 每个 thread 的唤醒账本:{ wakesAt: number[], sessionId }。
|
|
466
564
|
* wakesAt 只保留滑动窗口内的时间戳,既给限速/冷却用,也让后续消息
|
|
@@ -513,6 +611,34 @@ function applyUnsafe(ctx, config) {
|
|
|
513
611
|
}
|
|
514
612
|
});
|
|
515
613
|
|
|
614
|
+
// ── 机器列表的持久化 ──
|
|
615
|
+
//
|
|
616
|
+
// 重启后不必干等组播/扫描重新发现:先把上次见过的机器按「离线但已知地址」
|
|
617
|
+
// 放回来(restore 保留原 lastSeen,不会假装在线)。离线机器尤其需要它 ——
|
|
618
|
+
// 对端关机时永远等不到重新发现,页面就会一直是空的。
|
|
619
|
+
{
|
|
620
|
+
const snap = loadPeerSnapshot(stateDir());
|
|
621
|
+
if (snap.peers.length > 0) {
|
|
622
|
+
const restored = discovery.restore(snap.peers);
|
|
623
|
+
if (restored > 0) {
|
|
624
|
+
log(
|
|
625
|
+
`已恢复 ${restored} 台上次见过的机器(离线,重新发现后转为在线)` +
|
|
626
|
+
(snap.savedAt ? `,快照时间 ${new Date(snap.savedAt).toISOString()}` : ""),
|
|
627
|
+
);
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
let peerSnapshotTimer = null;
|
|
632
|
+
const schedulePeerSnapshot = () => {
|
|
633
|
+
if (peerSnapshotTimer) return;
|
|
634
|
+
peerSnapshotTimer = setTimeout(() => {
|
|
635
|
+
peerSnapshotTimer = null;
|
|
636
|
+
savePeerSnapshot(stateDir(), discovery.peers());
|
|
637
|
+
}, 2000);
|
|
638
|
+
peerSnapshotTimer.unref?.();
|
|
639
|
+
};
|
|
640
|
+
discovery.on("change", schedulePeerSnapshot);
|
|
641
|
+
|
|
516
642
|
// ── 能力采集(Placement 步骤 ①)──
|
|
517
643
|
//
|
|
518
644
|
// 尽早启动:采集是异步的、绝不阻塞启动(首轮可能要等 GPU 探测 ~3.5s)。
|
|
@@ -544,7 +670,7 @@ function applyUnsafe(ctx, config) {
|
|
|
544
670
|
const waker = { ready: false, ctx: undefined };
|
|
545
671
|
|
|
546
672
|
// 1) 先起对端 HTTP(拿到真实端口),再开始发现
|
|
547
|
-
startPeerServer(ctx, { config, discovery, inbound, log, warn, waker, threadState, capFor, capOverrides, throttled })
|
|
673
|
+
startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn, waker, threadState, capFor, capOverrides, throttled, onHistoryChange: scheduleHistorySave })
|
|
548
674
|
.then(async (port) => {
|
|
549
675
|
discovery.setPort(port);
|
|
550
676
|
|
|
@@ -649,10 +775,10 @@ function applyUnsafe(ctx, config) {
|
|
|
649
775
|
setupInbound(ctx, config, log, warn, waker);
|
|
650
776
|
|
|
651
777
|
// 3) agent 工具
|
|
652
|
-
registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState });
|
|
778
|
+
registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState, hostDispatched, onHistoryChange: scheduleHistorySave });
|
|
653
779
|
|
|
654
780
|
// 4) UI 接口
|
|
655
|
-
registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, capFor, capOverrides, throttled, waker });
|
|
781
|
+
registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, hostDispatched, capFor, capOverrides, throttled, waker, onHistoryChange: scheduleHistorySave });
|
|
656
782
|
|
|
657
783
|
ctx.effect(() => () => {
|
|
658
784
|
discovery.stop();
|
|
@@ -770,8 +896,8 @@ async function wakeAgent(waker, config, task, warn = () => {}) {
|
|
|
770
896
|
warn(`本机 DSH 的 agentPresets 没有 standingKeyFor(版本较旧?),已跳过;继续尝试建会话`);
|
|
771
897
|
}
|
|
772
898
|
|
|
773
|
-
const workspace = await c.workspaceRegistry.create(resolveWorkspace(config));
|
|
774
899
|
const sessionId = brandString(`mesh-${randomUUID()}`);
|
|
900
|
+
const workspace = await c.workspaceRegistry.create(resolveWorkspace(config, sessionId));
|
|
775
901
|
const selection = c.agentDefaultModel.currentSelection();
|
|
776
902
|
|
|
777
903
|
const handle = await c.agents.create({
|
|
@@ -826,6 +952,72 @@ async function wakeAgent(waker, config, task, warn = () => {}) {
|
|
|
826
952
|
return sessionId;
|
|
827
953
|
}
|
|
828
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
|
+
|
|
829
1021
|
/**
|
|
830
1022
|
* 把一条入站任务喂进一个**已存在但已结束**的会话,而不是新建一个。
|
|
831
1023
|
*
|
|
@@ -909,9 +1101,16 @@ async function wakeAgentOrResume(waker, config, task, resumeSessionId, warn = ()
|
|
|
909
1101
|
return wakeAgent(waker, config, task, warn);
|
|
910
1102
|
}
|
|
911
1103
|
|
|
912
|
-
function resolveWorkspace(config) {
|
|
1104
|
+
function resolveWorkspace(config, sessionId) {
|
|
913
1105
|
if (config.workspaceRoot && isAbsolute(config.workspaceRoot)) return config.workspaceRoot;
|
|
914
|
-
|
|
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;
|
|
915
1114
|
}
|
|
916
1115
|
|
|
917
1116
|
|
|
@@ -995,7 +1194,18 @@ function classifyInbound(task, threadState, config, now, capFor, { canInject = f
|
|
|
995
1194
|
* 收到对端任务:会话键命中且会话仍活跃就复用,否则新建,
|
|
996
1195
|
* 最后才新建会话。复用是为了避免"每条消息都从零重新探索上下文"。
|
|
997
1196
|
*/
|
|
998
|
-
function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled) {
|
|
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
|
+
}
|
|
999
1209
|
const rec = inbound.find((t) => t.id === task.id);
|
|
1000
1210
|
// 记下"回信地址",与"本机用哪个会话处理"是两件事。对端可以 GET
|
|
1001
1211
|
// /mesh/v1/tasks 读到它,调试时能看清结果该送回哪里。
|
|
@@ -1028,6 +1238,7 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
|
|
|
1028
1238
|
if (!verdict.wake) {
|
|
1029
1239
|
if (rec) {
|
|
1030
1240
|
rec.status = verdict.kind === "cap" ? "throttled" : "noted-only";
|
|
1241
|
+
onHistoryChange?.();
|
|
1031
1242
|
// 原因必须写出来。之前这里什么都不记,于是 status='noted-only' 时
|
|
1032
1243
|
// routeDecision 是 None —— 看不出为什么没处理,又回到"只能靠猜"的老路
|
|
1033
1244
|
rec.routeDecision = `未唤醒:${verdict.reason}`;
|
|
@@ -1092,6 +1303,7 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
|
|
|
1092
1303
|
);
|
|
1093
1304
|
if (targetRec) {
|
|
1094
1305
|
targetRec.status = status;
|
|
1306
|
+
onHistoryChange?.();
|
|
1095
1307
|
// 决策留痕:对端可以 GET /mesh/v1/tasks 读到"为什么这么路由"。
|
|
1096
1308
|
// 没有这个,出问题时只能靠猜(dispatchError 那次就是这么加的)。
|
|
1097
1309
|
targetRec.routeDecision = `${label} ${sessionId}(会话键 ${conversationKey(targetTask) || "无"})`;
|
|
@@ -1128,6 +1340,7 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
|
|
|
1128
1340
|
if (!waker?.ready) {
|
|
1129
1341
|
if (rec) {
|
|
1130
1342
|
rec.status = "stored-only";
|
|
1343
|
+
onHistoryChange?.();
|
|
1131
1344
|
rec.routeDecision = key ? `无法新建会话(会话键 ${key})` : "无法新建会话(无会话键)";
|
|
1132
1345
|
// 记下原因,让对端能远程读到(GET /mesh/v1/tasks)。一台没有界面或
|
|
1133
1346
|
// 日志访问权的机器(比如 Android/Termux)出问题,否则只能靠猜。
|
|
@@ -1148,6 +1361,7 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
|
|
|
1148
1361
|
// 背压:明确回"忙",而不是无脑排队让对方以为已受理
|
|
1149
1362
|
if (rec) {
|
|
1150
1363
|
rec.status = "busy";
|
|
1364
|
+
onHistoryChange?.();
|
|
1151
1365
|
rec.routeDecision = `会话 ${key} 积压 ${pending.length} 条(上限 ${MAX_PENDING_PER_CONV}),已背压`;
|
|
1152
1366
|
}
|
|
1153
1367
|
warn(`任务 ${task.id} 被背压:会话 ${key} 积压已达上限 ${MAX_PENDING_PER_CONV}`);
|
|
@@ -1156,6 +1370,7 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
|
|
|
1156
1370
|
pending.push({ task, rec });
|
|
1157
1371
|
if (rec) {
|
|
1158
1372
|
rec.status = "queued-for-session";
|
|
1373
|
+
onHistoryChange?.();
|
|
1159
1374
|
rec.routeDecision = `会话 ${key} 正在建会话,已排队(队内第 ${pending.length} 条)`;
|
|
1160
1375
|
}
|
|
1161
1376
|
log(`任务 ${task.id} 排队等待会话 ${key} 建立`);
|
|
@@ -1172,6 +1387,7 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
|
|
|
1172
1387
|
.then((sessionId) => {
|
|
1173
1388
|
if (rec) {
|
|
1174
1389
|
rec.status = "dispatched";
|
|
1390
|
+
onHistoryChange?.();
|
|
1175
1391
|
// 三分支文案要互斥:恢复成功时不能再挂「首次出现,或原会话已结束」——
|
|
1176
1392
|
// 那句话正好与事实相反(实测时读出来自相矛盾)。
|
|
1177
1393
|
const resumed = sessionId === knownSessionId;
|
|
@@ -1205,6 +1421,7 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
|
|
|
1205
1421
|
for (const item of queued.slice(drained)) {
|
|
1206
1422
|
if (item.rec) {
|
|
1207
1423
|
item.rec.status = "queued-lost";
|
|
1424
|
+
onHistoryChange?.();
|
|
1208
1425
|
item.rec.routeDecision = `会话 ${key} 建好后已不可注入(会话可能已结束)`;
|
|
1209
1426
|
}
|
|
1210
1427
|
}
|
|
@@ -1214,6 +1431,7 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
|
|
|
1214
1431
|
if (key) pendingByConv.delete(key);
|
|
1215
1432
|
if (rec) {
|
|
1216
1433
|
rec.status = "dispatch-failed";
|
|
1434
|
+
onHistoryChange?.();
|
|
1217
1435
|
// 同上:原因必须随任务记录一起能被远端读到
|
|
1218
1436
|
rec.dispatchError = String(err?.message ?? err);
|
|
1219
1437
|
rec.routeDecision = `${key ? `新建会话(会话键 ${key})` : "新建会话(无会话键,一次性任务)"} → 失败`;
|
|
@@ -1489,7 +1707,7 @@ async function peerFetchEndpoint(ep, url, opts = {}) {
|
|
|
1489
1707
|
|
|
1490
1708
|
// ───────────────────────── 对端 HTTP 服务 ─────────────────────────
|
|
1491
1709
|
|
|
1492
|
-
function startPeerServer(ctx, { config, discovery, inbound, log, warn, waker, threadState, capFor, capOverrides, throttled }) {
|
|
1710
|
+
function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn, waker, threadState, capFor, capOverrides, throttled, onHistoryChange }) {
|
|
1493
1711
|
const send = (res, code, payload) => {
|
|
1494
1712
|
const body = Buffer.from(JSON.stringify(payload), "utf8");
|
|
1495
1713
|
res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Content-Length": body.length });
|
|
@@ -1554,12 +1772,13 @@ function startPeerServer(ctx, { config, discovery, inbound, log, warn, waker, th
|
|
|
1554
1772
|
const duplicate = inbound.some((t) => t.id === task.id);
|
|
1555
1773
|
if (!duplicate) {
|
|
1556
1774
|
inbound.push(task);
|
|
1775
|
+
onHistoryChange?.();
|
|
1557
1776
|
if (inbound.length > MAX_HISTORY) inbound.shift();
|
|
1558
1777
|
}
|
|
1559
1778
|
log(`收到任务 ${task.id} 来自 ${task.from}${duplicate ? "(重复,忽略)" : ""}`);
|
|
1560
1779
|
if (!duplicate) {
|
|
1561
1780
|
try {
|
|
1562
|
-
handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled);
|
|
1781
|
+
handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled, onHistoryChange, outbound);
|
|
1563
1782
|
} catch (err) {
|
|
1564
1783
|
warn(`处理入站任务异常: ${err?.message ?? err}`);
|
|
1565
1784
|
}
|
|
@@ -1618,7 +1837,7 @@ function readJson(req) {
|
|
|
1618
1837
|
|
|
1619
1838
|
// ───────────────────────── agent 工具 ─────────────────────────
|
|
1620
1839
|
|
|
1621
|
-
function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState }) {
|
|
1840
|
+
function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState, hostDispatched, onHistoryChange }) {
|
|
1622
1841
|
const text = (v) => [{ type: "text", text: v }];
|
|
1623
1842
|
|
|
1624
1843
|
ctx.tools.register(
|
|
@@ -1739,6 +1958,16 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
|
|
|
1739
1958
|
originSession: exec?.agent?.session?.id ? String(exec.agent.session.id) : "",
|
|
1740
1959
|
};
|
|
1741
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
|
+
|
|
1742
1971
|
// Replies arrive from the target machine, so bind its inbound key
|
|
1743
1972
|
// before HTTP: the peer may reply before this request completes.
|
|
1744
1973
|
const replyKey = conversationKey({ fromMachine: target.machine, thread: payload.thread });
|
|
@@ -1763,6 +1992,7 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
|
|
|
1763
1992
|
});
|
|
1764
1993
|
const body = await res.json().catch(() => ({}));
|
|
1765
1994
|
outbound.push({ ...payload, toMachine: target.machine, at: new Date().toISOString(), ok: res.ok, status: res.status });
|
|
1995
|
+
onHistoryChange?.();
|
|
1766
1996
|
if (outbound.length > MAX_HISTORY) outbound.shift();
|
|
1767
1997
|
|
|
1768
1998
|
if (!res.ok) {
|
|
@@ -1777,6 +2007,7 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
|
|
|
1777
2007
|
);
|
|
1778
2008
|
} catch (err) {
|
|
1779
2009
|
outbound.push({ ...payload, toMachine: target.machine, at: new Date().toISOString(), ok: false, error: String(err?.message ?? err) });
|
|
2010
|
+
onHistoryChange?.();
|
|
1780
2011
|
return `派发失败:${err?.name === "TimeoutError" ? "超时" : err?.message ?? err}`;
|
|
1781
2012
|
}
|
|
1782
2013
|
},
|
|
@@ -1803,7 +2034,7 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
|
|
|
1803
2034
|
|
|
1804
2035
|
// ───────────────────────── UI 接口(本地回环) ─────────────────────────
|
|
1805
2036
|
|
|
1806
|
-
function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, capFor, capOverrides, throttled, waker }) {
|
|
2037
|
+
function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, hostDispatched, capFor, capOverrides, throttled, waker, onHistoryChange }) {
|
|
1807
2038
|
const send = (res, code, payload) => {
|
|
1808
2039
|
const body = Buffer.from(JSON.stringify(payload), "utf8");
|
|
1809
2040
|
res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Content-Length": body.length });
|
|
@@ -1979,7 +2210,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
1979
2210
|
throttled.delete(thread);
|
|
1980
2211
|
if (task) {
|
|
1981
2212
|
log(`用户将 thread "${thread}" 上限提高到 ${next},放行最新任务 ${lastId}`);
|
|
1982
|
-
handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled);
|
|
2213
|
+
handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled, onHistoryChange, outbound);
|
|
1983
2214
|
} else {
|
|
1984
2215
|
log(`用户将 thread "${thread}" 上限提高到 ${next}(未找到可重放的任务)`);
|
|
1985
2216
|
}
|
|
@@ -2199,6 +2430,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2199
2430
|
const target = found.peer;
|
|
2200
2431
|
|
|
2201
2432
|
const id = `t-${randomBytes(6).toString("hex")}`;
|
|
2433
|
+
let createdSessionId = "";
|
|
2202
2434
|
const payload = {
|
|
2203
2435
|
id,
|
|
2204
2436
|
from: `${machineOf(discovery)}/${safeUser()}`,
|
|
@@ -2208,7 +2440,63 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2208
2440
|
noWake: body?.noWake === true,
|
|
2209
2441
|
newSession: body?.newSession === true,
|
|
2210
2442
|
workspace: body?.workspace ? String(body.workspace) : "",
|
|
2443
|
+
// 页面手动派发时,UI 会带上「当前会话 id」,回执就能落回那个会话。
|
|
2444
|
+
// 不带的话宿主没有绑定可登记,对端回传只能新开一个 mesh-* 会话 ——
|
|
2445
|
+
// 这正是「手动派发后回执自己长出一个新会话」的原因。
|
|
2446
|
+
originSession: body?.originSession ? String(body.originSession) : "",
|
|
2211
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
|
+
|
|
2212
2500
|
try {
|
|
2213
2501
|
const r = await peerFetch(target, "/mesh/v1/task", {
|
|
2214
2502
|
method: "POST",
|
|
@@ -2218,8 +2506,9 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2218
2506
|
});
|
|
2219
2507
|
const rb = await r.json().catch(() => ({}));
|
|
2220
2508
|
outbound.push({ ...payload, toMachine: target.machine, at: new Date().toISOString(), ok: r.ok, status: r.status });
|
|
2509
|
+
onHistoryChange?.();
|
|
2221
2510
|
if (outbound.length > MAX_HISTORY) outbound.shift();
|
|
2222
|
-
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 });
|
|
2223
2512
|
} catch (err) {
|
|
2224
2513
|
return send(res, 502, { ok: false, error: String(err?.message ?? err) });
|
|
2225
2514
|
}
|