dsh-plugin-mesh 0.3.35 → 0.4.0
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 +2 -0
- package/lib/_selftest-reasoning.mjs +48 -0
- package/lib/_selftest-reply-route.mjs +159 -0
- package/lib/_selftest-resume.mjs +199 -0
- package/lib/index.js +119 -9
- package/package.json +5 -2
package/README.md
CHANGED
|
@@ -857,6 +857,8 @@ node lib/_selftest-discovery.mjs alpha 45900 9000 # 两个进程同时跑可
|
|
|
857
857
|
| 提交信息怎么写、PR 会被哪些门禁检查 | [`CONTRIBUTING.md`](CONTRIBUTING.md) |
|
|
858
858
|
| 流水线怎么运作、失败了怎么重跑、怎么撤回 | [`docs/RELEASE.md`](docs/RELEASE.md) |
|
|
859
859
|
| 改代码前必须知道的硬约束与坑 | [`AGENTS.md`](AGENTS.md) |
|
|
860
|
+
| 版本升级 / 新功能后的回归测试怎么跑 | [`docs/TEST-CASES.md`](docs/TEST-CASES.md) |
|
|
861
|
+
| 功能需求、架构逻辑、多版本通信协议、跨 IDE 实现契约 | [`docs/PLUGIN-SPEC.md`](docs/PLUGIN-SPEC.md) |
|
|
860
862
|
|
|
861
863
|
本地预演"如果现在合并会发生什么"(不联网、不改文件):
|
|
862
864
|
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Exercise the real wakeAgent function with inert host services; no model calls.
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
import vm from "node:vm";
|
|
5
|
+
|
|
6
|
+
const source = readFileSync(new URL("./index.js", import.meta.url), "utf8");
|
|
7
|
+
const start = source.indexOf("async function wakeAgent(");
|
|
8
|
+
// 切到**下一个顶层函数**为止,而不是写死 resolveWorkspace:
|
|
9
|
+
// 之前写死它,一旦在两者之间插入新函数,切片就变成「多个函数声明套在括号里」,
|
|
10
|
+
// 直接 SyntaxError(加会话恢复时就这么炸过一次)。
|
|
11
|
+
const nextFn = /\n(?:async )?function [A-Za-z_$]/.exec(source.slice(start + 1));
|
|
12
|
+
const end = nextFn ? start + 1 + nextFn.index : -1;
|
|
13
|
+
assert.ok(start >= 0 && end > start, "wakeAgent source boundaries must exist");
|
|
14
|
+
const wake = vm.runInNewContext(`(${source.slice(start, end)})`, {
|
|
15
|
+
randomUUID: () => "test-id",
|
|
16
|
+
brandString: (id) => id,
|
|
17
|
+
resolveWorkspace: () => "/test",
|
|
18
|
+
permissionPresetFor: () => "read-only",
|
|
19
|
+
createUserMessage: (message) => message,
|
|
20
|
+
buildPrompt: () => "test task",
|
|
21
|
+
RULE_KIND: "test", RULE_ID: "test",
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
for (const effort of ["low", "high", undefined]) {
|
|
25
|
+
let captured;
|
|
26
|
+
let prompted = false;
|
|
27
|
+
const selection = { provider: "test-provider", model: "test-model" };
|
|
28
|
+
if (effort !== undefined) selection.reasoningEffort = effort;
|
|
29
|
+
const ctx = {
|
|
30
|
+
agentPresets: { resolve: async () => ({ id: "standard" }), mount: async () => {} },
|
|
31
|
+
workspaceRegistry: { create: async () => ({ path: "/test", attachSession: async () => {} }) },
|
|
32
|
+
agentDefaultModel: { currentSelection: () => selection },
|
|
33
|
+
agents: { create: async (options) => {
|
|
34
|
+
captured = options.agentOptions;
|
|
35
|
+
await options.setup({});
|
|
36
|
+
return { agent: { session: {}, followup: () => { prompted = true; } } };
|
|
37
|
+
} },
|
|
38
|
+
permissionPresets: { set: () => {} },
|
|
39
|
+
sessionTitle: { rename: () => {} },
|
|
40
|
+
};
|
|
41
|
+
await wake({ ctx }, { agentPreset: "standard" }, { id: "task-id", from: "peer" });
|
|
42
|
+
assert.equal(captured.provider, selection.provider);
|
|
43
|
+
assert.equal(captured.model, selection.model);
|
|
44
|
+
assert.equal(captured.reasoningEffort, effort);
|
|
45
|
+
assert.equal(Object.hasOwn(captured, "reasoningEffort"), effort !== undefined);
|
|
46
|
+
assert.ok(prompted, "session setup must still reach followup");
|
|
47
|
+
console.log(`✓ wakeAgent ${effort === undefined ? "omits unset reasoningEffort" : `preserves reasoningEffort=${effort}`}`);
|
|
48
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/** Real tool → loopback HTTP → inbound routing; agents are inert test doubles.
|
|
2
|
+
* No DSH installation, model calls, multicast, or external network required.
|
|
3
|
+
*/
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import vm from "node:vm";
|
|
6
|
+
import { readFileSync, mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
|
|
7
|
+
import { tmpdir } from "node:os";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { conversationKey } from "./conversation.js";
|
|
10
|
+
|
|
11
|
+
const root = mkdtempSync(join(tmpdir(), "mesh-reply-test-"));
|
|
12
|
+
const cleanups = [];
|
|
13
|
+
const entryUrl = new URL("./index.js", import.meta.url);
|
|
14
|
+
let entrySource = readFileSync(entryUrl, "utf8");
|
|
15
|
+
// Mutation guard: prove the HTTP roundtrip fails with the original missing bind.
|
|
16
|
+
if (process.env.MESH_TEST_WITHOUT_REPLY_BINDING === "1") {
|
|
17
|
+
entrySource = entrySource.replace("if (replyKey && payload.originSession)", "if (false)");
|
|
18
|
+
}
|
|
19
|
+
entrySource = entrySource.replace(
|
|
20
|
+
'async function wakeAgent(waker, config, task, warn = () => {}) {',
|
|
21
|
+
'async function wakeAgent(waker, config, task, warn = () => {}) { return waker.runtime.wake();',
|
|
22
|
+
);
|
|
23
|
+
const noop = () => {};
|
|
24
|
+
const taskText = "Please complete this deterministic routing test without calling any model.";
|
|
25
|
+
|
|
26
|
+
async function makeNode(machine) {
|
|
27
|
+
const home = join(root, machine);
|
|
28
|
+
mkdirSync(join(home, "mesh"), { recursive: true });
|
|
29
|
+
writeFileSync(join(home, "mesh", "state.json"), JSON.stringify({ secret: "test-only-shared-secret" }));
|
|
30
|
+
const node = { machine, home, peers: [], tools: new Map(), agents: new Map(), inbound: [], outbound: [], threadState: new Map(), created: 0, sent: 0 };
|
|
31
|
+
const context = vm.createContext({
|
|
32
|
+
console, Buffer, URL, AbortSignal, setTimeout, clearTimeout, setInterval, clearInterval,
|
|
33
|
+
process: { ...process, env: { ...process.env, DSH_HOME: home } },
|
|
34
|
+
fetch: async (...args) => {
|
|
35
|
+
node.sent++;
|
|
36
|
+
if (node.fetchOverride) return node.fetchOverride(...args);
|
|
37
|
+
const response = await fetch(...args);
|
|
38
|
+
if (node.beforeAck) { const hook = node.beforeAck; node.beforeAck = undefined; await hook(); }
|
|
39
|
+
return response;
|
|
40
|
+
},
|
|
41
|
+
});
|
|
42
|
+
const schema = new Proxy(() => schema, { get: () => schema });
|
|
43
|
+
const mocks = {
|
|
44
|
+
"@deepseek-ai/schemastery": { default: schema },
|
|
45
|
+
"@deepseek-ai/dsh-brand": { brandString: (value) => value },
|
|
46
|
+
"@deepseek-ai/dsh-tools": { defineTool: (tool) => tool },
|
|
47
|
+
"@deepseek-ai/dsh-llm": { createUserMessage: (message) => message },
|
|
48
|
+
};
|
|
49
|
+
const module = new vm.SourceTextModule(entrySource + "\nexport { registerTools, startPeerServer };", {
|
|
50
|
+
context, identifier: entryUrl.href, initializeImportMeta: (meta) => { meta.url = entryUrl.href; },
|
|
51
|
+
});
|
|
52
|
+
await module.link(async (specifier) => {
|
|
53
|
+
const exports = mocks[specifier] ?? await import(specifier.startsWith(".") ? new URL(specifier, entryUrl).href : specifier);
|
|
54
|
+
return new vm.SyntheticModule(Object.keys(exports), function () {
|
|
55
|
+
for (const key of Object.keys(exports)) this.setExport(key, exports[key]);
|
|
56
|
+
}, { context });
|
|
57
|
+
});
|
|
58
|
+
await module.evaluate();
|
|
59
|
+
const ctx = {
|
|
60
|
+
get: (name) => name === "agents" ? node.agents : undefined,
|
|
61
|
+
effect: (fn) => cleanups.push(fn()),
|
|
62
|
+
tools: { register: (tool) => node.tools.set(tool.name, tool) },
|
|
63
|
+
};
|
|
64
|
+
const discovery = {
|
|
65
|
+
instanceId: machine, peers: () => node.peers,
|
|
66
|
+
selfRecord: () => ({ machine, id: machine, host: "127.0.0.1", port: node.port }),
|
|
67
|
+
};
|
|
68
|
+
node.config = { port: 0, requestTimeoutMs: 500, requirePairing: true, minTaskChars: 24, maxWakesPerThread: 30, threadCooldownMs: 5000, threadWindowMs: 3600000 };
|
|
69
|
+
const waker = { ready: true, ctx, runtime: { wake: async () => {
|
|
70
|
+
const id = `mesh-${machine}-${++node.created}`;
|
|
71
|
+
node.agents.set(id, { messages: [], followup(message) { this.messages.push(message); } });
|
|
72
|
+
return id;
|
|
73
|
+
} } };
|
|
74
|
+
const options = { ...node, discovery, config: node.config, log: noop, warn: noop, waker, capFor: () => node.config.maxWakesPerThread, capOverrides: new Map(), throttled: new Map() };
|
|
75
|
+
node.port = await module.namespace.startPeerServer(ctx, options);
|
|
76
|
+
module.namespace.registerTools(ctx, options);
|
|
77
|
+
node.peer = { machine, id: machine, online: true, host: "127.0.0.1", port: node.port,
|
|
78
|
+
endpoints: [{ transport: "lan", host: "127.0.0.1", port: node.port, lastSeen: Date.now() }] };
|
|
79
|
+
node.send = (peer, thread, sessionId, extra = {}) => node.tools.get("mesh_run").execute(
|
|
80
|
+
{ peer, thread, task: taskText, ...extra }, { agent: { session: { id: sessionId } } },
|
|
81
|
+
);
|
|
82
|
+
return node;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function until(check) {
|
|
86
|
+
const end = Date.now() + 3000;
|
|
87
|
+
while (!check()) {
|
|
88
|
+
if (Date.now() > end) throw new Error("routing did not settle");
|
|
89
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
try {
|
|
94
|
+
const a = await makeNode("A");
|
|
95
|
+
const b = await makeNode("B");
|
|
96
|
+
a.peers.push(b.peer); b.peers.push(a.peer);
|
|
97
|
+
const original = { messages: [], followup(message) { this.messages.push(message); } };
|
|
98
|
+
a.agents.set("original-session", original);
|
|
99
|
+
const key = (thread) => conversationKey({ fromMachine: "B", thread });
|
|
100
|
+
const disk = () => JSON.parse(readFileSync(join(a.home, "mesh", "threads.json"), "utf8"));
|
|
101
|
+
|
|
102
|
+
// First dispatch: persistence must be visible before B returns any reply.
|
|
103
|
+
assert.match(await a.send("B", "roundtrip", "original-session"), /已派发/);
|
|
104
|
+
assert.equal(disk().threads[key("roundtrip")].sessionId, "original-session");
|
|
105
|
+
await until(() => b.inbound.at(-1)?.status === "dispatched");
|
|
106
|
+
assert.match(await b.send("A", "roundtrip", "mesh-B-1"), /已派发/);
|
|
107
|
+
assert.equal(original.messages.length, 1);
|
|
108
|
+
assert.equal(a.inbound.at(-1).status, "injected-thread-session");
|
|
109
|
+
assert.equal(a.created, 0, "reply must not create a new A session");
|
|
110
|
+
console.log("✓ real mesh_run/HTTP roundtrip: original session receives reply, zero new A sessions");
|
|
111
|
+
|
|
112
|
+
// Very fast return before the sending tool receives its acknowledgement.
|
|
113
|
+
a.beforeAck = async () => {
|
|
114
|
+
assert.equal(disk().threads[key("fast")].sessionId, "original-session");
|
|
115
|
+
await until(() => b.inbound.at(-1)?.status === "dispatched");
|
|
116
|
+
assert.match(await b.send("A", "fast", "mesh-B-2"), /已派发/);
|
|
117
|
+
};
|
|
118
|
+
await a.send(`${b.peer.host}:${b.port}`, "fast", "original-session");
|
|
119
|
+
assert.equal(original.messages.length, 2);
|
|
120
|
+
assert.equal(a.created, 0);
|
|
121
|
+
console.log("✓ early reply and ip:port target resolve to the peer's machine name");
|
|
122
|
+
|
|
123
|
+
// Conflicting origin must be refused before HTTP; do not silently steal replies.
|
|
124
|
+
const sentBefore = a.sent;
|
|
125
|
+
assert.match(await a.send("B", "roundtrip", "another-session"), /任务未派发.*另一会话/);
|
|
126
|
+
assert.equal(a.sent, sentBefore);
|
|
127
|
+
assert.equal(a.threadState.get(key("roundtrip")).sessionId, "original-session");
|
|
128
|
+
|
|
129
|
+
// Delivery uncertainty must not erase the destination of a late reply.
|
|
130
|
+
a.fetchOverride = async () => { throw new Error("simulated timeout after possible delivery"); };
|
|
131
|
+
assert.match(await a.send("B", "uncertain", "original-session"), /派发失败/);
|
|
132
|
+
assert.equal(disk().threads[key("uncertain")].sessionId, "original-session");
|
|
133
|
+
a.fetchOverride = undefined;
|
|
134
|
+
console.log("✓ conflict refused; uncertain delivery keeps late-reply route");
|
|
135
|
+
|
|
136
|
+
// Existing inbound gates and explicit newSession remain in force.
|
|
137
|
+
await b.send("A", "roundtrip", "mesh-B-1", { noWake: true });
|
|
138
|
+
assert.equal(a.inbound.at(-1).status, "noted-only");
|
|
139
|
+
assert.equal(original.messages.length, 2);
|
|
140
|
+
a.config.maxWakesPerThread = 1;
|
|
141
|
+
await b.send("A", "roundtrip", "mesh-B-1");
|
|
142
|
+
assert.equal(a.inbound.at(-1).status, "throttled");
|
|
143
|
+
a.config.maxWakesPerThread = 30;
|
|
144
|
+
a.config.threadCooldownMs = 0;
|
|
145
|
+
await b.send("A", "roundtrip", "mesh-B-1", { newSession: true });
|
|
146
|
+
await until(() => a.inbound.at(-1).status === "dispatched");
|
|
147
|
+
assert.equal(a.created, 1);
|
|
148
|
+
console.log("✓ noWake, wake cap and explicit newSession still apply");
|
|
149
|
+
|
|
150
|
+
// Missing thread or originating session must not create a reply binding.
|
|
151
|
+
const bindings = a.threadState.size;
|
|
152
|
+
await a.send("B", "", "original-session", { noWake: true });
|
|
153
|
+
await a.send("B", "no-origin", "", { noWake: true });
|
|
154
|
+
assert.equal(a.threadState.size, bindings);
|
|
155
|
+
console.log("✓ absent thread/session does not bind");
|
|
156
|
+
} finally {
|
|
157
|
+
for (const cleanup of cleanups.reverse()) cleanup?.();
|
|
158
|
+
rmSync(root, { recursive: true, force: true });
|
|
159
|
+
}
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/** 会话恢复路径的单元检查:注入前能否把「已结束但记录还在」的会话接回来。
|
|
2
|
+
*
|
|
3
|
+
* 背景:`liveSession()` 查的是 DSH 内存里的 agent 注册表。重启 DSH 之后注册表是空的,
|
|
4
|
+
* 但磁盘上的对话记录完好无损。原实现直接新建会话,于是每重启一次所有跨机对话线
|
|
5
|
+
* 都静默断开。这里验证新增的 `wakeAgentOrResume` 会先尝试 `agents.resume`。
|
|
6
|
+
*
|
|
7
|
+
* 不联网、不装 DSH:index.js 用 vm 加载,import 被替换成最小 mock。
|
|
8
|
+
*/
|
|
9
|
+
import assert from "node:assert/strict";
|
|
10
|
+
import vm from "node:vm";
|
|
11
|
+
import { readFileSync, mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
|
|
12
|
+
import { tmpdir } from "node:os";
|
|
13
|
+
import { join } from "node:path";
|
|
14
|
+
import { conversationKey } from "./conversation.js";
|
|
15
|
+
|
|
16
|
+
const root = mkdtempSync(join(tmpdir(), "mesh-resume-test-"));
|
|
17
|
+
const entryUrl = new URL("./index.js", import.meta.url);
|
|
18
|
+
const cleanupPaths = [];
|
|
19
|
+
const noop = () => {};
|
|
20
|
+
|
|
21
|
+
const TASK_TEXT = "这张会话在重启前处理过的工作,现在要对端回传结果,测试请勿联网执行任何命令。";
|
|
22
|
+
|
|
23
|
+
async function loadModule() {
|
|
24
|
+
let source = readFileSync(entryUrl, "utf8");
|
|
25
|
+
// 暴露内部函数(这些不是公开 API,只给测试用)
|
|
26
|
+
source += "\nexport { handleInboundTask };";
|
|
27
|
+
const schema = new Proxy(() => schema, { get: () => schema });
|
|
28
|
+
const mocks = {
|
|
29
|
+
"@deepseek-ai/schemastery": { default: schema },
|
|
30
|
+
"@deepseek-ai/dsh-brand": { brandString: (value) => value },
|
|
31
|
+
"@deepseek-ai/dsh-tools": { defineTool: (tool) => tool },
|
|
32
|
+
"@deepseek-ai/dsh-llm": { createUserMessage: (message) => message },
|
|
33
|
+
};
|
|
34
|
+
const context = vm.createContext({ console, Buffer, URL, AbortSignal, setTimeout, clearTimeout, setInterval, clearInterval, process });
|
|
35
|
+
const module = new vm.SourceTextModule(source, {
|
|
36
|
+
context,
|
|
37
|
+
identifier: entryUrl.href,
|
|
38
|
+
initializeImportMeta: (meta) => { meta.url = entryUrl.href; },
|
|
39
|
+
});
|
|
40
|
+
await module.link(async (specifier) => {
|
|
41
|
+
const exports = mocks[specifier] ?? (await import(specifier.startsWith(".") ? new URL(specifier, entryUrl).href : specifier));
|
|
42
|
+
return new vm.SyntheticModule(Object.keys(exports), function () {
|
|
43
|
+
for (const key of Object.keys(exports)) this.setExport(key, exports[key]);
|
|
44
|
+
}, { context });
|
|
45
|
+
});
|
|
46
|
+
await module.evaluate();
|
|
47
|
+
return module.namespace;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 跑一次入站任务,返回本次尝试的结果。 */
|
|
51
|
+
async function runInbound(ns, opts = {}) {
|
|
52
|
+
const home = mkdtempSync(join(root, "home-"));
|
|
53
|
+
mkdirSync(join(home, "mesh"), { recursive: true });
|
|
54
|
+
writeFileSync(join(home, "mesh", "state.json"), JSON.stringify({ secret: "s" }));
|
|
55
|
+
|
|
56
|
+
const messages = [];
|
|
57
|
+
const resumedIds = [];
|
|
58
|
+
const createdIds = [];
|
|
59
|
+
const warnings = [];
|
|
60
|
+
|
|
61
|
+
const makeHandle = (sessionId) => ({
|
|
62
|
+
agent: { session: { id: sessionId }, followup: (m) => messages.push(m) },
|
|
63
|
+
dispose: async () => {},
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
const agentApi = {
|
|
67
|
+
resume: opts.withResume === false ? undefined : async ({ resumeSessionId }) => {
|
|
68
|
+
resumedIds.push(resumeSessionId);
|
|
69
|
+
if (opts.resumeFails) throw new Error("session log missing");
|
|
70
|
+
return makeHandle(resumeSessionId);
|
|
71
|
+
},
|
|
72
|
+
create: async ({ sessionId }) => {
|
|
73
|
+
createdIds.push(sessionId);
|
|
74
|
+
return makeHandle(sessionId);
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
const liveAgents = new Map();
|
|
79
|
+
const ctx = {
|
|
80
|
+
get: (name) => (name === "agents" ? { get: (id) => liveAgents.get(id), ...agentApi } : undefined),
|
|
81
|
+
effect: () => () => {},
|
|
82
|
+
};
|
|
83
|
+
const services = {
|
|
84
|
+
agentPresets: { resolve: async (id) => ({ id }), standingKeyFor: async () => {}, mount: async () => {} },
|
|
85
|
+
workspaceRegistry: {
|
|
86
|
+
create: async () => ({
|
|
87
|
+
path: home,
|
|
88
|
+
attachSession: async () => {},
|
|
89
|
+
detachSession: async () => {},
|
|
90
|
+
}),
|
|
91
|
+
},
|
|
92
|
+
agentDefaultModel: { currentSelection: () => ({ provider: "p", model: "m", reasoningEffort: "low" }) },
|
|
93
|
+
permissionPresets: { set: () => {} },
|
|
94
|
+
sessionTitle: { rename: () => {} },
|
|
95
|
+
};
|
|
96
|
+
// wakeAgent 通过 waker.ctx 取服务(c.agents.create / c.agents.resume 都在这里)
|
|
97
|
+
const wakerCtx = Object.assign(Object.create(ctx), services, {
|
|
98
|
+
get: ctx.get,
|
|
99
|
+
effect: () => () => {},
|
|
100
|
+
agents: agentApi,
|
|
101
|
+
});
|
|
102
|
+
const waker = { ready: true, ctx: wakerCtx, missing: [] };
|
|
103
|
+
|
|
104
|
+
const threadState = new Map();
|
|
105
|
+
const thread = "重启前的对话";
|
|
106
|
+
const key = conversationKey({ fromMachine: "B", thread });
|
|
107
|
+
if (opts.boundSessionId) threadState.set(key, { sessionId: opts.boundSessionId, wakesAt: [] });
|
|
108
|
+
if (opts.liveSessionId) liveAgents.set(opts.liveSessionId, { followup: noop });
|
|
109
|
+
|
|
110
|
+
const task = {
|
|
111
|
+
id: "t-resume-1",
|
|
112
|
+
from: "B/u",
|
|
113
|
+
fromMachine: "B",
|
|
114
|
+
thread,
|
|
115
|
+
task: TASK_TEXT,
|
|
116
|
+
newSession: opts.newSession === true,
|
|
117
|
+
};
|
|
118
|
+
const inbound = [];
|
|
119
|
+
const config = {
|
|
120
|
+
port: 0,
|
|
121
|
+
requestTimeoutMs: 500,
|
|
122
|
+
minTaskChars: 10,
|
|
123
|
+
maxWakesPerThread: 30,
|
|
124
|
+
threadCooldownMs: 5000,
|
|
125
|
+
threadWindowMs: 3600000,
|
|
126
|
+
agentPreset: "standard",
|
|
127
|
+
permissionPreset: "danger-full-access",
|
|
128
|
+
workspaceRoot: home,
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
await ns.handleInboundTask(
|
|
132
|
+
ctx, task, inbound, config, noop, (m) => warnings.push(String(m)),
|
|
133
|
+
waker, threadState, () => config.maxWakesPerThread, new Map(),
|
|
134
|
+
);
|
|
135
|
+
// 等 wakeAgentOrResume 的 then/catch 落定:出现任一可见副作用即可
|
|
136
|
+
const settled = () => r().messages.length > 0 || r().createdIds.length > 0 || r().resumedIds.length > 0 || r().warnings.length > 0;
|
|
137
|
+
function r() { return { messages, createdIds, resumedIds, warnings }; }
|
|
138
|
+
for (let i = 0; i < 200 && !settled(); i += 1) {
|
|
139
|
+
await new Promise((res) => setTimeout(res, 10));
|
|
140
|
+
}
|
|
141
|
+
await new Promise((res) => setTimeout(res, 60));
|
|
142
|
+
cleanupPaths.push(home);
|
|
143
|
+
return { messages, resumedIds, createdIds, warnings, threadState, key, inbound, home };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const ns = await loadModule();
|
|
147
|
+
|
|
148
|
+
try {
|
|
149
|
+
// 1) 绑定的会话不在注册表里,但能恢复 → 必须恢复,且不新建
|
|
150
|
+
{
|
|
151
|
+
const r = await runInbound(ns, { boundSessionId: "dead-session" });
|
|
152
|
+
assert.deepEqual(r.resumedIds, ["dead-session"], "应当按绑定 id 恢复旧会话");
|
|
153
|
+
assert.equal(r.createdIds.length, 0, "能恢复时不该新建会话");
|
|
154
|
+
assert.equal(r.messages.length, 1, "恢复后要把任务提示注入进去");
|
|
155
|
+
assert.equal(r.threadState.get(r.key).sessionId, "dead-session", "绑定仍是那个会话");
|
|
156
|
+
console.log("✓ 已结束的会话被恢复:注入原会话,未新建");
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// 2) 恢复失败 → 退回新建,且不能丢消息
|
|
160
|
+
{
|
|
161
|
+
const r = await runInbound(ns, { boundSessionId: "gone-session", resumeFails: true });
|
|
162
|
+
assert.deepEqual(r.resumedIds, ["gone-session"], "先尝试恢复");
|
|
163
|
+
assert.equal(r.createdIds.length, 1, "恢复失败后应新建会话");
|
|
164
|
+
assert.equal(r.messages.length, 1, "任务提示仍要注入(不能丢回传)");
|
|
165
|
+
assert.ok(r.warnings.some((w) => w.includes("恢复会话")), "恢复失败要留下 warn 原因");
|
|
166
|
+
assert.equal(r.threadState.get(r.key).sessionId, r.createdIds[0], "绑定改到新会话");
|
|
167
|
+
console.log("✓ 恢复失败时退回新建:消息不丢,原因有记录");
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// 3) 旧版 DSH 没有 agents.resume → 直接新建,不抛错
|
|
171
|
+
{
|
|
172
|
+
const r = await runInbound(ns, { boundSessionId: "old-dsh", withResume: false });
|
|
173
|
+
assert.equal(r.createdIds.length, 1, "没有 resume 时应新建");
|
|
174
|
+
assert.equal(r.messages.length, 1);
|
|
175
|
+
assert.ok(r.warnings.some((w) => w.includes("没有 resume")), "要说清是版本能力缺失");
|
|
176
|
+
console.log("✓ 没有 resume API 时优雅降级为新建");
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// 4) 发送方显式要求新会话 → 不许恢复
|
|
180
|
+
{
|
|
181
|
+
const r = await runInbound(ns, { boundSessionId: "dead-session", newSession: true });
|
|
182
|
+
assert.equal(r.resumedIds.length, 0, "newSession=true 时不该恢复");
|
|
183
|
+
assert.equal(r.createdIds.length, 1, "应新建会话");
|
|
184
|
+
console.log("✓ newSession=true 时不恢复");
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// 5) 会话仍活跃 → 走注入路径,既不恢复也不新建
|
|
188
|
+
{
|
|
189
|
+
const r = await runInbound(ns, { boundSessionId: "live-1", liveSessionId: "live-1" });
|
|
190
|
+
assert.equal(r.resumedIds.length, 0, "活着就直接注入");
|
|
191
|
+
assert.equal(r.createdIds.length, 0);
|
|
192
|
+
console.log("✓ 会话仍活跃时直接注入,不触发恢复");
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
console.log("\n全部通过");
|
|
196
|
+
} finally {
|
|
197
|
+
for (const p of cleanupPaths) rmSync(p, { recursive: true, force: true });
|
|
198
|
+
rmSync(root, { recursive: true, force: true });
|
|
199
|
+
}
|
package/lib/index.js
CHANGED
|
@@ -45,7 +45,7 @@ import { tailnetFetch, tailnetOrigin } from "./tsnet/bridge.js";
|
|
|
45
45
|
export const name = "dsh-plugin-mesh";
|
|
46
46
|
export const inject = ["tools", "webServer"];
|
|
47
47
|
|
|
48
|
-
const VERSION = "0.
|
|
48
|
+
const VERSION = "0.4.0";
|
|
49
49
|
const RULE_ID = "mesh-inbound";
|
|
50
50
|
const RULE_KIND = "mesh";
|
|
51
51
|
const MAX_BODY = 256 * 1024;
|
|
@@ -649,7 +649,7 @@ function applyUnsafe(ctx, config) {
|
|
|
649
649
|
setupInbound(ctx, config, log, warn, waker);
|
|
650
650
|
|
|
651
651
|
// 3) agent 工具
|
|
652
|
-
registerTools(ctx, { discovery, config, inbound, outbound, log, warn });
|
|
652
|
+
registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState });
|
|
653
653
|
|
|
654
654
|
// 4) UI 接口
|
|
655
655
|
registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, capFor, capOverrides, throttled, waker });
|
|
@@ -777,7 +777,11 @@ async function wakeAgent(waker, config, task, warn = () => {}) {
|
|
|
777
777
|
const handle = await c.agents.create({
|
|
778
778
|
sessionId,
|
|
779
779
|
meta: { cwd: workspace.path, agentPreset: preset.id },
|
|
780
|
-
agentOptions: {
|
|
780
|
+
agentOptions: {
|
|
781
|
+
provider: selection.provider,
|
|
782
|
+
model: selection.model,
|
|
783
|
+
...(selection.reasoningEffort === undefined ? {} : { reasoningEffort: selection.reasoningEffort }),
|
|
784
|
+
},
|
|
781
785
|
setup: async (agentCtx) => {
|
|
782
786
|
await c.agentPresets.mount(agentCtx, preset.id);
|
|
783
787
|
},
|
|
@@ -822,6 +826,89 @@ async function wakeAgent(waker, config, task, warn = () => {}) {
|
|
|
822
826
|
return sessionId;
|
|
823
827
|
}
|
|
824
828
|
|
|
829
|
+
/**
|
|
830
|
+
* 把一条入站任务喂进一个**已存在但已结束**的会话,而不是新建一个。
|
|
831
|
+
*
|
|
832
|
+
* 为什么需要:`liveSession()` 看的是 DSH 内存里的 agent 注册表,重启 DSH 或
|
|
833
|
+
* 会话空闲被回收之后,注册表里就没有它了 —— 哪怕磁盘上的对话记录完好无损。
|
|
834
|
+
* 原来的做法是直接 `agents.create` 一个全新的 `mesh-<uuid>`,于是每重启一次,
|
|
835
|
+
* 所有跨机对话线都在下一次回传时静默断开(上下文还在旧会话里,新会话从零开始)。
|
|
836
|
+
*
|
|
837
|
+
* DSH 本身支持按 id 从持久化日志恢复会话:`agents.resume({ resumeSessionId })`。
|
|
838
|
+
* 这里就用它把旧会话接回来再注入。
|
|
839
|
+
*
|
|
840
|
+
* 失败(版本太旧没有 resume、会话记录被删、没配 sessionPersistence)时返回 null,
|
|
841
|
+
* 由调用方回退到新建会话 —— 恢复是**尽力而为**,不能因为它挂了就让回传丢失。
|
|
842
|
+
*/
|
|
843
|
+
async function resumeAgent(waker, config, task, sessionId, warn = () => {}) {
|
|
844
|
+
const c = waker.ctx;
|
|
845
|
+
if (typeof c.agents?.resume !== "function") {
|
|
846
|
+
warn("本机 DSH 的 agents 没有 resume,无法恢复已结束的会话;将新建会话");
|
|
847
|
+
return null;
|
|
848
|
+
}
|
|
849
|
+
const preset = await c.agentPresets.resolve(config.agentPreset);
|
|
850
|
+
if (typeof c.agentPresets.standingKeyFor === "function") {
|
|
851
|
+
await c.agentPresets.standingKeyFor(preset.id);
|
|
852
|
+
}
|
|
853
|
+
const selection = c.agentDefaultModel.currentSelection();
|
|
854
|
+
const handle = await c.agents.resume({
|
|
855
|
+
resumeSessionId: sessionId,
|
|
856
|
+
agentOptions: {
|
|
857
|
+
provider: selection.provider,
|
|
858
|
+
model: selection.model,
|
|
859
|
+
...(selection.reasoningEffort === undefined ? {} : { reasoningEffort: selection.reasoningEffort }),
|
|
860
|
+
},
|
|
861
|
+
setup: async (agentCtx) => {
|
|
862
|
+
await c.agentPresets.mount(agentCtx, preset.id);
|
|
863
|
+
},
|
|
864
|
+
});
|
|
865
|
+
try {
|
|
866
|
+
c.permissionPresets.set(handle.agent.session, permissionPresetFor(config, task));
|
|
867
|
+
// 恢复的会话**不重命名**:原标题承载着"这场对话原来是什么",改掉就丢了这段历史。
|
|
868
|
+
handle.agent.followup(
|
|
869
|
+
createUserMessage({
|
|
870
|
+
content: [{ type: "text", text: buildPrompt(task) }],
|
|
871
|
+
source: {
|
|
872
|
+
kind: "webhook",
|
|
873
|
+
provider: RULE_KIND,
|
|
874
|
+
source: task.from,
|
|
875
|
+
deliveryId: task.id,
|
|
876
|
+
ruleId: RULE_ID,
|
|
877
|
+
form: "notice",
|
|
878
|
+
summary: `mesh task from ${task.from} (resumed)`,
|
|
879
|
+
},
|
|
880
|
+
}),
|
|
881
|
+
);
|
|
882
|
+
} catch (err) {
|
|
883
|
+
try {
|
|
884
|
+
await handle.dispose();
|
|
885
|
+
} catch {
|
|
886
|
+
/* 回滚失败不覆盖原始错误 */
|
|
887
|
+
}
|
|
888
|
+
throw err;
|
|
889
|
+
}
|
|
890
|
+
return sessionId;
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
/**
|
|
894
|
+
* 唤醒会话:能恢复就恢复,恢复不了才新建。
|
|
895
|
+
*
|
|
896
|
+
* 优先级是「接续旧上下文」高于「开一个干净的新会话」—— 后者会让用户丢掉
|
|
897
|
+
* 整场对话的记忆,而这个 plugin 的全部价值就在于把上下文带过去。
|
|
898
|
+
*/
|
|
899
|
+
async function wakeAgentOrResume(waker, config, task, resumeSessionId, warn = () => {}) {
|
|
900
|
+
if (resumeSessionId && task?.newSession !== true) {
|
|
901
|
+
try {
|
|
902
|
+
const resumed = await resumeAgent(waker, config, task, resumeSessionId, warn);
|
|
903
|
+
if (resumed) return resumed;
|
|
904
|
+
} catch (err) {
|
|
905
|
+
// 恢复失败不该让这条回传丢掉:退回新建,并把原因记下来。
|
|
906
|
+
warn(`恢复会话 ${String(resumeSessionId).slice(0, 20)}… 失败,改为新建:${err?.message ?? err}`);
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
return wakeAgent(waker, config, task, warn);
|
|
910
|
+
}
|
|
911
|
+
|
|
825
912
|
function resolveWorkspace(config) {
|
|
826
913
|
if (config.workspaceRoot && isAbsolute(config.workspaceRoot)) return config.workspaceRoot;
|
|
827
914
|
return resolve(homedir());
|
|
@@ -1078,14 +1165,23 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
|
|
|
1078
1165
|
}
|
|
1079
1166
|
|
|
1080
1167
|
noteWake();
|
|
1081
|
-
|
|
1168
|
+
// 走到这里说明「能注入」不成立。若这个键绑过会话,先试着把它**恢复**回来
|
|
1169
|
+
// (重启 DSH / 会话被回收后,记录还在磁盘,注册表里却没有了),
|
|
1170
|
+
// 恢复不了再新建 —— 见 wakeAgentOrResume。
|
|
1171
|
+
wakeAgentOrResume(waker, config, task, knownSessionId, warn)
|
|
1082
1172
|
.then((sessionId) => {
|
|
1083
1173
|
if (rec) {
|
|
1084
1174
|
rec.status = "dispatched";
|
|
1175
|
+
// 三分支文案要互斥:恢复成功时不能再挂「首次出现,或原会话已结束」——
|
|
1176
|
+
// 那句话正好与事实相反(实测时读出来自相矛盾)。
|
|
1177
|
+
const resumed = sessionId === knownSessionId;
|
|
1178
|
+
const why = resumed
|
|
1179
|
+
? "重启或会话被回收后接回原上下文"
|
|
1180
|
+
: task.newSession === true
|
|
1181
|
+
? "发送方显式要求新会话"
|
|
1182
|
+
: "首次出现,或原会话已结束";
|
|
1085
1183
|
rec.routeDecision = key
|
|
1086
|
-
?
|
|
1087
|
-
task.newSession === true ? "发送方显式要求新会话" : "首次出现,或原会话已结束"
|
|
1088
|
-
})`
|
|
1184
|
+
? `${resumed ? "恢复了已结束的会话" : "新建会话"}并绑定会话键 ${key}(${why})`
|
|
1089
1185
|
: "新建会话(无会话键,一次性任务,用完不绑定)";
|
|
1090
1186
|
}
|
|
1091
1187
|
if (key) {
|
|
@@ -1522,7 +1618,7 @@ function readJson(req) {
|
|
|
1522
1618
|
|
|
1523
1619
|
// ───────────────────────── agent 工具 ─────────────────────────
|
|
1524
1620
|
|
|
1525
|
-
function registerTools(ctx, { discovery, config, inbound, outbound, log, warn }) {
|
|
1621
|
+
function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState }) {
|
|
1526
1622
|
const text = (v) => [{ type: "text", text: v }];
|
|
1527
1623
|
|
|
1528
1624
|
ctx.tools.register(
|
|
@@ -1592,7 +1688,7 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn })
|
|
|
1592
1688
|
"注意:纯回执/确认(收到、好的、ack、ping)不要用本工具,那会凭空开一个 agent 会话;" +
|
|
1593
1689
|
"确实要发这类内容就带 noWake: true。" +
|
|
1594
1690
|
"同一件事请始终复用同一个 thread 值 —— 对端会据此复用同一个会话," +
|
|
1595
|
-
"既省 token
|
|
1691
|
+
"既省 token 也让它记得前几轮的结论。不同发起会话请使用不同 thread,避免回复串线。",
|
|
1596
1692
|
parameters: {
|
|
1597
1693
|
peer: { type: "string", required: true, description: "目标机器名(用 mesh_peers 查)" },
|
|
1598
1694
|
task: { type: "string", required: true, description: "任务内容,自然语言描述清楚" },
|
|
@@ -1643,6 +1739,20 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn })
|
|
|
1643
1739
|
originSession: exec?.agent?.session?.id ? String(exec.agent.session.id) : "",
|
|
1644
1740
|
};
|
|
1645
1741
|
|
|
1742
|
+
// Replies arrive from the target machine, so bind its inbound key
|
|
1743
|
+
// before HTTP: the peer may reply before this request completes.
|
|
1744
|
+
const replyKey = conversationKey({ fromMachine: target.machine, thread: payload.thread });
|
|
1745
|
+
if (replyKey && payload.originSession) {
|
|
1746
|
+
if (pendingByConv.has(replyKey)) return "任务未派发:此 thread 正在建立会话,请稍后重试。";
|
|
1747
|
+
const previous = threadState.get(replyKey);
|
|
1748
|
+
if (previous?.sessionId && previous.sessionId !== payload.originSession) {
|
|
1749
|
+
return "任务未派发:thread 已绑定另一会话,请使用新的 thread。";
|
|
1750
|
+
}
|
|
1751
|
+
threadState.set(replyKey, { ...previous, wakesAt: previous?.wakesAt ?? [], sessionId: payload.originSession });
|
|
1752
|
+
saveThreads(threadState);
|
|
1753
|
+
// Retain the binding on failure: a timeout does not prove non-delivery.
|
|
1754
|
+
}
|
|
1755
|
+
|
|
1646
1756
|
const started = Date.now();
|
|
1647
1757
|
try {
|
|
1648
1758
|
const res = await peerFetch(target, "/mesh/v1/task", {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-plugin-mesh",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "DSH Mesh:局域网自动发现同网段的 DSH 实例、显示每台机器上报的能力,并双向派发任务;可用内置的用户态 Tailscale 节点跨互联网组网。Discovers other DSH instances on the LAN, shows the capabilities each one reports, and dispatches tasks between machines in both directions, with an optional userspace Tailscale node for links across networks.",
|
|
6
6
|
"license": "MIT",
|
|
@@ -59,7 +59,10 @@
|
|
|
59
59
|
"selftest:caps": "node lib/_selftest-capabilities.mjs",
|
|
60
60
|
"selftest:newsession": "node lib/_selftest-newsession.mjs",
|
|
61
61
|
"selftest:release": "node scripts/_selftest-release-plan.mjs",
|
|
62
|
-
"
|
|
62
|
+
"selftest:reply": "node --experimental-vm-modules lib/_selftest-reply-route.mjs",
|
|
63
|
+
"selftest:resume": "node --experimental-vm-modules lib/_selftest-resume.mjs",
|
|
64
|
+
"selftest:reasoning": "node lib/_selftest-reasoning.mjs",
|
|
65
|
+
"test": "npm run check && npm run selftest && npm run selftest:prompt && npm run selftest:pairing && npm run selftest:client && npm run selftest:caps && npm run selftest:release && npm run selftest:reply && npm run selftest:reasoning && npm run selftest:resume",
|
|
63
66
|
"check": "node scripts/check-version.mjs && node scripts/check-tdz.mjs && node --check lib/index.js && node --check lib/discovery.js && node --check lib/conversation.js && node --check lib/identity.js && node --check lib/capabilities.js && node --check lib/prompt.js && node --check lib/pairing.js && node --check lib/scan.js && node --check lib/tsnet/download.js && node --check lib/tsnet/manager.js && node --check lib/tsnet/bridge.js && node --check client/client.js && node --check scripts/release-plan.mjs && npm run check:loadable && npm run check:docs",
|
|
64
67
|
"build:sidecar": "bash scripts/build-sidecar.sh",
|
|
65
68
|
"verify:mirror": "node scripts/verify-lan-mirror.mjs",
|