dsh-plugin-mesh 0.3.35 → 0.3.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/_selftest-reasoning.mjs +44 -0
- package/lib/_selftest-reply-route.mjs +159 -0
- package/lib/index.js +23 -5
- package/package.json +4 -2
|
@@ -0,0 +1,44 @@
|
|
|
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
|
+
const end = source.indexOf("\nfunction resolveWorkspace(", start);
|
|
9
|
+
assert.ok(start >= 0 && end > start, "wakeAgent source boundaries must exist");
|
|
10
|
+
const wake = vm.runInNewContext(`(${source.slice(start, end)})`, {
|
|
11
|
+
randomUUID: () => "test-id",
|
|
12
|
+
brandString: (id) => id,
|
|
13
|
+
resolveWorkspace: () => "/test",
|
|
14
|
+
permissionPresetFor: () => "read-only",
|
|
15
|
+
createUserMessage: (message) => message,
|
|
16
|
+
buildPrompt: () => "test task",
|
|
17
|
+
RULE_KIND: "test", RULE_ID: "test",
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
for (const effort of ["low", "high", undefined]) {
|
|
21
|
+
let captured;
|
|
22
|
+
let prompted = false;
|
|
23
|
+
const selection = { provider: "test-provider", model: "test-model" };
|
|
24
|
+
if (effort !== undefined) selection.reasoningEffort = effort;
|
|
25
|
+
const ctx = {
|
|
26
|
+
agentPresets: { resolve: async () => ({ id: "standard" }), mount: async () => {} },
|
|
27
|
+
workspaceRegistry: { create: async () => ({ path: "/test", attachSession: async () => {} }) },
|
|
28
|
+
agentDefaultModel: { currentSelection: () => selection },
|
|
29
|
+
agents: { create: async (options) => {
|
|
30
|
+
captured = options.agentOptions;
|
|
31
|
+
await options.setup({});
|
|
32
|
+
return { agent: { session: {}, followup: () => { prompted = true; } } };
|
|
33
|
+
} },
|
|
34
|
+
permissionPresets: { set: () => {} },
|
|
35
|
+
sessionTitle: { rename: () => {} },
|
|
36
|
+
};
|
|
37
|
+
await wake({ ctx }, { agentPreset: "standard" }, { id: "task-id", from: "peer" });
|
|
38
|
+
assert.equal(captured.provider, selection.provider);
|
|
39
|
+
assert.equal(captured.model, selection.model);
|
|
40
|
+
assert.equal(captured.reasoningEffort, effort);
|
|
41
|
+
assert.equal(Object.hasOwn(captured, "reasoningEffort"), effort !== undefined);
|
|
42
|
+
assert.ok(prompted, "session setup must still reach followup");
|
|
43
|
+
console.log(`✓ wakeAgent ${effort === undefined ? "omits unset reasoningEffort" : `preserves reasoningEffort=${effort}`}`);
|
|
44
|
+
}
|
|
@@ -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
|
+
}
|
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.3.
|
|
48
|
+
const VERSION = "0.3.36";
|
|
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
|
},
|
|
@@ -1522,7 +1526,7 @@ function readJson(req) {
|
|
|
1522
1526
|
|
|
1523
1527
|
// ───────────────────────── agent 工具 ─────────────────────────
|
|
1524
1528
|
|
|
1525
|
-
function registerTools(ctx, { discovery, config, inbound, outbound, log, warn }) {
|
|
1529
|
+
function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState }) {
|
|
1526
1530
|
const text = (v) => [{ type: "text", text: v }];
|
|
1527
1531
|
|
|
1528
1532
|
ctx.tools.register(
|
|
@@ -1592,7 +1596,7 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn })
|
|
|
1592
1596
|
"注意:纯回执/确认(收到、好的、ack、ping)不要用本工具,那会凭空开一个 agent 会话;" +
|
|
1593
1597
|
"确实要发这类内容就带 noWake: true。" +
|
|
1594
1598
|
"同一件事请始终复用同一个 thread 值 —— 对端会据此复用同一个会话," +
|
|
1595
|
-
"既省 token
|
|
1599
|
+
"既省 token 也让它记得前几轮的结论。不同发起会话请使用不同 thread,避免回复串线。",
|
|
1596
1600
|
parameters: {
|
|
1597
1601
|
peer: { type: "string", required: true, description: "目标机器名(用 mesh_peers 查)" },
|
|
1598
1602
|
task: { type: "string", required: true, description: "任务内容,自然语言描述清楚" },
|
|
@@ -1643,6 +1647,20 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn })
|
|
|
1643
1647
|
originSession: exec?.agent?.session?.id ? String(exec.agent.session.id) : "",
|
|
1644
1648
|
};
|
|
1645
1649
|
|
|
1650
|
+
// Replies arrive from the target machine, so bind its inbound key
|
|
1651
|
+
// before HTTP: the peer may reply before this request completes.
|
|
1652
|
+
const replyKey = conversationKey({ fromMachine: target.machine, thread: payload.thread });
|
|
1653
|
+
if (replyKey && payload.originSession) {
|
|
1654
|
+
if (pendingByConv.has(replyKey)) return "任务未派发:此 thread 正在建立会话,请稍后重试。";
|
|
1655
|
+
const previous = threadState.get(replyKey);
|
|
1656
|
+
if (previous?.sessionId && previous.sessionId !== payload.originSession) {
|
|
1657
|
+
return "任务未派发:thread 已绑定另一会话,请使用新的 thread。";
|
|
1658
|
+
}
|
|
1659
|
+
threadState.set(replyKey, { ...previous, wakesAt: previous?.wakesAt ?? [], sessionId: payload.originSession });
|
|
1660
|
+
saveThreads(threadState);
|
|
1661
|
+
// Retain the binding on failure: a timeout does not prove non-delivery.
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1646
1664
|
const started = Date.now();
|
|
1647
1665
|
try {
|
|
1648
1666
|
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.
|
|
3
|
+
"version": "0.3.36",
|
|
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,9 @@
|
|
|
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:reasoning": "node lib/_selftest-reasoning.mjs",
|
|
64
|
+
"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",
|
|
63
65
|
"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
66
|
"build:sidecar": "bash scripts/build-sidecar.sh",
|
|
65
67
|
"verify:mirror": "node scripts/verify-lan-mirror.mjs",
|