dsh-netchat 0.0.0-stage → 0.3.19
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 +147 -2
- package/client/client.js +696 -0
- package/cordis.patch.yml +4 -0
- package/lib/host.mjs +234 -0
- package/lib/index.js +243 -0
- package/lib/runtime.mjs +9 -0
- package/lib/shared.mjs +28 -0
- package/package.json +34 -4
- package/shared/core/client.mjs +301 -0
- package/shared/core/consts.mjs +71 -0
- package/shared/core/datadir.mjs +92 -0
- package/shared/core/feishu-frame.mjs +190 -0
- package/shared/core/feishu.mjs +878 -0
- package/shared/core/hostbridge.mjs +115 -0
- package/shared/core/netchat.mjs +2542 -0
- package/shared/core/ops.mjs +803 -0
- package/shared/core/protocol.mjs +132 -0
- package/shared/core/util.mjs +184 -0
- package/shared/core/wsstream.mjs +204 -0
- package/shared/mcp/server.mjs +212 -0
- package/shared/skills/net-chat/SKILL.md +110 -0
- package/shared/ui/panel.html +2652 -0
package/cordis.patch.yml
ADDED
package/lib/host.mjs
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Connects the LAN service to the sessions and workspaces of this DeepSeek Harness.
|
|
3
|
+
*
|
|
4
|
+
* `core/netchat.mjs` talks to its host only through the hooks this module returns
|
|
5
|
+
* (`createSession`, `sendToSession`, `readSession`, ...), the same contract the
|
|
6
|
+
* ZCode extension implements in `extension/main.mjs`. Nothing in `core/` knows
|
|
7
|
+
* which host it is running on.
|
|
8
|
+
*
|
|
9
|
+
* The dsh services (`sessionController`, `workspaceRegistry`) arrive lazily: the
|
|
10
|
+
* plugin's `inject` lists only `webServer`, and the rest is read from `ctx.get`
|
|
11
|
+
* at call time, so a composition without them still boots the panel.
|
|
12
|
+
*/
|
|
13
|
+
import { randomUUID } from "node:crypto";
|
|
14
|
+
|
|
15
|
+
// Static, like every import of the shared core (see lib/shared.mjs).
|
|
16
|
+
import { NetChatError } from "../shared/core/util.mjs";
|
|
17
|
+
|
|
18
|
+
/** Service failures in dsh's vocabulary, in the codes `core/` and the panel already understand. */
|
|
19
|
+
const HOST_ERRORS = {
|
|
20
|
+
"session/not-found": ["not_found", "会话已不存在"],
|
|
21
|
+
"workspace/not-found": ["project_not_found", "工作区已不存在"],
|
|
22
|
+
"session/agent-busy": ["input_rejected", "会话正忙,没有接受这条输入"],
|
|
23
|
+
"session/model-unavailable": ["create_failed", "所选模型当前不可用:请在 DeepSeek Harness 里确认模型配置,或在 NetChat 设置里换一个默认模型"],
|
|
24
|
+
"session/provider-models-unavailable": ["create_failed", "没有可用的模型:请先在 DeepSeek Harness 里配置模型"],
|
|
25
|
+
"session/provider-credentials-unavailable": ["create_failed", "模型凭据不可用:请先在 DeepSeek Harness 里登录或配置 API key"],
|
|
26
|
+
"session/workspace-attach-failed": ["create_failed", "会话已创建,但没能加入工作区"],
|
|
27
|
+
"gateway/bad-request": ["invalid_input", "请求无效"],
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
function translate(error) {
|
|
31
|
+
const mapped = HOST_ERRORS[error?.code];
|
|
32
|
+
return mapped ? new NetChatError(mapped[0], mapped[1]) : error;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const wrap =
|
|
36
|
+
(action) =>
|
|
37
|
+
async (...args) => {
|
|
38
|
+
try {
|
|
39
|
+
return await action(...args);
|
|
40
|
+
} catch (error) {
|
|
41
|
+
throw translate(error);
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const textOf = (content) =>
|
|
46
|
+
(Array.isArray(content) ? content : [])
|
|
47
|
+
.filter((part) => part?.type === "text" && typeof part.text === "string")
|
|
48
|
+
.map((part) => part.text)
|
|
49
|
+
.join("\n");
|
|
50
|
+
|
|
51
|
+
/** A fresh request id per prompt; dsh uses it to make a retried prompt idempotent. */
|
|
52
|
+
const newRequestId = () => randomUUID();
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* How a model is named across NetChat: `provider/model`, the same shape ZCode's host uses, so
|
|
56
|
+
* the setting and the panel need not care which host they are for.
|
|
57
|
+
*/
|
|
58
|
+
const modelIdOf = (provider, model) => `${provider}/${model}`;
|
|
59
|
+
|
|
60
|
+
/** Splits a model id back into what dsh's selectModel takes; null when it is not of that shape. */
|
|
61
|
+
const selectionOf = (id) => {
|
|
62
|
+
const text = String(id ?? "");
|
|
63
|
+
const at = text.indexOf("/");
|
|
64
|
+
const provider = text.slice(0, at);
|
|
65
|
+
const model = text.slice(at + 1);
|
|
66
|
+
return at > 0 && model ? { provider, model } : null;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* @param ctx - the dsh plugin context; `sessionController` and `workspaceRegistry` are read on demand.
|
|
71
|
+
*/
|
|
72
|
+
export function createHost(ctx) {
|
|
73
|
+
const service = (name) => {
|
|
74
|
+
const value = ctx.get?.(name);
|
|
75
|
+
return value === undefined ? null : value;
|
|
76
|
+
};
|
|
77
|
+
const sessions = () => service("sessionController");
|
|
78
|
+
const workspaces = () => service("workspaceRegistry");
|
|
79
|
+
|
|
80
|
+
/** One row per workspace. Sessions may also be created from a bare cwd, which `execute` falls back to. */
|
|
81
|
+
async function listProjects() {
|
|
82
|
+
const registry = workspaces();
|
|
83
|
+
if (!registry) return { projects: [] };
|
|
84
|
+
return {
|
|
85
|
+
projects: registry.list().map((workspace) => ({
|
|
86
|
+
projectId: workspace.id,
|
|
87
|
+
sourceServerId: "dsh",
|
|
88
|
+
title: workspace.title || workspace.path,
|
|
89
|
+
// `execute` hands this object straight back to createSession.
|
|
90
|
+
project: { projectId: workspace.id, sourceServerId: "dsh", workspaceId: workspace.id, path: workspace.path },
|
|
91
|
+
})),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The models a session can be started with, from the host's own catalog (what its model
|
|
97
|
+
* picker shows). Providers that fail to answer are left out, as they are there; the group's
|
|
98
|
+
* name is kept as the provider, and the label shows it before the model's own name so two
|
|
99
|
+
* providers offering the same model id stay apart.
|
|
100
|
+
*/
|
|
101
|
+
async function listModels() {
|
|
102
|
+
const controller = sessions();
|
|
103
|
+
if (!controller || typeof controller.modelCatalog !== "function") return { models: [] };
|
|
104
|
+
const catalog = await controller.modelCatalog();
|
|
105
|
+
const models = [];
|
|
106
|
+
for (const group of Array.isArray(catalog?.groups) ? catalog.groups : []) {
|
|
107
|
+
for (const model of Array.isArray(group?.models) ? group.models : []) {
|
|
108
|
+
if (typeof model?.id !== "string" || !model.id || typeof group.id !== "string" || !group.id) continue;
|
|
109
|
+
models.push({ id: modelIdOf(group.id, model.id), label: `${group.name || group.id} · ${model.name || model.id}`, provider: String(group.name || group.id) });
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return { models };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** The prompt that starts a task, or continues a session, as one text part. */
|
|
116
|
+
const promptRequest = (sessionId, mode, prompt) => ({
|
|
117
|
+
requestId: newRequestId(),
|
|
118
|
+
sessionId,
|
|
119
|
+
mode,
|
|
120
|
+
content: [{ type: "text", text: prompt }],
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
return {
|
|
124
|
+
label: "dsh",
|
|
125
|
+
|
|
126
|
+
listProjects: wrap(listProjects),
|
|
127
|
+
listModels: wrap(listModels),
|
|
128
|
+
|
|
129
|
+
readSession: wrap(async (sessionId, { cursor, limit } = {}) => {
|
|
130
|
+
const controller = sessions();
|
|
131
|
+
if (!controller) throw new NetChatError("extension_required", "读取会话需要 DeepSeek Harness 的会话服务");
|
|
132
|
+
// dsh pages backwards from the end of the log; `beforeSeq` is where the previous page started.
|
|
133
|
+
const page = await controller.events(
|
|
134
|
+
{
|
|
135
|
+
address: { kind: "session", sessionId },
|
|
136
|
+
...(cursor ? { beforeSeq: Number(cursor) } : {}),
|
|
137
|
+
...(limit ? { maxMessages: limit } : {}),
|
|
138
|
+
},
|
|
139
|
+
new AbortController().signal,
|
|
140
|
+
);
|
|
141
|
+
const messages = [];
|
|
142
|
+
for (const record of Array.isArray(page?.records) ? page.records : []) {
|
|
143
|
+
const event = record?.event;
|
|
144
|
+
if (event?.type === "user/message" && event.data?.role === "user") {
|
|
145
|
+
messages.push({ role: "user", text: textOf(event.data.content) });
|
|
146
|
+
} else if (event?.type === "assistant/message" && event.data?.role === "assistant") {
|
|
147
|
+
messages.push({ role: "assistant", text: textOf(event.data.content) });
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const first = page?.records?.[0]?.event?.seq;
|
|
151
|
+
return {
|
|
152
|
+
messages,
|
|
153
|
+
...(page?.hasMore && Number.isInteger(first) ? { nextCursor: String(first) } : {}),
|
|
154
|
+
};
|
|
155
|
+
}),
|
|
156
|
+
|
|
157
|
+
sessionInfo: wrap(async (sessionId) => {
|
|
158
|
+
const controller = sessions();
|
|
159
|
+
if (!controller) return { title: "" };
|
|
160
|
+
const result = await controller.list();
|
|
161
|
+
const hit = (Array.isArray(result?.items) ? result.items : []).find((item) => item.sessionId === sessionId);
|
|
162
|
+
return { title: hit ? String(hit.title ?? "") : "", workspacePath: hit?.cwd ?? "" };
|
|
163
|
+
}),
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* The sessions a task could be run in. dsh lists every session at once, newest first; the
|
|
167
|
+
* ones of one workspace are told apart by the registry's own record of which sessions belong
|
|
168
|
+
* to it (the same list its sidebar shows). A project the registry does not know gives none.
|
|
169
|
+
*/
|
|
170
|
+
listSessions: wrap(async ({ project }) => {
|
|
171
|
+
const controller = sessions();
|
|
172
|
+
if (!controller || typeof controller.list !== "function") return { sessions: [] };
|
|
173
|
+
const result = await controller.list();
|
|
174
|
+
const items = Array.isArray(result?.items) ? result.items : [];
|
|
175
|
+
const wanted = project?.workspaceId ? workspaces()?.get(project.workspaceId) : null;
|
|
176
|
+
const ofProject = project ? (wanted ? new Set(wanted.sessionIds ?? []) : new Set()) : null;
|
|
177
|
+
return {
|
|
178
|
+
sessions: items
|
|
179
|
+
.filter((item) => item?.sessionId && (!ofProject || ofProject.has(item.sessionId)))
|
|
180
|
+
.map((item) => ({
|
|
181
|
+
sessionId: item.sessionId,
|
|
182
|
+
title: String(item.title ?? ""),
|
|
183
|
+
status: item.running ? "running" : "idle",
|
|
184
|
+
running: item.running === true,
|
|
185
|
+
})),
|
|
186
|
+
};
|
|
187
|
+
}),
|
|
188
|
+
|
|
189
|
+
createSession: wrap(async ({ project, prompt, title, model }) => {
|
|
190
|
+
const controller = sessions();
|
|
191
|
+
if (!controller) throw new NetChatError("extension_required", "执行任务需要 DeepSeek Harness 的会话服务");
|
|
192
|
+
const workspaceId = project?.workspaceId;
|
|
193
|
+
const created = await controller.create(workspaceId ? { workspaceId } : {});
|
|
194
|
+
const sessionId = created?.sessionId;
|
|
195
|
+
if (!sessionId) throw new NetChatError("create_failed", "DeepSeek Harness 没有返回新会话的 id");
|
|
196
|
+
// The model is chosen per session in dsh, and must be set before the first prompt is
|
|
197
|
+
// queued for that prompt to run with it. This is the host's own picker's call; as there,
|
|
198
|
+
// the host also remembers the choice as its default. An id of another shape (one meant for
|
|
199
|
+
// another host) is refused before the session is touched, as selectModel would reject it anyway.
|
|
200
|
+
if (model) {
|
|
201
|
+
const selection = selectionOf(model);
|
|
202
|
+
if (!selection || typeof controller.selectModel !== "function") {
|
|
203
|
+
throw new NetChatError("create_failed", `DeepSeek Harness 不能用模型「${model}」:请在 NetChat 设置里重新选择默认模型`);
|
|
204
|
+
}
|
|
205
|
+
await controller.selectModel({ sessionId, ...selection });
|
|
206
|
+
}
|
|
207
|
+
await controller.prompt(promptRequest(sessionId, "queue", prompt), new AbortController().signal);
|
|
208
|
+
// The title is cosmetic; a host that refuses it must not fail the task.
|
|
209
|
+
if (title) await controller.rename({ sessionId, title }).catch(() => {});
|
|
210
|
+
return { creation: "created", session: { sessionId } };
|
|
211
|
+
}),
|
|
212
|
+
|
|
213
|
+
// Puts a message in front of a session that already exists. `steer` (the default) delivers it
|
|
214
|
+
// at a running session's next input opportunity, for a message about the task it is on; `queue`
|
|
215
|
+
// waits for its next turn, for a new piece of work put into it (see core's executeInSession).
|
|
216
|
+
// Either keeps the session's own model and mode.
|
|
217
|
+
sendToSession: wrap(async ({ sessionId, prompt, mode = "steer" }) => {
|
|
218
|
+
const controller = sessions();
|
|
219
|
+
if (!controller) throw new NetChatError("extension_required", "需要 DeepSeek Harness 的会话服务");
|
|
220
|
+
const result = await controller.prompt(promptRequest(sessionId, mode === "queue" ? "queue" : "steer", prompt), new AbortController().signal);
|
|
221
|
+
return { admission: result?.accepted === true ? "accepted" : "unknown", delivery: mode === "queue" ? "queued" : "steer" };
|
|
222
|
+
}),
|
|
223
|
+
|
|
224
|
+
renameSession: wrap(async (sessionId, title) => {
|
|
225
|
+
const controller = sessions();
|
|
226
|
+
if (!controller) return;
|
|
227
|
+
await controller.rename({ sessionId, title });
|
|
228
|
+
}),
|
|
229
|
+
|
|
230
|
+
// The host half has no window. The browser half sees this call go past on the bridge
|
|
231
|
+
// (`net_chat_open_session`) and navigates to the session itself; here, success is the answer.
|
|
232
|
+
openSession: wrap(async (sessionId) => ({ sessionId })),
|
|
233
|
+
};
|
|
234
|
+
}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* NetChat for DeepSeek Harness, host half.
|
|
3
|
+
*
|
|
4
|
+
* Same shape as the ZCode extension (`extension/main.mjs`), on dsh's plugin
|
|
5
|
+
* contract: `createRuntime()` owns the LAN service, `createHost()` adapts dsh's
|
|
6
|
+
* session and workspace services to the hooks `core/` calls, and two exact routes
|
|
7
|
+
* on the web server carry the panel and its bridge:
|
|
8
|
+
*
|
|
9
|
+
* GET /__netchat/panel the panel page, run by the browser half inside a sandboxed iframe
|
|
10
|
+
* POST /__netchat/call `{ name, arguments }` -> the MCP `CallToolResult` of that op
|
|
11
|
+
*
|
|
12
|
+
* The browser half (`client/client.js`) is the iframe's parent and acts as the
|
|
13
|
+
* MCP Apps host the panel already speaks to; it forwards `tools/call` here.
|
|
14
|
+
*
|
|
15
|
+
* `webServer` is the only hard dependency. The session services arrive later
|
|
16
|
+
* (`createHost` reads them on demand) and the MCP manager is optional: a
|
|
17
|
+
* composition without it still runs the panel, the model just sees no tools.
|
|
18
|
+
*
|
|
19
|
+
* Runtime data lives in one directory for every host on the machine (`~/.netchat`,
|
|
20
|
+
* see core/datadir.mjs). The fixed UDP port lets exactly one process on the
|
|
21
|
+
* machine own the LAN presence; when ZCode and dsh are both running, the first
|
|
22
|
+
* one up owns it and the other borrows it through the same rendezvous file the
|
|
23
|
+
* ZCode extension and its MCP servers already share.
|
|
24
|
+
*
|
|
25
|
+
* Imports of the shared core are static throughout. dsh's hot reload replaces a
|
|
26
|
+
* changed module together with the modules that statically import it, up to the
|
|
27
|
+
* entry; a module reached only through a dynamic `import()` is left in the cache
|
|
28
|
+
* with its old version, which is how a hot upgrade once started the new entry
|
|
29
|
+
* against the old core. `activate()` also checks the core it was handed and
|
|
30
|
+
* stops the service itself when a later step fails, so a failed activation
|
|
31
|
+
* leaves nothing running.
|
|
32
|
+
*/
|
|
33
|
+
import { readFileSync } from "node:fs";
|
|
34
|
+
import { join } from "node:path";
|
|
35
|
+
|
|
36
|
+
// Every import of the shared core is static: dsh's hot reload replaces a changed module together
|
|
37
|
+
// with its static importers, and only then does the entry come up against the core of the same
|
|
38
|
+
// version (see lib/shared.mjs).
|
|
39
|
+
import { createRuntime } from "./runtime.mjs";
|
|
40
|
+
import { createHost } from "./host.mjs";
|
|
41
|
+
import { MCP_SERVER, PANEL_HTML, SHARED_ROOT } from "./shared.mjs";
|
|
42
|
+
import { ensureSharedRecords } from "../shared/core/datadir.mjs";
|
|
43
|
+
import { errorResult } from "../shared/core/ops.mjs";
|
|
44
|
+
import { FileLogger, isPlainObject } from "../shared/core/util.mjs";
|
|
45
|
+
|
|
46
|
+
export const name = "netchat";
|
|
47
|
+
export const inject = ["webServer"];
|
|
48
|
+
|
|
49
|
+
export const PANEL_ROUTE = "/__netchat/panel";
|
|
50
|
+
export const CALL_ROUTE = "/__netchat/call";
|
|
51
|
+
const CALL_BODY_LIMIT = 1024 * 1024;
|
|
52
|
+
|
|
53
|
+
function send(res, status, headers, body) {
|
|
54
|
+
res.writeHead(status, { "cache-control": "no-store", ...headers });
|
|
55
|
+
res.end(body);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const json = (res, status, value) =>
|
|
59
|
+
send(res, status, { "content-type": "application/json; charset=utf-8" }, JSON.stringify(value));
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The route is an exact registration, which dsh's own `/api` browser-trust fence never
|
|
63
|
+
* sees (it matches a prefix), so the fence is applied here: loopback peers only, a
|
|
64
|
+
* Host that is loopback, and no cross-site Origin.
|
|
65
|
+
*/
|
|
66
|
+
function admitted(req) {
|
|
67
|
+
const address = String(req.socket.remoteAddress ?? "").replace(/^::ffff:/i, "");
|
|
68
|
+
if (address !== "127.0.0.1" && address !== "::1") return false;
|
|
69
|
+
const host = String(req.headers.host ?? "").toLowerCase().replace(/:\d+$/, "").replace(/^\[|\]$/g, "");
|
|
70
|
+
if (host && !/^(localhost|127\.0\.0\.1|::1)$/.test(host)) return false;
|
|
71
|
+
return req.headers["sec-fetch-site"] !== "cross-site";
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function readJsonBody(req, limit) {
|
|
75
|
+
const declared = Number(req.headers["content-length"]);
|
|
76
|
+
if (Number.isFinite(declared) && declared > limit) return null;
|
|
77
|
+
const chunks = [];
|
|
78
|
+
let size = 0;
|
|
79
|
+
for await (const chunk of req) {
|
|
80
|
+
size += chunk.length;
|
|
81
|
+
if (size > limit) return null;
|
|
82
|
+
chunks.push(chunk);
|
|
83
|
+
}
|
|
84
|
+
try {
|
|
85
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
|
|
86
|
+
} catch {
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Registers one route, taking the path over from an earlier instance of this plugin if it left
|
|
93
|
+
* a route there. dsh refuses a second registration of the same path — rightly, as a collision
|
|
94
|
+
* is a misconfiguration — but this plugin before 0.2.16 never took its routes down, so on a dsh
|
|
95
|
+
* that kept running while the plugin was upgraded, the old routes are still in the table and
|
|
96
|
+
* the new instance would fail to start at all. Both paths are this plugin's own namespace, so
|
|
97
|
+
* whatever is on them is ours to replace. If the table cannot be reached (another host
|
|
98
|
+
* version), the route is skipped with a warning and the rest of the plugin still comes up.
|
|
99
|
+
*/
|
|
100
|
+
function mount(webServer, route) {
|
|
101
|
+
try {
|
|
102
|
+
return webServer.register(route);
|
|
103
|
+
} catch (error) {
|
|
104
|
+
if (!/duplicate .* route/.test(String(error?.message ?? error))) throw error;
|
|
105
|
+
}
|
|
106
|
+
const table = webServer.exact;
|
|
107
|
+
if (!(table instanceof Map) || !table.has(route.path)) {
|
|
108
|
+
console.warn(`netchat: route ${route.path} is already taken and cannot be replaced; it is not mounted`);
|
|
109
|
+
return () => {};
|
|
110
|
+
}
|
|
111
|
+
table.set(route.path, route);
|
|
112
|
+
return () => { if (table.get(route.path) === route) table.delete(route.path); };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Mounts the panel and bridge routes on a web server; exposed for the tests.
|
|
116
|
+
* Returns what takes them down again, so a reloaded plugin does not register them twice. */
|
|
117
|
+
export function registerRoutes(webServer, runtime) {
|
|
118
|
+
const disposers = [];
|
|
119
|
+
disposers.push(
|
|
120
|
+
mount(webServer, {
|
|
121
|
+
kind: "exact",
|
|
122
|
+
path: PANEL_ROUTE,
|
|
123
|
+
handler: (req, res) => {
|
|
124
|
+
if (!admitted(req)) return send(res, 403, { "content-type": "text/plain; charset=utf-8" }, "forbidden");
|
|
125
|
+
// Read per request so an edited panel shows up on reload during development.
|
|
126
|
+
let html;
|
|
127
|
+
try {
|
|
128
|
+
html = readFileSync(PANEL_HTML, "utf8");
|
|
129
|
+
} catch (error) {
|
|
130
|
+
return send(res, 500, { "content-type": "text/plain; charset=utf-8" }, `panel missing: ${error.message}`);
|
|
131
|
+
}
|
|
132
|
+
return send(res, 200, { "content-type": "text/html; charset=utf-8" }, html);
|
|
133
|
+
},
|
|
134
|
+
}),
|
|
135
|
+
);
|
|
136
|
+
|
|
137
|
+
disposers.push(
|
|
138
|
+
mount(webServer, {
|
|
139
|
+
kind: "exact",
|
|
140
|
+
path: CALL_ROUTE,
|
|
141
|
+
handler: async (req, res) => {
|
|
142
|
+
// One connection per call: a long poll holds the socket for up to 25 s, and the
|
|
143
|
+
// service may move to another process between calls.
|
|
144
|
+
res.setHeader("connection", "close");
|
|
145
|
+
if (!admitted(req)) return json(res, 403, { ok: false, reason: "forbidden" });
|
|
146
|
+
if (req.method !== "POST") return json(res, 405, { ok: false, reason: "method_not_allowed" });
|
|
147
|
+
if (!String(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) {
|
|
148
|
+
return json(res, 415, { ok: false, reason: "unsupported_media_type" });
|
|
149
|
+
}
|
|
150
|
+
const body = await readJsonBody(req, CALL_BODY_LIMIT);
|
|
151
|
+
if (body === null) return json(res, 413, { ok: false, reason: "too_large_or_invalid_json" });
|
|
152
|
+
if (!isPlainObject(body) || typeof body.name !== "string" || !body.name) {
|
|
153
|
+
return json(res, 400, { ok: false, reason: "invalid_call" });
|
|
154
|
+
}
|
|
155
|
+
try {
|
|
156
|
+
// Already an MCP CallToolResult; the bridge hands it back as the JSON-RPC result.
|
|
157
|
+
return json(res, 200, await runtime.call(body.name, body.arguments ?? {}, body.meta ?? {}));
|
|
158
|
+
} catch (error) {
|
|
159
|
+
return json(res, 200, errorResult(error));
|
|
160
|
+
}
|
|
161
|
+
},
|
|
162
|
+
}),
|
|
163
|
+
);
|
|
164
|
+
// A disposer that calls back whatever the registrations returned, in case a host gives none.
|
|
165
|
+
return () => { for (const dispose of disposers.splice(0)) dispose?.(); };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* What `createRuntime()` must hand back. Checked before anything is started: if the entry was
|
|
170
|
+
* evaluated against a `core/` of another version — what a hot upgrade used to do, see
|
|
171
|
+
* lib/shared.mjs — the first symptom would otherwise be a call on something that is not there.
|
|
172
|
+
*/
|
|
173
|
+
const RUNTIME_API = ["call", "ensure", "expose", "stop"];
|
|
174
|
+
|
|
175
|
+
export async function apply(ctx) {
|
|
176
|
+
// One directory for the records, whoever runs the service (see core/datadir.mjs). The first
|
|
177
|
+
// run copies what ~/.dsh/netchat or the ZCode plugin's directory already holds.
|
|
178
|
+
const { dir: dataDir, migratedFrom } = ensureSharedRecords();
|
|
179
|
+
if (migratedFrom) ctx.logger.info(`netchat: records copied from ${migratedFrom} to ${dataDir}`);
|
|
180
|
+
const logger = new FileLogger(join(dataDir, "netchat.log"));
|
|
181
|
+
const runtime = await createRuntime({ role: "extension", dataDir, logger, host: createHost(ctx) });
|
|
182
|
+
await activate(ctx, runtime);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Starts a runtime under the plugin's lifecycle — its service, the two routes and the MCP
|
|
187
|
+
* server — and takes the service down again when a later step fails.
|
|
188
|
+
*
|
|
189
|
+
* Two things here are about a hot upgrade on a running Desktop (0.2.17 -> 0.3.9). The
|
|
190
|
+
* regression tests in tests/dsh-package.test.mjs are written against this function so that they
|
|
191
|
+
* can hand it a runtime of their own.
|
|
192
|
+
*
|
|
193
|
+
* The service's cleanup is registered before the service is started, not after: the disposer
|
|
194
|
+
* has to be in place when the start is issued, because a start that is under way and a step that
|
|
195
|
+
* then throws leave a service nobody can reach. That service kept the LAN ports and went on
|
|
196
|
+
* announcing the old version while the plugin showed as failed, and disabling the plugin could
|
|
197
|
+
* not stop it. The catch is for the case where even that registration did not happen, or where
|
|
198
|
+
* the host does not dispose a plugin whose apply() failed.
|
|
199
|
+
*/
|
|
200
|
+
export async function activate(ctx, runtime) {
|
|
201
|
+
const missing = RUNTIME_API.filter((name) => typeof runtime[name] !== "function");
|
|
202
|
+
if (missing.length > 0) {
|
|
203
|
+
throw new Error(
|
|
204
|
+
`netchat: the LAN service of this version is not the one that was loaded (createRuntime() gives no ${missing.join(", ")}). `
|
|
205
|
+
+ "This happens when DeepSeek Harness hot-reloads the plugin while modules of the previous version stay cached: "
|
|
206
|
+
+ "quit DeepSeek Harness completely and start it again.",
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
// Returned, not fired and forgotten: the host awaits a plugin's disposers, and on a reload the
|
|
210
|
+
// instance that comes next needs the LAN ports this one gives up.
|
|
211
|
+
ctx.effect(() => () => runtime.stop(), "netchat: service");
|
|
212
|
+
try {
|
|
213
|
+
// The panel's first call acquires the service; a port conflict must not keep the panel from opening.
|
|
214
|
+
runtime.ensure().catch((error) => ctx.logger.warn(`netchat: service did not start: ${error.message}`));
|
|
215
|
+
// Let the other host on this machine (ZCode's plugin) use dsh's workspaces and sessions when it
|
|
216
|
+
// owns the shared service; and the other way round, dsh's panel uses ZCode's through its bridge.
|
|
217
|
+
runtime.expose().catch((error) => ctx.logger.warn(`netchat: host bridge: ${error?.message ?? error}`));
|
|
218
|
+
// The routes go with the plugin: a reload applies this again, and a second registration of the
|
|
219
|
+
// same path is refused by the host ("duplicate exact route").
|
|
220
|
+
ctx.effect(() => registerRoutes(ctx.webServer, runtime), "netchat: routes");
|
|
221
|
+
|
|
222
|
+
// The same stdio server ZCode runs, so the model gets the same net_chat_* tools.
|
|
223
|
+
// Registered under the plugin's lifecycle: disabling the plugin withdraws them.
|
|
224
|
+
ctx.inject(["mcpManager"], (managerCtx) => {
|
|
225
|
+
// The server finds the records by itself (core/datadir.mjs); only the test port shift is
|
|
226
|
+
// passed on, so the suite can run both hosts on shifted ports.
|
|
227
|
+
// The server is started by dsh, so its calls are for dsh's host; it finds that out from this.
|
|
228
|
+
const env = { NETCHAT_HOST_LABEL: "dsh" };
|
|
229
|
+
if (process.env.NETCHAT_TEST_PORTS) env.NETCHAT_TEST_PORTS = process.env.NETCHAT_TEST_PORTS;
|
|
230
|
+
managerCtx.effect(
|
|
231
|
+
() => managerCtx.mcpManager.register("net-chat", { transport: "stdio", command: process.execPath, args: [MCP_SERVER], env }),
|
|
232
|
+
"netchat: mcp server",
|
|
233
|
+
);
|
|
234
|
+
});
|
|
235
|
+
} catch (error) {
|
|
236
|
+
// stop() waits for a start that is still under way and then takes the service down, which
|
|
237
|
+
// nothing the host disposes can do.
|
|
238
|
+
await runtime.stop().catch(() => {});
|
|
239
|
+
throw error;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
ctx.logger.info(`netchat: ready (shared root ${SHARED_ROOT})`);
|
|
243
|
+
}
|
package/lib/runtime.mjs
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The LAN service, from the shared core. Everything here is the same `core/` the
|
|
3
|
+
* ZCode plugin runs; only the `host` object differs, and that is `host.mjs`.
|
|
4
|
+
*
|
|
5
|
+
* The import is static on purpose: it puts this file between `core/client.mjs`
|
|
6
|
+
* and the plugin entry in the module graph dsh's HMR walks, so a hot upgrade
|
|
7
|
+
* replaces the core with the entry instead of leaving the old one cached.
|
|
8
|
+
*/
|
|
9
|
+
export { createRuntime } from "../shared/core/client.mjs";
|
package/lib/shared.mjs
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the host-neutral parts of NetChat live, relative to this package.
|
|
3
|
+
*
|
|
4
|
+
* In the repository the dsh package sits beside the ZCode plugin and borrows
|
|
5
|
+
* `core/`, `mcp/`, `ui/` and `skills/` from it; when packed, the same files are
|
|
6
|
+
* copied under `shared/` so the package is self-contained, which is what
|
|
7
|
+
* `dsh plugin add` needs.
|
|
8
|
+
*
|
|
9
|
+
* The code reaches them through one path in both layouts — static imports of
|
|
10
|
+
* `../shared/...` — and in the repository `shared/` is a mirror of the ZCode
|
|
11
|
+
* plugin that the test suite refreshes before it loads anything
|
|
12
|
+
* (`scripts/shared.mjs`). It used to be resolved at run time instead, with
|
|
13
|
+
* `await import(sharedUrl(...))`, and that broke hot upgrades: dsh's HMR
|
|
14
|
+
* replaces a changed module together with the modules that statically import
|
|
15
|
+
* it, so a core file reached only through a dynamic `import()` stayed cached
|
|
16
|
+
* with its old version while the entry was re-evaluated against it
|
|
17
|
+
* (`runtime.expose is not a function`, 0.2.17 -> 0.3.9).
|
|
18
|
+
*/
|
|
19
|
+
import { join } from "node:path";
|
|
20
|
+
import { fileURLToPath } from "node:url";
|
|
21
|
+
|
|
22
|
+
const HERE = fileURLToPath(new URL(".", import.meta.url));
|
|
23
|
+
const SHARED_ROOT = join(HERE, "..", "shared");
|
|
24
|
+
|
|
25
|
+
export { SHARED_ROOT };
|
|
26
|
+
|
|
27
|
+
export const PANEL_HTML = join(SHARED_ROOT, "ui", "panel.html");
|
|
28
|
+
export const MCP_SERVER = join(SHARED_ROOT, "mcp", "server.mjs");
|
package/package.json
CHANGED
|
@@ -1,6 +1,36 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-netchat",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.3.19",
|
|
4
|
+
"description": "NetChat for DeepSeek Harness: discover other agents on the LAN, hand tasks to them, and keep a task moving through its thread. Shares its core with the ZCode plugin.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "lib/index.js",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./lib/index.js",
|
|
10
|
+
"./client": "./client/client.js",
|
|
11
|
+
"./package.json": "./package.json"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"lib",
|
|
15
|
+
"client",
|
|
16
|
+
"shared",
|
|
17
|
+
"cordis.patch.yml",
|
|
18
|
+
"README.md"
|
|
19
|
+
],
|
|
20
|
+
"dsh": {
|
|
21
|
+
"engines": {
|
|
22
|
+
"dsh": ">=0.2.2-rc.5 <0.3.0"
|
|
23
|
+
},
|
|
24
|
+
"bundle": {
|
|
25
|
+
"patch": "./cordis.patch.yml"
|
|
26
|
+
},
|
|
27
|
+
"client": {
|
|
28
|
+
"platform": "web",
|
|
29
|
+
"immediately": true,
|
|
30
|
+
"inject": ["react-dom", "@deepseek-ai/dsh-client-ui-layout", "@deepseek-ai/dsh-client-ui-sidebar", "@deepseek-ai/dsh-client-ui-workspace", "@deepseek-ai/dsh-client-ui-session", "@deepseek-ai/dsh-client-ui-session-status", "@deepseek-ai/dsh-client-ui-sidebar-right", "@deepseek-ai/dsh-client-ui-session-panel"]
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"peerDependencies": {
|
|
34
|
+
"@deepseek-ai/cordis": "~4.1.0"
|
|
35
|
+
}
|
|
36
|
+
}
|