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.
@@ -0,0 +1,301 @@
1
+ import { existsSync, readFileSync, unlinkSync } from "node:fs";
2
+ import os from "node:os";
3
+ import { join } from "node:path";
4
+ import * as C from "./consts.mjs";
5
+ import { serveHost } from "./hostbridge.mjs";
6
+ import { NetChat } from "./netchat.mjs";
7
+ import { createOps, errorResult, toolDefinitions } from "./ops.mjs";
8
+ import { NetChatError, describeError, fetchJson, writeJsonAtomic } from "./util.mjs";
9
+
10
+ /**
11
+ * Wherever the service is, the other processes on this machine find it through a file in the
12
+ * temp directory: both the extension host and the MCP servers can locate it without assuming
13
+ * they were handed the same data directory.
14
+ */
15
+ export function rendezvousPath() {
16
+ const who = typeof process.getuid === "function" ? String(process.getuid()) : "user";
17
+ // Tests keep their own rendezvous file, so they cannot displace a real installation's service.
18
+ return join(os.tmpdir(), `zcode-net-chat-${who}${C.TEST_MODE ? "-test" : ""}`, "service.json");
19
+ }
20
+
21
+ export function readRendezvous() {
22
+ try {
23
+ const info = JSON.parse(readFileSync(rendezvousPath(), "utf8"));
24
+ return Number.isInteger(info?.port) && typeof info.token === "string" ? info : null;
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+
30
+ export async function probeService(timeoutMs = 1500) {
31
+ const info = readRendezvous();
32
+ if (!info) return null;
33
+ const outcome = await fetchJson(`http://127.0.0.1:${info.port}/__local/health`, {
34
+ headers: { authorization: `Bearer ${info.token}` },
35
+ timeoutMs,
36
+ retries: 1,
37
+ }).catch(() => null);
38
+ return outcome?.ok && outcome.data?.ok === true ? { ...outcome.data, token: info.token } : null;
39
+ }
40
+
41
+ export function removeRendezvous() {
42
+ try {
43
+ const info = readRendezvous();
44
+ if (info?.pid === process.pid && existsSync(rendezvousPath())) unlinkSync(rendezvousPath());
45
+ } catch {
46
+ // A stale file is harmless: the next probe fails and it gets overwritten.
47
+ }
48
+ }
49
+
50
+ async function requestTakeover(target) {
51
+ const outcome = await fetchJson(`http://127.0.0.1:${target.port}/__local/takeover`, {
52
+ method: "POST",
53
+ body: JSON.stringify({ role: "extension" }),
54
+ headers: { authorization: `Bearer ${target.token}` },
55
+ timeoutMs: 3000,
56
+ retries: 1,
57
+ }).catch(() => null);
58
+ if (!outcome?.ok) {
59
+ throw new NetChatError("takeover_refused", `当前的服务进程拒绝了接管${outcome ? `(${outcome.status})` : ""}`);
60
+ }
61
+ }
62
+
63
+ async function isAlive(target) {
64
+ const outcome = await fetchJson(`http://127.0.0.1:${target.port}/__local/health`, {
65
+ headers: { authorization: `Bearer ${target.token}` },
66
+ timeoutMs: 1200,
67
+ retries: 1,
68
+ }).catch(() => null);
69
+ return outcome?.ok === true;
70
+ }
71
+
72
+ /** A raw `bind EADDRINUSE 0.0.0.0:47921` helps nobody reading the panel; say what it means. */
73
+ function describeBindFailure(error) {
74
+ const port = String(error?.port ?? "");
75
+ const what = port === String(C.UDP_PORT) ? `局域网发现端口 UDP ${C.UDP_PORT}` : `NetChat 的网络端口 ${port || "(未知)"}`;
76
+ if (error?.code === "EADDRINUSE") {
77
+ return new NetChatError("port_in_use", `${what} 已被其他程序占用,本机暂时无法加入局域网。换一个网络或关闭占用该端口的程序后,重启 ZCode 即可。`);
78
+ }
79
+ if (error?.code === "EACCES" || error?.code === "EPERM") {
80
+ return new NetChatError("port_denied", `${what} 被系统保留或无权监听(${error.code}),本机暂时无法加入局域网。`);
81
+ }
82
+ return error;
83
+ }
84
+
85
+ /**
86
+ * Owns the LAN service or borrows the one another process already owns.
87
+ *
88
+ * The extension host is the preferred owner because it is a single long-lived process with
89
+ * access to sessions. MCP servers are per-session, so they only step in when no extension is
90
+ * running, and hand the service back when the extension asks.
91
+ */
92
+ export async function createRuntime({ role, dataDir, logger, host = {} }) {
93
+ let owner = null;
94
+ let remote = null;
95
+ let acquiring = null;
96
+ let stopped = false;
97
+ // Who this process's host is, for the service to use when a call names no host. An MCP server
98
+ // has no host of its own: it is started by one (ZCode's extension or dsh's plugin), which is
99
+ // the host its calls are for — dsh passes its label in NETCHAT_HOST_LABEL, ZCode's is the
100
+ // default. Only a process with a real host speaks in its own name.
101
+ const hostLabel = role === "mcp" ? process.env.NETCHAT_HOST_LABEL || "extension" : host.label || "extension";
102
+ let bridge = null;
103
+
104
+ /** Opens this process's host to the service when another process owns it (see hostbridge.mjs). */
105
+ async function openBridge() {
106
+ if (bridge || stopped) return bridge;
107
+ if (typeof host.listProjects !== "function" && typeof host.createSession !== "function") return null;
108
+ bridge = await serveHost({ host, label: hostLabel, dataDir, logger });
109
+ return bridge;
110
+ }
111
+
112
+ async function startOwner({ takeover = false } = {}) {
113
+ let displaced = null;
114
+ const existing = await probeService();
115
+ if (existing) {
116
+ if (!(takeover && existing.owner === "mcp" && role === "extension")) {
117
+ remote = existing;
118
+ return false;
119
+ }
120
+ await requestTakeover(existing);
121
+ displaced = existing.pid;
122
+ }
123
+ const netChat = new NetChat({ dir: dataDir, logger, host });
124
+ netChat.ops = createOps(netChat);
125
+ // The fixed UDP port allows exactly one owner. A displaced process releases its sockets a
126
+ // moment after acknowledging, so keep trying; if some other process wins the race fairly,
127
+ // borrow its service instead.
128
+ const deadline = Date.now() + 5000;
129
+ for (;;) {
130
+ try {
131
+ await netChat.start();
132
+ break;
133
+ } catch (error) {
134
+ await netChat.stop().catch(() => {});
135
+ if (error?.code !== "EADDRINUSE" || Date.now() > deadline) throw describeBindFailure(error);
136
+ const winner = await probeService(800);
137
+ if (winner && winner.pid !== displaced) {
138
+ remote = winner;
139
+ logger.warn(`service is owned by another process (pid ${winner.pid}); acting as a client`);
140
+ return false;
141
+ }
142
+ await new Promise((resolve) => setTimeout(resolve, 250));
143
+ }
144
+ }
145
+ owner = netChat;
146
+ netChat.onTakeover = () => void release("takeover");
147
+ await writeJsonAtomic(rendezvousPath(), {
148
+ port: netChat.port,
149
+ token: netChat.token,
150
+ owner: role,
151
+ pid: process.pid,
152
+ startedAt: new Date().toISOString(),
153
+ }).catch(() => {});
154
+ logger.info(`service owned by ${role} (pid ${process.pid}, http ${netChat.port})`);
155
+ return true;
156
+ }
157
+
158
+ async function release(reason) {
159
+ const netChat = owner;
160
+ owner = null;
161
+ remote = null;
162
+ if (!netChat) return;
163
+ removeRendezvous();
164
+ await netChat.stop().catch((error) => logger.warn(`stop: ${describeError(error)}`));
165
+ logger.info(`service released (${reason})`);
166
+ }
167
+
168
+ /** Makes sure a service exists and this runtime can reach it. Resolves to true when this process owns it. */
169
+ async function ensure() {
170
+ if (stopped) throw new NetChatError("stopped", "NetChat 服务已停止");
171
+ if (owner) return true;
172
+ if (!acquiring) {
173
+ acquiring = (async () => {
174
+ if (remote && (await isAlive(remote))) return false;
175
+ remote = null;
176
+ return startOwner({ takeover: role === "extension" });
177
+ })().finally(() => {
178
+ acquiring = null;
179
+ });
180
+ }
181
+ return acquiring;
182
+ }
183
+
184
+ async function localCall(target, name, args, meta, timeoutMs) {
185
+ let outcome;
186
+ try {
187
+ // Deliberately not retried: the operation may already have run when the connection drops.
188
+ outcome = await fetchJson(`http://127.0.0.1:${target.port}/__local/call`, {
189
+ method: "POST",
190
+ body: JSON.stringify({ op: name, args, meta }),
191
+ headers: { authorization: `Bearer ${target.token}` },
192
+ timeoutMs,
193
+ });
194
+ } catch (error) {
195
+ // Forget the service so the next call elects a new owner.
196
+ remote = null;
197
+ if (error instanceof NetChatError) throw error;
198
+ throw new NetChatError("service_unavailable", `NetChat 服务暂不可用:${describeError(error)}`);
199
+ }
200
+ const data = outcome.data;
201
+ if (!outcome.ok || data?.ok !== true) {
202
+ if (outcome.status === 401) remote = null;
203
+ if (data?.error?.code && data.error.message) {
204
+ const { code, message, ...extra } = data.error;
205
+ throw new NetChatError(code, message, extra);
206
+ }
207
+ throw new NetChatError("local_call_failed", `本地 NetChat 服务返回 ${outcome.status}`);
208
+ }
209
+ return data.result;
210
+ }
211
+
212
+ /**
213
+ * The meta a call goes out with: the caller's own, plus this process's host label where none is
214
+ * named — but only when the call travels to another process. A call the owner handles itself
215
+ * carries no label: the service then uses its own host, which is the right one for a caller
216
+ * that did not say otherwise.
217
+ */
218
+ const withHost = (meta, local) => {
219
+ if (local) return meta;
220
+ return { ...meta, hostLabel: typeof meta.hostLabel === "string" && meta.hostLabel ? meta.hostLabel : hostLabel };
221
+ };
222
+
223
+ async function call(name, args = {}, meta = {}, options = {}) {
224
+ await ensure();
225
+ // Another process may own the service; it reaches this process's host through the bridge.
226
+ if (!owner) await openBridge();
227
+ const callMeta = withHost(meta, Boolean(owner));
228
+ try {
229
+ return owner
230
+ ? await owner.ops.call(name, args, callMeta, options)
231
+ : await localCall(remote, name, args, callMeta, options.timeoutMs ?? C.LOCAL_TIMEOUT_MS);
232
+ } catch (error) {
233
+ // A client that lost its service re-elects once before giving up.
234
+ if (error.code !== "service_unavailable" || stopped) throw error;
235
+ remote = null;
236
+ await ensure();
237
+ const retryMeta = withHost(meta, Boolean(owner));
238
+ return owner
239
+ ? await owner.ops.call(name, args, retryMeta, options)
240
+ : await localCall(remote, name, args, retryMeta, options.timeoutMs ?? C.LOCAL_TIMEOUT_MS);
241
+ }
242
+ }
243
+
244
+ return {
245
+ role,
246
+ call,
247
+ ensure,
248
+ /** Opens this process's host to the service now, so another process's owner can reach it
249
+ * before this one makes a call (an MCP server started by this host may call first). */
250
+ expose: openBridge,
251
+ get owner() {
252
+ return owner;
253
+ },
254
+ get mode() {
255
+ return owner ? "owner" : remote ? "client" : "none";
256
+ },
257
+ get serviceOwner() {
258
+ return owner ? role : (remote?.owner ?? null);
259
+ },
260
+ /** Tools for the extension view: same operations, routed like any other caller. */
261
+ viewTools() {
262
+ const table = toolDefinitions().filter((tool) => tool.visibility.includes("app"));
263
+ return Object.fromEntries(
264
+ table.map((tool) => [
265
+ tool.name,
266
+ {
267
+ description: tool.description,
268
+ inputSchema: tool.inputSchema,
269
+ run: async (args, view) => {
270
+ try {
271
+ return await call(tool.name, args ?? {}, metaFromView(view));
272
+ } catch (error) {
273
+ return errorResult(error);
274
+ }
275
+ },
276
+ },
277
+ ]),
278
+ );
279
+ },
280
+ async stop() {
281
+ stopped = true;
282
+ // A start may still be under way (the panel's first call acquires the service, and the
283
+ // plugin can be stopped before that finishes). Setting `stopped` does not undo it: the
284
+ // start would complete afterwards and leave a service running that nobody owns. So wait
285
+ // for it, then release what it started.
286
+ if (acquiring) await acquiring.catch(() => {});
287
+ await release("stop");
288
+ // The bridge goes with the process: its address file names this pid and is removed with it.
289
+ await bridge?.close();
290
+ bridge = null;
291
+ },
292
+ get hostLabel() {
293
+ return hostLabel;
294
+ },
295
+ };
296
+ }
297
+
298
+ function metaFromView(view) {
299
+ const session = view?.scope?.kind === "session" ? view.scope : null;
300
+ return { sessionId: session?.sessionId ?? "", workspacePath: session?.workspace?.workspacePath ?? "" };
301
+ }
@@ -0,0 +1,71 @@
1
+ // Shared constants for the NetChat plugin.
2
+ export const PROTOCOL = 1;
3
+ export const VERSION = "0.3.19";
4
+
5
+ // The test suite shifts every port by a fixed amount so that it never binds the ports a real
6
+ // installation on this machine owns, and never announces itself to real installations on the LAN.
7
+ // A value that is not a usable shift throws: silently falling back to the real ports is exactly
8
+ // what this must prevent.
9
+ const REAL_UDP_PORT = 47921;
10
+ const REAL_HTTP_PORT = 47920;
11
+ const HTTP_PORT_SPAN = 12;
12
+ const rawShift = Number(process.env.NETCHAT_TEST_PORTS ?? 0);
13
+ const TEST_SHIFT = Number.isInteger(rawShift) && rawShift !== 0 ? rawShift : 0;
14
+ if (process.env.NETCHAT_TEST_PORTS !== undefined && TEST_SHIFT === 0) {
15
+ throw new Error(`NETCHAT_TEST_PORTS must be a non-zero integer, got ${JSON.stringify(process.env.NETCHAT_TEST_PORTS)}`);
16
+ }
17
+ if (TEST_SHIFT) {
18
+ const lowest = Math.min(REAL_UDP_PORT, REAL_HTTP_PORT) + TEST_SHIFT;
19
+ const highest = Math.max(REAL_UDP_PORT, REAL_HTTP_PORT) + TEST_SHIFT + HTTP_PORT_SPAN - 1;
20
+ if (lowest < 1024 || highest > 65535) {
21
+ throw new Error(`NETCHAT_TEST_PORTS=${TEST_SHIFT} puts the ports outside ${lowest}..${highest}; choose a shift that keeps them within 1024..65535`);
22
+ }
23
+ }
24
+ export const TEST_MODE = TEST_SHIFT !== 0;
25
+
26
+ // Fixed discovery port is the single-owner marker; the HTTP port may drift when occupied.
27
+ export const UDP_PORT = REAL_UDP_PORT + TEST_SHIFT;
28
+ export const HTTP_PORT = REAL_HTTP_PORT + TEST_SHIFT;
29
+ export const HTTP_PORT_ATTEMPTS = HTTP_PORT_SPAN;
30
+
31
+ export const PEER_TTL_MS = 20_000;
32
+ export const ANNOUNCE_INTERVAL_MS = 5_000;
33
+ export const GOSSIP_INTERVAL_MS = 15_000;
34
+ export const PRUNE_INTERVAL_MS = 3_000;
35
+
36
+ export const MAX_ENVELOPE_BYTES = 768 * 1024;
37
+ export const MAX_DATAGRAM_BYTES = 2048;
38
+ export const MAX_ID_CHARS = 80;
39
+ export const MAX_NAME_CHARS = 60;
40
+ export const MAX_ROLE_CHARS = 40;
41
+ export const MAX_TITLE_CHARS = 200;
42
+ export const MAX_BODY_CHARS = 60_000;
43
+ export const MAX_REPLY_CHARS = 16_000;
44
+ export const MAX_OPTION_COUNT = 12;
45
+ export const MAX_OPTION_CHARS = 100;
46
+ export const MAX_NOTE_CHARS = 4_000;
47
+ export const MAX_HINT_CHARS = 1_024;
48
+ // What a directory goes by among teammates' machines (core/netchat.mjs, setProjectName).
49
+ export const MAX_PROJECT_NAME_CHARS = 60;
50
+ export const MAX_TRANSCRIPT_MESSAGES = 2_000;
51
+ export const MAX_TRANSCRIPT_CHARS = 300_000;
52
+ export const MAX_TRANSCRIPT_TEXT_CHARS = 8_000;
53
+ export const MAX_SESSION_TITLE_CHARS = 80;
54
+ // A model as the host names it: the id is opaque here (ZCode's is "provider/model"), the label is what the sheet shows.
55
+ export const MAX_MODEL_ID_CHARS = 200;
56
+ export const MAX_MODEL_LABEL_CHARS = 120;
57
+ // How long the Feishu notice that a task finished may be, in characters: a glance, not a report.
58
+ export const FEISHU_DONE_CHARS = 100;
59
+
60
+ export const INBOX_LIMIT = 500;
61
+ export const OUTBOX_LIMIT = 500;
62
+ export const SEEN_LIMIT = 4_000;
63
+ export const DELIVER_TIMEOUT_MS = 8_000;
64
+ export const LOCAL_TIMEOUT_MS = 120_000;
65
+ export const RATE_LIMIT_WINDOW_MS = 60_000;
66
+ export const RATE_LIMIT_MAX = 90;
67
+
68
+ // A task is the only content an agent can receive; replies and receipts are feedback on a task.
69
+ export const KINDS = ["task", "reply", "receipt"];
70
+ export const RECEIPT_STATUSES = ["accepted", "started", "declined", "failed", "done"];
71
+ export const PRIORITIES = ["normal", "high"];
@@ -0,0 +1,92 @@
1
+ // Where NetChat keeps its records on this machine, whichever host is running it.
2
+ //
3
+ // The ZCode plugin and the DeepSeek Harness plugin share one LAN service (one fixed port, one
4
+ // rendezvous file), so they must share one set of records too. Each used to pick a directory of
5
+ // its own: the ZCode plugin one under its own data path, the dsh plugin ~/.dsh/netchat. Whichever
6
+ // host started first owned the service and showed the panel its own directory — which, for the
7
+ // one that had just been installed, was empty, and the user's history looked gone.
8
+ //
9
+ // So the directory is now fixed and belongs to neither host: ~/.netchat. The first time a host
10
+ // finds it without records, it copies them from wherever an older version left them (copy, not
11
+ // move: the old files stay in place, so nothing is lost if this goes wrong).
12
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
13
+ import { homedir } from "node:os";
14
+ import { join } from "node:path";
15
+
16
+ import * as C from "./consts.mjs";
17
+
18
+ /** The files that make up the records. The control token and the log are not among them. */
19
+ export const RECORD_FILES = ["identity.json", "settings.json", "peers.json", "hidden.json", "inbox.json", "outbox.json", "seen.json", "projects.json"];
20
+
21
+ /**
22
+ * Where the records live. Tests get a directory of their own, like their ports, and the suite
23
+ * can point a process at a private one with NETCHAT_DATA_DIR — read only in test mode, so no
24
+ * setting can pull a real installation's records somewhere else.
25
+ */
26
+ export function sharedDataDir() {
27
+ if (C.TEST_MODE) return process.env.NETCHAT_DATA_DIR?.trim() || join(homedir(), ".netchat-test");
28
+ return join(homedir(), ".netchat");
29
+ }
30
+
31
+ /**
32
+ * Where earlier versions kept the records: the dsh plugin's own directory, and every ZCode
33
+ * plugin data directory that carries this plugin's name (the name carries the marketplace it
34
+ * was installed from, so it is matched by prefix). `home` is the user's home directory.
35
+ *
36
+ * In the suite only directories ending in "-test" are considered, as the shared directory does:
37
+ * a test makes its own under that name and never finds — let alone copies — a real
38
+ * installation's records.
39
+ */
40
+ export function legacyDataDirs(home = homedir()) {
41
+ const dirs = [join(home, ".dsh", C.TEST_MODE ? "netchat-test" : "netchat")];
42
+ const zcodeData = join(home, ".zcode", "cli", "plugins", "data");
43
+ if (existsSync(zcodeData)) {
44
+ // The plain name, with or without the suite's suffix, or the marketplace-qualified one.
45
+ const ours = (name) => name === "zcode-net-chat" || name === "zcode-net-chat-test" || name.startsWith("zcode-net-chat@");
46
+ for (const name of readdirSync(zcodeData)) {
47
+ if (!ours(name)) continue;
48
+ if (C.TEST_MODE && !name.endsWith("-test")) continue;
49
+ if (existsSync(join(zcodeData, name))) dirs.push(join(zcodeData, name));
50
+ }
51
+ }
52
+ return dirs;
53
+ }
54
+
55
+ const countRecords = (dir) => {
56
+ let count = 0;
57
+ for (const name of ["inbox.json", "outbox.json"]) {
58
+ try {
59
+ const items = JSON.parse(readFileSync(join(dir, name), "utf8"));
60
+ if (Array.isArray(items)) count += items.length;
61
+ } catch {
62
+ // Missing or unreadable: counts as nothing.
63
+ }
64
+ }
65
+ return count;
66
+ };
67
+
68
+ /**
69
+ * Makes sure the shared directory holds records, copying them from an older location the first
70
+ * time. Returns what was done, for the log.
71
+ *
72
+ * Nothing is copied once the shared directory has an inbox: from then on it is the one that
73
+ * counts, and the older copies are left behind (they only go stale).
74
+ */
75
+ export function ensureSharedRecords(dir = sharedDataDir(), home = homedir()) {
76
+ mkdirSync(dir, { recursive: true });
77
+ if (existsSync(join(dir, "inbox.json"))) return { dir, migratedFrom: null };
78
+ // A directory the suite named is that test's own; it is not filled from anywhere.
79
+ if (C.TEST_MODE && process.env.NETCHAT_DATA_DIR?.trim() === dir) return { dir, migratedFrom: null };
80
+ const candidates = legacyDataDirs(home).filter((legacy) => existsSync(join(legacy, "inbox.json")));
81
+ if (!candidates.length) return { dir, migratedFrom: null };
82
+ // Both older locations can have records (a machine that ran both hosts for a while). The one
83
+ // with more tasks is taken; they are not merged, as the same task can be in both.
84
+ const source = candidates.map((legacy) => ({ legacy, count: countRecords(legacy) })).sort((a, b) => b.count - a.count)[0].legacy;
85
+ for (const name of RECORD_FILES) {
86
+ const from = join(source, name);
87
+ const target = join(dir, name);
88
+ // Never overwrite: the directory held no inbox, but a file may exist all the same.
89
+ if (existsSync(from) && !existsSync(target)) copyFileSync(from, target);
90
+ }
91
+ return { dir, migratedFrom: source };
92
+ }
@@ -0,0 +1,190 @@
1
+ // The wire format of Feishu's long connection, as read off the official SDK's Frame/Header
2
+ // encode functions: a protobuf `Frame` whose headers are key/value pairs and whose payload is
3
+ // the event JSON (or the pong JSON, or the ack JSON). Field numbers are the protocol; this file
4
+ // is a hand-written encoder/decoder for exactly these two messages and nothing more.
5
+ //
6
+ // Frame { 1: SeqID uint64, 2: LogID uint64, 3: service int32, 4: method int32,
7
+ // 5: headers repeated Header, 6: payloadEncoding string?, 7: payloadType string?,
8
+ // 8: payload bytes, 9: LogIDNew string? }
9
+ // Header { 1: key string, 2: value string }
10
+ //
11
+ // `method` is 0 for control frames (ping/pong) and 1 for data frames (events, and our acks).
12
+
13
+ const HEADER_KEY_TYPE = "type";
14
+ const HEADER_KEY_MESSAGE_ID = "message_id";
15
+ const HEADER_KEY_SUM = "sum";
16
+ const HEADER_KEY_SEQ = "seq";
17
+ const HEADER_KEY_TRACE_ID = "trace_id";
18
+ const HEADER_KEY_BIZ_RT = "biz_rt";
19
+ const HEADER_KEY_HANDSHAKE_STATUS = "handshake-status";
20
+ export const MESSAGE_EVENT = "event";
21
+ export const MESSAGE_PING = "ping";
22
+ export const MESSAGE_PONG = "pong";
23
+ export const METHOD_CONTROL = 0;
24
+ export const METHOD_DATA = 1;
25
+
26
+ // ---- protobuf primitives -------------------------------------------------------------------------
27
+
28
+ const varint = (value) => {
29
+ let x = BigInt(value);
30
+ const out = [];
31
+ for (;;) {
32
+ const byte = Number(x & 0x7fn);
33
+ x >>= 7n;
34
+ if (x === 0n) {
35
+ out.push(byte);
36
+ return out;
37
+ }
38
+ out.push(byte | 0x80);
39
+ }
40
+ };
41
+ const lengthDelimited = (bytes) => [...varint(bytes.length), ...bytes];
42
+ /** A protobuf string field: tag (field number, wire type 2), length, UTF-8 bytes. */
43
+ const stringField = (field, text) => [...varint((field << 3) | 2), ...lengthDelimited([...Buffer.from(text, "utf8")])];
44
+
45
+ /** A protobuf reader over a buffer: field by field, values as BigInt / Buffer. */
46
+ function reader(buffer) {
47
+ let pos = 0;
48
+ const readVarint = () => {
49
+ let value = 0n;
50
+ let shift = 0n;
51
+ for (;;) {
52
+ const byte = buffer[pos++];
53
+ value |= BigInt(byte & 0x7f) << shift;
54
+ if (!(byte & 0x80)) return value;
55
+ shift += 7n;
56
+ }
57
+ };
58
+ const readBytes = () => {
59
+ const length = Number(readVarint());
60
+ const out = buffer.subarray(pos, pos + length);
61
+ pos += length;
62
+ return Buffer.from(out);
63
+ };
64
+ return {
65
+ get done() {
66
+ return pos >= buffer.length;
67
+ },
68
+ field() {
69
+ const tag = Number(readVarint());
70
+ return [tag >>> 3, tag & 7];
71
+ },
72
+ readVarint,
73
+ readBytes,
74
+ skip(wire) {
75
+ if (wire === 0) readVarint();
76
+ else if (wire === 2) readBytes();
77
+ else if (wire === 1) pos += 8;
78
+ else if (wire === 5) pos += 4;
79
+ else throw new Error(`unsupported protobuf wire type ${wire}`);
80
+ },
81
+ };
82
+ }
83
+
84
+ // ---- encode ---------------------------------------------------------------------------------------
85
+
86
+ function headerEntry(key, value) {
87
+ const inner = [...stringField(1, key), ...stringField(2, value)];
88
+ return [...varint((5 << 3) | 2), ...lengthDelimited(inner)]; // field 5, wire 2
89
+ }
90
+
91
+ /** Encodes a Frame. `payload` is a Buffer or null; headers is an array of {key, value}. */
92
+ export function encodeFrame({ SeqID = 0, LogID = 0, service = 0, method = 0, headers = [], payload = null }) {
93
+ const out = [
94
+ 0x08, ...varint(SeqID), // field 1, varint
95
+ 0x10, ...varint(LogID), // field 2, varint
96
+ 0x18, ...varint(service), // field 3, varint
97
+ 0x20, ...varint(method), // field 4, varint
98
+ ];
99
+ for (const { key, value } of headers) out.push(...headerEntry(key, value));
100
+ if (payload) out.push(0x42, ...lengthDelimited([...payload])); // field 8, bytes
101
+ return Buffer.from(out);
102
+ }
103
+
104
+ // ---- decode ---------------------------------------------------------------------------------------
105
+
106
+ /** Decodes a Frame; unknown fields are skipped so the server may add them. */
107
+ export function decodeFrame(buffer) {
108
+ const r = reader(buffer);
109
+ const frame = { SeqID: 0, LogID: 0, service: 0, method: 0, headers: [] };
110
+ while (!r.done) {
111
+ const [field, wire] = r.field();
112
+ if (field === 1) frame.SeqID = Number(r.readVarint());
113
+ else if (field === 2) frame.LogID = Number(r.readVarint());
114
+ else if (field === 3) frame.service = Number(r.readVarint());
115
+ else if (field === 4) frame.method = Number(r.readVarint());
116
+ else if (field === 5) {
117
+ const header = reader(r.readBytes());
118
+ const entry = { key: "", value: "" };
119
+ while (!header.done) {
120
+ const [name] = header.field();
121
+ if (name === 1) entry.key = header.readBytes().toString("utf8");
122
+ else if (name === 2) entry.value = header.readBytes().toString("utf8");
123
+ else header.skip(wire);
124
+ }
125
+ frame.headers.push(entry);
126
+ } else if (field === 8) frame.payload = r.readBytes();
127
+ else r.skip(wire);
128
+ }
129
+ frame.headerMap = Object.fromEntries(frame.headers.map((entry) => [entry.key, entry.value]));
130
+ return frame;
131
+ }
132
+
133
+ /** The frame that acknowledges an event: same frame, plus how long it took, payload {code}. */
134
+ export function ackFor(frame, code = 200) {
135
+ return encodeFrame({
136
+ SeqID: frame.SeqID,
137
+ LogID: frame.LogID,
138
+ service: frame.service,
139
+ method: frame.method,
140
+ headers: [...frame.headers, { key: HEADER_KEY_BIZ_RT, value: "0" }],
141
+ payload: Buffer.from(JSON.stringify({ code }), "utf8"),
142
+ });
143
+ }
144
+
145
+ export const pingFrame = (service) =>
146
+ encodeFrame({ service, method: METHOD_CONTROL, headers: [{ key: HEADER_KEY_TYPE, value: MESSAGE_PING }] });
147
+
148
+ /**
149
+ * Reassembles an event delivered in fragments. Headers carry `sum` (fragment count) and
150
+ * `seq` (this fragment's index); the payload bytes concatenate in order. Returns the whole
151
+ * event as a Buffer once the last fragment is in, null until then.
152
+ */
153
+ export class FragmentCache {
154
+ constructor() {
155
+ this.parts = new Map();
156
+ }
157
+
158
+ merge({ messageId, sum, seq, data }) {
159
+ if (!Number.isInteger(sum) || sum <= 0 || !Number.isInteger(seq) || seq < 0 || seq >= sum) {
160
+ throw new Error(`invalid fragment metadata (sum ${sum}, seq ${seq})`);
161
+ }
162
+ let entry = this.parts.get(messageId);
163
+ if (!entry) {
164
+ entry = { slots: new Array(sum).fill(null), at: Date.now() };
165
+ this.parts.set(messageId, entry);
166
+ } else if (entry.slots.length !== sum) {
167
+ this.parts.delete(messageId);
168
+ throw new Error(`fragment sum changed for ${messageId}`);
169
+ }
170
+ entry.slots[seq] = data;
171
+ if (entry.slots.some((slot) => slot === null)) return null;
172
+ this.parts.delete(messageId);
173
+ return Buffer.concat(entry.slots);
174
+ }
175
+
176
+ /** Drops fragments that never completed; a partial event older than this is abandoned. */
177
+ prune(maxAgeMs = 120_000) {
178
+ const now = Date.now();
179
+ for (const [id, entry] of this.parts) if (now - entry.at > maxAgeMs) this.parts.delete(id);
180
+ }
181
+ }
182
+
183
+ export const headerKeys = {
184
+ type: HEADER_KEY_TYPE,
185
+ messageId: HEADER_KEY_MESSAGE_ID,
186
+ sum: HEADER_KEY_SUM,
187
+ seq: HEADER_KEY_SEQ,
188
+ traceId: HEADER_KEY_TRACE_ID,
189
+ handshakeStatus: HEADER_KEY_HANDSHAKE_STATUS,
190
+ };