@bom0792/herdgate 0.9.20 → 0.9.26
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 +136 -1
- package/bin/herdgate.mjs +45 -5
- package/bin/home-tui.mjs +121 -0
- package/dist-readme.md +27 -2
- package/package.json +5 -2
- package/plugin/server/herdr-ssh-win.mjs +43 -0
- package/plugin/server/herdr-ssh.mjs +102 -0
- package/plugin/server/index.mjs +49 -12
- package/plugin/server/mobile-tui-core.mjs +321 -0
- package/plugin/server/mobile-tui-stream.mjs +61 -0
- package/plugin/server/publish-tui.mjs +113 -0
- package/plugin/server/publisher-tui-lifecycle.mjs +117 -0
- package/plugin/server/ssh.d.mts +26 -0
- package/plugin/server/ssh.mjs +165 -37
- package/scripts/build-host-bundle.sh +3 -3
- package/src/cloud/gateway.ts +39 -46
- package/src/cloud/ssh-tcp-edge.ts +119 -0
- package/src/cloud/sshd.ts +36 -28
- package/src/host/mobile-tui-core.mjs +3 -0
- package/src/host/mobile-tui.ts +72 -0
- package/src/host/ssh.ts +5 -315
- package/src/web/app.css +2 -0
- package/src/web/app.js +365 -183
- package/src/web/herdgate-host.zip +0 -0
- package/src/web/index.html +1 -0
- package/src/web/sw.js +1 -1
- package/templates/herdgate-tcp-edge.service +20 -0
- package/windows/cli.mjs +48 -0
- package/windows/install-cli.mjs +137 -0
- package/windows/setup-tui.mjs +110 -0
package/plugin/server/index.mjs
CHANGED
|
@@ -2,16 +2,18 @@
|
|
|
2
2
|
* herdgate plugin for Herdr — commands behind the manifest.
|
|
3
3
|
*
|
|
4
4
|
* The plugin calls Herdr through `HERDR_BIN_PATH` (the official CLI) and publishes the
|
|
5
|
-
* resulting metadata to a herdgate cloud over one outbound WebSocket.
|
|
6
|
-
*
|
|
5
|
+
* resulting metadata to a herdgate cloud over one outbound WebSocket. Device
|
|
6
|
+
* permissions are checked before dispatching any interactive bridge commands.
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
9
|
import { spawn } from "node:child_process";
|
|
10
10
|
import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync } from "node:fs";
|
|
11
11
|
import { join, dirname } from "node:path";
|
|
12
12
|
import { hostname, homedir } from "node:os";
|
|
13
|
+
import { fileURLToPath } from "node:url";
|
|
13
14
|
import { dirs, readConfig, writeConfig, readState, writeState, herdrSnapshot, summarize, herdrPanes, herdrRead } from "./common.mjs";
|
|
14
15
|
import { createSshBridge } from "./ssh.mjs";
|
|
16
|
+
import { registerPublisher } from "./publisher-tui-lifecycle.mjs";
|
|
15
17
|
import { HostChannel, b64d, b64e, fingerprint, generateKeyPair } from "./e2e.mjs";
|
|
16
18
|
|
|
17
19
|
const D = dirs();
|
|
@@ -139,13 +141,28 @@ async function serve() {
|
|
|
139
141
|
|
|
140
142
|
/**
|
|
141
143
|
* The long-lived publisher: read Herdr metadata and push it to every paired device.
|
|
142
|
-
* Reconnects with bounded backoff.
|
|
143
|
-
*
|
|
144
|
+
* Reconnects with bounded backoff. The default transport uses Node's global
|
|
145
|
+
* WebSocket, so a standalone `herdr plugin install` needs no node_modules.
|
|
144
146
|
*/
|
|
145
147
|
async function publisherLoop() {
|
|
146
148
|
const cfg = readConfig(D.configPath);
|
|
147
149
|
const url = cfg.HERDGATE_URL.replace(/\/$/, "");
|
|
148
150
|
const wsUrl = url.replace(/^http/, "ws") + "/v1/agent/ws";
|
|
151
|
+
let openSocket = () => new WebSocket(wsUrl);
|
|
152
|
+
const loopbackPort = cfg.HERDGATE_AGENT_LOOPBACK_PORT;
|
|
153
|
+
if (loopbackPort) {
|
|
154
|
+
if (!/^[1-9]\d{0,4}$/.test(loopbackPort) || Number(loopbackPort) > 65_535) {
|
|
155
|
+
throw new Error("HERDGATE_AGENT_LOOPBACK_PORT must be a port from 1 to 65535");
|
|
156
|
+
}
|
|
157
|
+
// Only for co-located publisher/gate deployments. Node's native WebSocket
|
|
158
|
+
// won't set Host; use the gateway's existing ws dependency for this mode.
|
|
159
|
+
const { default: LocalWebSocket } = await import("ws");
|
|
160
|
+
const host = new URL(url).host;
|
|
161
|
+
const endpoint = `ws://127.0.0.1:${loopbackPort}/v1/agent/ws`;
|
|
162
|
+
openSocket = () => new LocalWebSocket(endpoint, {
|
|
163
|
+
headers: { Host: host }, agent: false, handshakeTimeout: 5_000, perMessageDeflate: false,
|
|
164
|
+
});
|
|
165
|
+
}
|
|
149
166
|
const token = cfg.HERDGATE_ROOM_TOKEN;
|
|
150
167
|
let backoff = 1_000;
|
|
151
168
|
let lastSig = "";
|
|
@@ -241,12 +258,17 @@ async function publisherLoop() {
|
|
|
241
258
|
};
|
|
242
259
|
|
|
243
260
|
const ssh = createSshBridge({
|
|
261
|
+
session: cfg.HERDGATE_HERDR_SESSION || undefined,
|
|
262
|
+
tuiOnly: process.env.HERDGATE_TUI_ONLY === "1",
|
|
263
|
+
mobileHcBin: process.env.HERDGATE_MOBILE_HC_BIN || null,
|
|
264
|
+
mobileTuiAdapter: process.env.HERDGATE_MOBILE_TUI_DEVICE ? {
|
|
265
|
+
device: process.env.HERDGATE_MOBILE_TUI_DEVICE,
|
|
266
|
+
scope: process.env.HERDGATE_MOBILE_TUI_SCOPE === "act" ? "act" : "read",
|
|
267
|
+
script: fileURLToPath(new URL("./mobile-tui-core.mjs", import.meta.url)),
|
|
268
|
+
} : null,
|
|
244
269
|
send: (device, payload) => {
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
wsRef.send(JSON.stringify({ v: 1, t: "frame", device, payload: await e2eToDevice(device, payload) }));
|
|
248
|
-
}
|
|
249
|
-
})();
|
|
270
|
+
// sshd is the SSH endpoint; a concurrent PWA session must not seal these frames.
|
|
271
|
+
if (wsRef?.readyState === 1) wsRef.send(JSON.stringify({ v: 1, t: "frame", device, payload }));
|
|
250
272
|
},
|
|
251
273
|
scopeOf: (device) => devices.find((d) => d.id === device)?.scope ?? null,
|
|
252
274
|
log,
|
|
@@ -274,8 +296,18 @@ async function publisherLoop() {
|
|
|
274
296
|
}
|
|
275
297
|
};
|
|
276
298
|
|
|
299
|
+
const shutdown = () => {
|
|
300
|
+
ssh.closeAll();
|
|
301
|
+
if (wsRef?.readyState === 1) wsRef.close();
|
|
302
|
+
process.exit(0);
|
|
303
|
+
};
|
|
304
|
+
const tuiOnly = process.env.HERDGATE_TUI_ONLY === "1";
|
|
305
|
+
const lifecycle = tuiOnly && process.env.HERDGATE_TUI_RUN_ID
|
|
306
|
+
? registerPublisher(D.stateDir, process.env.HERDGATE_TUI_RUN_ID, shutdown)
|
|
307
|
+
: null;
|
|
308
|
+
|
|
277
309
|
const connect = () => {
|
|
278
|
-
const ws =
|
|
310
|
+
const ws = openSocket();
|
|
279
311
|
wsRef = ws;
|
|
280
312
|
let helloed = false;
|
|
281
313
|
ws.onopen = () => {
|
|
@@ -297,7 +329,8 @@ async function publisherLoop() {
|
|
|
297
329
|
helloed = true;
|
|
298
330
|
backoff = 1_000;
|
|
299
331
|
devices = m.devices ?? [];
|
|
300
|
-
|
|
332
|
+
lifecycle?.setConnected(true);
|
|
333
|
+
log(`connected to ${url}${loopbackPort ? ` via loopback 127.0.0.1:${loopbackPort}` : ""} (room ${m.roomId}, ${devices.length} device(s))`);
|
|
301
334
|
void publish(ws);
|
|
302
335
|
if (timer) clearInterval(timer);
|
|
303
336
|
timer = setInterval(() => void publish(ws), 30_000);
|
|
@@ -305,7 +338,9 @@ async function publisherLoop() {
|
|
|
305
338
|
return;
|
|
306
339
|
}
|
|
307
340
|
if (m.t === "room.update") {
|
|
308
|
-
|
|
341
|
+
const next = m.devices ?? [];
|
|
342
|
+
for (const d of devices) if (!next.some((n) => n.id === d.id && n.scope === d.scope)) ssh.dropDevice(d.id);
|
|
343
|
+
devices = next;
|
|
309
344
|
void publish(ws);
|
|
310
345
|
return;
|
|
311
346
|
}
|
|
@@ -392,6 +427,7 @@ async function publisherLoop() {
|
|
|
392
427
|
const retry = (why) => {
|
|
393
428
|
if (retried) return;
|
|
394
429
|
retried = true;
|
|
430
|
+
lifecycle?.setConnected(false);
|
|
395
431
|
if (timer) clearInterval(timer);
|
|
396
432
|
timer = null;
|
|
397
433
|
ssh.closeAll();
|
|
@@ -404,6 +440,7 @@ async function publisherLoop() {
|
|
|
404
440
|
ws.onclose = () => retry("disconnected");
|
|
405
441
|
ws.onerror = () => retry("ws error");
|
|
406
442
|
};
|
|
443
|
+
if (tuiOnly) for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, shutdown);
|
|
407
444
|
connect();
|
|
408
445
|
// Keep the child alive while the socket reconnects.
|
|
409
446
|
setInterval(() => {}, 1 << 30);
|
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Subset of the Core API for TUI panes. Input requires explicit local opt-in.
|
|
3
|
+
import { execFile } from "node:child_process";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { hostname, homedir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { promisify, stripVTControlCharacters } from "node:util";
|
|
8
|
+
import { openTerminal, validDimension } from "./mobile-tui-stream.mjs";
|
|
9
|
+
|
|
10
|
+
const invoke = promisify(execFile);
|
|
11
|
+
const herdr = process.env.HERDR_BIN_PATH || join(homedir(), ".local/bin/herdr");
|
|
12
|
+
const name = process.env.HERDGATE_HOST_NAME || "home-tui-mobile";
|
|
13
|
+
const digest = (text) => createHash("sha256").update(text).digest("hex");
|
|
14
|
+
const core = { id: digest(`herdgate-tui:${hostname()}:${name}`).slice(0, 32), name };
|
|
15
|
+
const version = "0.1.21"; // Core wire compatibility target, not a running Core binary.
|
|
16
|
+
const methods = ["hello", "server.status", "terminal.list", "terminal.get", "terminal.read", "events.subscribe", "templates.list", "machine.list", "doc.get"];
|
|
17
|
+
const inputMethods = ["terminal.send", "terminal.keys", "terminal.interrupt"];
|
|
18
|
+
const args = process.argv.slice(2);
|
|
19
|
+
const interactive = args[0] === "--interactive";
|
|
20
|
+
if (interactive) args.shift();
|
|
21
|
+
const mode = interactive ? "interactive" : "read-only";
|
|
22
|
+
const inputText = (text) => typeof text === "string" && text.length > 0 && !text.includes("\0") && Buffer.byteLength(text) <= 8192;
|
|
23
|
+
const frameKind = { data: 0, credit: 1, close: 2, resize: 3 };
|
|
24
|
+
const cap = 128 * 1024;
|
|
25
|
+
const windowBytes = 64 * 1024;
|
|
26
|
+
const maxStreams = 2;
|
|
27
|
+
const pollMs = 1_250;
|
|
28
|
+
const startedAt = Date.now();
|
|
29
|
+
let cache;
|
|
30
|
+
let cacheUntil = 0;
|
|
31
|
+
const run = async (args) => (await invoke(herdr, args, { timeout: 4_000, maxBuffer: 512 * 1024, windowsHide: true, shell: false })).stdout;
|
|
32
|
+
|
|
33
|
+
async function panes() {
|
|
34
|
+
if (cache && Date.now() < cacheUntil) return cache;
|
|
35
|
+
const parsed = JSON.parse(await run(["pane", "list"]));
|
|
36
|
+
if (!Array.isArray(parsed?.result?.panes)) throw new Error("Herdr pane list unavailable");
|
|
37
|
+
cache = parsed.result.panes.filter((p) => typeof p?.pane_id === "string" && /^[a-zA-Z0-9_:.-]{1,128}$/.test(p.pane_id) && !p.pane_id.startsWith("-"))
|
|
38
|
+
.slice(0, 180).map((p) => {
|
|
39
|
+
const title = clip(p.terminal_title_stripped || p.terminal_title || p.pane_id, 120);
|
|
40
|
+
return { id: p.pane_id, target: typeof p.terminal_id === "string" && /^term_[a-zA-Z0-9]{1,96}$/.test(p.terminal_id) ? p.terminal_id : null, terminal: {
|
|
41
|
+
address: "t" + digest(p.pane_id).slice(0, 12), title, name: null, argv: [], cwd: clip(p.cwd, 512),
|
|
42
|
+
state: "live", created_ms: 0, screen: "inexact", cols: 80, rows: 24,
|
|
43
|
+
labels: { where: clip(p.workspace_id, 128) }, turn: 0,
|
|
44
|
+
} };
|
|
45
|
+
});
|
|
46
|
+
cacheUntil = Date.now() + 1_000;
|
|
47
|
+
return cache;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function clip(x, n) { return typeof x === "string" ? x.slice(0, n) : ""; }
|
|
51
|
+
const status = async () => ({ core, version, pid: process.pid, uptime_ms: Date.now() - startedAt, holders: [], live: (await panes()).length, finished: 0, keeps_running_after_logout: true });
|
|
52
|
+
class RpcError extends Error {
|
|
53
|
+
constructor(code, message, kind) { super(message); this.code = code; this.kind = kind; }
|
|
54
|
+
}
|
|
55
|
+
const invalid = () => new RpcError(-32602, "Invalid params", "usage");
|
|
56
|
+
|
|
57
|
+
async function findPane(terminal) {
|
|
58
|
+
if (typeof terminal !== "string") throw invalid();
|
|
59
|
+
const hit = (await panes()).find((x) => x.terminal.address === terminal);
|
|
60
|
+
if (!hit) throw new RpcError(-32000, "No such terminal", "not_found");
|
|
61
|
+
return hit;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function call(method, p, framed, attach) {
|
|
65
|
+
switch (method) {
|
|
66
|
+
case "hello":
|
|
67
|
+
return { core, version, generation: 1, framed, features: framed ? ["framed", "attach", "status", ...(interactive ? ["resize_notifications"] : [])] : ["status"], methods: [...methods, ...(framed ? ["terminal.attach"] : []), ...(interactive ? inputMethods : [])], keeps_running_after_logout: true };
|
|
68
|
+
case "server.status": return status();
|
|
69
|
+
case "terminal.list":
|
|
70
|
+
case "events.subscribe": {
|
|
71
|
+
const filters = p.labels ?? {};
|
|
72
|
+
if (!filters || typeof filters !== "object" || Array.isArray(filters)) throw invalid();
|
|
73
|
+
const terminals = (await panes()).map(({ terminal }) => terminal).filter((t) =>
|
|
74
|
+
(method === "terminal.list" || (!p.children_of && (!p.terminal || p.terminal === t.address))) &&
|
|
75
|
+
Object.entries(filters).every(([k, v]) => Object.hasOwn(t.labels, k) && t.labels[k] === v));
|
|
76
|
+
return method === "terminal.list" ? { terminals, hidden_finished: 0, machines: [] } : { terminals, seq: 0, channel: null };
|
|
77
|
+
}
|
|
78
|
+
case "terminal.send":
|
|
79
|
+
case "terminal.keys":
|
|
80
|
+
case "terminal.interrupt": {
|
|
81
|
+
if (!interactive) throw new RpcError(-32601, "This pairing is read-only", "forbidden");
|
|
82
|
+
const { id, terminal } = await findPane(p.terminal);
|
|
83
|
+
const { turn } = terminal;
|
|
84
|
+
if (method === "terminal.send") {
|
|
85
|
+
if (!inputText(p.text) || p.wait === true || p.if != null) throw invalid();
|
|
86
|
+
// Herdr's pane run takes positional text and submits it with Enter in one API request.
|
|
87
|
+
await run(["pane", "run", id, p.text]);
|
|
88
|
+
return { turn, status: null, started: null, wait: null };
|
|
89
|
+
}
|
|
90
|
+
const keys = method === "terminal.interrupt" ? ["ctrl+c"] : p.keys;
|
|
91
|
+
if (!Array.isArray(keys) || !keys.length || keys.length > 32 || keys.some((key) => typeof key !== "string" || !/^(?:(?:ctrl|alt|shift|super)\+)*[a-z0-9][a-z0-9_-]{0,15}$/i.test(key) || key.length > 32)) throw invalid();
|
|
92
|
+
await run(["pane", "send-keys", id, ...keys]);
|
|
93
|
+
return method === "terminal.interrupt" ? { key: keys[0], outcome: "unknown" } : { turn, status: null };
|
|
94
|
+
}
|
|
95
|
+
case "terminal.get":
|
|
96
|
+
case "terminal.attach":
|
|
97
|
+
case "terminal.read": {
|
|
98
|
+
const hit = await findPane(p.terminal);
|
|
99
|
+
if (method === "terminal.get") return hit.terminal;
|
|
100
|
+
if (method === "terminal.attach") {
|
|
101
|
+
if (!framed) throw new RpcError(-32000, "Framed connection required", "needs_framed");
|
|
102
|
+
if ([p.cols, p.rows].some((n) => n !== undefined && n !== 0 && !validDimension(n))) throw invalid();
|
|
103
|
+
return attach(hit, p);
|
|
104
|
+
}
|
|
105
|
+
const lines = p.lines ?? 0;
|
|
106
|
+
if (!Number.isSafeInteger(lines) || lines < 0) throw invalid();
|
|
107
|
+
const text = await run(["pane", "read", hit.id, "--source", "recent", "--lines", String(Math.max(24, Math.min(120, lines + 24))), "--format", "text", "--raw"]);
|
|
108
|
+
return { text: text.slice(0, 32 * 1024), complete: text.length <= 32 * 1024, how: "screen" };
|
|
109
|
+
}
|
|
110
|
+
case "templates.list": return { templates: [] };
|
|
111
|
+
case "machine.list": return { machines: [] };
|
|
112
|
+
case "doc.get": return { value: null, version: 0 };
|
|
113
|
+
default: throw new RpcError(-32601, "Method not available on this TUI adapter", "forbidden");
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function paint(paneId, rows) {
|
|
118
|
+
const raw = await run(["pane", "read", paneId, "--source", "visible", "--lines", String(rows), "--format", "text", "--raw"]);
|
|
119
|
+
// Do not replay host terminal escapes (clipboard, title, device queries, etc.).
|
|
120
|
+
const text = stripVTControlCharacters(raw.slice(0, 16_000))
|
|
121
|
+
.replace(/\r\n?/g, "\n").replace(/[\x00-\x09\x0b-\x1f\x7f-\x9f]/g, "")
|
|
122
|
+
.replace(/\n/g, "\r\n");
|
|
123
|
+
return Buffer.from("\x1b[2J\x1b[H" + text);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function serve() {
|
|
127
|
+
let framed = false;
|
|
128
|
+
let buffer = Buffer.alloc(0);
|
|
129
|
+
const streams = new Map();
|
|
130
|
+
let nextChannel = 1;
|
|
131
|
+
let timer;
|
|
132
|
+
let polling = false;
|
|
133
|
+
let closed = false;
|
|
134
|
+
|
|
135
|
+
function output(bytes) {
|
|
136
|
+
return new Promise((resolve, reject) => process.stdout.write(bytes, (err) => err ? reject(err) : resolve()));
|
|
137
|
+
}
|
|
138
|
+
function frame(channel, kind, body = Buffer.alloc(0)) {
|
|
139
|
+
const header = Buffer.alloc(9);
|
|
140
|
+
header.writeUInt32LE(channel, 0);
|
|
141
|
+
header[4] = kind;
|
|
142
|
+
header.writeUInt32LE(body.length, 5);
|
|
143
|
+
return output(Buffer.concat([header, body]));
|
|
144
|
+
}
|
|
145
|
+
function write(reply) {
|
|
146
|
+
const body = Buffer.from(JSON.stringify(reply));
|
|
147
|
+
return framed ? frame(0, frameKind.data, body) : output(Buffer.concat([body, Buffer.from("\n")]));
|
|
148
|
+
}
|
|
149
|
+
async function attach(hit, p) {
|
|
150
|
+
if (streams.size >= maxStreams || nextChannel > 0xffff_ffff) throw new RpcError(-32000, "Too many open terminal views", "unavailable");
|
|
151
|
+
const writable = interactive && p.observe !== true;
|
|
152
|
+
if (writable && !hit.target) throw new RpcError(-32000, "This pane has no native terminal stream", "unavailable");
|
|
153
|
+
const native = writable ? await openTerminal(herdr, hit.target, Math.min(500, p.cols || hit.terminal.cols), Math.min(300, p.rows || hit.terminal.rows)) : null;
|
|
154
|
+
const channel = nextChannel++;
|
|
155
|
+
const resize = Boolean(native && p.resize_notifications === true);
|
|
156
|
+
const terminal = native ? { ...hit.terminal, cols: native.first.cols, rows: native.first.rows } : hit.terminal;
|
|
157
|
+
streams.set(channel, { id: hit.id, rows: Math.min(120, p.rows || hit.terminal.rows), credit: windowBytes, last: null, ready: false, native, resize });
|
|
158
|
+
return { channel, terminal, resize_notifications: resize, automatic_input: false };
|
|
159
|
+
}
|
|
160
|
+
function release(channel) {
|
|
161
|
+
const stream = streams.get(channel);
|
|
162
|
+
if (!stream) return false;
|
|
163
|
+
streams.delete(channel);
|
|
164
|
+
stream.native?.close();
|
|
165
|
+
stream.wake?.();
|
|
166
|
+
return true;
|
|
167
|
+
}
|
|
168
|
+
async function closeStream(channel) {
|
|
169
|
+
if (release(channel)) await frame(channel, frameKind.close);
|
|
170
|
+
}
|
|
171
|
+
async function pumpNative(channel, stream) {
|
|
172
|
+
async function sendPaint(paint) {
|
|
173
|
+
if (streams.get(channel) !== stream) return false;
|
|
174
|
+
if (stream.resize && (paint.cols !== stream.cols || paint.rows !== stream.nativeRows)) {
|
|
175
|
+
stream.cols = paint.cols;
|
|
176
|
+
stream.nativeRows = paint.rows;
|
|
177
|
+
const size = Buffer.alloc(4);
|
|
178
|
+
size.writeUInt16LE(paint.cols, 0);
|
|
179
|
+
size.writeUInt16LE(paint.rows, 2);
|
|
180
|
+
await frame(channel, frameKind.resize, size);
|
|
181
|
+
}
|
|
182
|
+
for (let offset = 0; offset < paint.bytes.length;) {
|
|
183
|
+
while (streams.get(channel) === stream && stream.credit === 0) await new Promise((resolve) => { stream.wake = resolve; });
|
|
184
|
+
if (streams.get(channel) !== stream) return false;
|
|
185
|
+
const end = Math.min(offset + stream.credit, offset + 32 * 1024, paint.bytes.length);
|
|
186
|
+
stream.credit -= end - offset;
|
|
187
|
+
await frame(channel, frameKind.data, paint.bytes.subarray(offset, end));
|
|
188
|
+
offset = end;
|
|
189
|
+
}
|
|
190
|
+
return true;
|
|
191
|
+
}
|
|
192
|
+
try {
|
|
193
|
+
if (await sendPaint(stream.native.first)) {
|
|
194
|
+
for await (const paint of stream.native.frames) if (!(await sendPaint(paint))) break;
|
|
195
|
+
}
|
|
196
|
+
} catch { /* Unexpected native close is signalled on this stream. */ }
|
|
197
|
+
finally { await closeStream(channel); }
|
|
198
|
+
}
|
|
199
|
+
function schedule(delay) {
|
|
200
|
+
if (closed || polling || timer || ![...streams.values()].some((s) => !s.native)) return;
|
|
201
|
+
timer = setTimeout(() => {
|
|
202
|
+
timer = undefined;
|
|
203
|
+
void poll().catch(() => process.stdin.destroy());
|
|
204
|
+
}, delay);
|
|
205
|
+
timer.unref();
|
|
206
|
+
}
|
|
207
|
+
async function poll() {
|
|
208
|
+
polling = true;
|
|
209
|
+
try {
|
|
210
|
+
for (const [channel, stream] of [...streams]) {
|
|
211
|
+
// Bound subprocesses and stop reading while a client is not draining this view.
|
|
212
|
+
if (closed || streams.get(channel) !== stream || stream.native || !stream.ready || stream.credit < windowBytes / 2) continue;
|
|
213
|
+
let snapshot;
|
|
214
|
+
try { snapshot = await paint(stream.id, stream.rows); }
|
|
215
|
+
catch {
|
|
216
|
+
if (!closed) await closeStream(channel);
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
if (closed || streams.get(channel) !== stream || snapshot.length > stream.credit || stream.last?.equals(snapshot)) continue;
|
|
220
|
+
stream.credit -= snapshot.length;
|
|
221
|
+
stream.last = snapshot;
|
|
222
|
+
await frame(channel, frameKind.data, snapshot);
|
|
223
|
+
}
|
|
224
|
+
} finally {
|
|
225
|
+
polling = false;
|
|
226
|
+
schedule(pollMs);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
try {
|
|
231
|
+
for await (const chunk of process.stdin) {
|
|
232
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
233
|
+
for (;;) {
|
|
234
|
+
let body;
|
|
235
|
+
if (framed) {
|
|
236
|
+
if (buffer.length < 9) break;
|
|
237
|
+
const size = buffer.readUInt32LE(5);
|
|
238
|
+
if (size > cap) throw new Error("Core frame too large");
|
|
239
|
+
if (buffer.length < 9 + size) break;
|
|
240
|
+
const channel = buffer.readUInt32LE(0);
|
|
241
|
+
const kind = buffer[4];
|
|
242
|
+
body = buffer.subarray(9, 9 + size);
|
|
243
|
+
buffer = buffer.subarray(9 + size);
|
|
244
|
+
if (channel !== 0) {
|
|
245
|
+
const stream = streams.get(channel);
|
|
246
|
+
if (stream && kind === frameKind.credit && size === 4) {
|
|
247
|
+
stream.credit = Math.min(windowBytes, stream.credit + body.readUInt32LE());
|
|
248
|
+
stream.wake?.();
|
|
249
|
+
stream.wake = null;
|
|
250
|
+
}
|
|
251
|
+
if (stream && kind === frameKind.close && size === 0) await closeStream(channel);
|
|
252
|
+
if (stream?.native) {
|
|
253
|
+
try {
|
|
254
|
+
if (kind === frameKind.data && size > 0) {
|
|
255
|
+
if (size > 32 * 1024) throw invalid();
|
|
256
|
+
await stream.native.send({ type: "terminal.input", bytes: body.toString("base64") });
|
|
257
|
+
}
|
|
258
|
+
if (kind === frameKind.resize && size === 4) {
|
|
259
|
+
const cols = body.readUInt16LE(0), rows = body.readUInt16LE(2);
|
|
260
|
+
if (cols > 0 && rows > 0) await stream.native.send({ type: "terminal.resize", cols: Math.min(500, cols), rows: Math.min(300, rows) });
|
|
261
|
+
}
|
|
262
|
+
} catch { await closeStream(channel); }
|
|
263
|
+
}
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
if (kind !== frameKind.data) continue;
|
|
267
|
+
} else {
|
|
268
|
+
const end = buffer.indexOf(10);
|
|
269
|
+
if (end > cap || (end < 0 && buffer.length > cap)) throw new Error("Core line too large");
|
|
270
|
+
if (end < 0) break;
|
|
271
|
+
body = buffer.subarray(0, end);
|
|
272
|
+
buffer = buffer.subarray(end + 1);
|
|
273
|
+
if (!body.length) continue;
|
|
274
|
+
}
|
|
275
|
+
let msg;
|
|
276
|
+
try { msg = JSON.parse(body.toString("utf8")); }
|
|
277
|
+
catch { await write({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }); continue; }
|
|
278
|
+
if (!msg || msg.jsonrpc !== "2.0" || typeof msg.method !== "string" || !Object.hasOwn(msg, "id")) continue;
|
|
279
|
+
if (msg.id !== null && typeof msg.id !== "number" && typeof msg.id !== "string") continue;
|
|
280
|
+
const reply = { jsonrpc: "2.0", id: msg.id };
|
|
281
|
+
const nextFramed = framed || (msg.method === "hello" && msg.params?.framed === true);
|
|
282
|
+
let result;
|
|
283
|
+
try {
|
|
284
|
+
if (msg.params != null && (typeof msg.params !== "object" || Array.isArray(msg.params))) throw invalid();
|
|
285
|
+
result = await call(msg.method, msg.params ?? {}, nextFramed, attach);
|
|
286
|
+
} catch (err) {
|
|
287
|
+
const error = err instanceof RpcError ? { code: err.code, message: err.message, data: { kind: err.kind } } : { code: -32000, message: "Herdr TUI unavailable", data: { kind: "unavailable" } };
|
|
288
|
+
await write({ ...reply, error });
|
|
289
|
+
continue;
|
|
290
|
+
}
|
|
291
|
+
await write({ ...reply, result });
|
|
292
|
+
framed = nextFramed;
|
|
293
|
+
if (msg.method === "terminal.attach") {
|
|
294
|
+
const stream = streams.get(result.channel);
|
|
295
|
+
stream.ready = true;
|
|
296
|
+
if (stream.native) void pumpNative(result.channel, stream).catch(() => process.stdin.destroy());
|
|
297
|
+
else schedule(0);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
} finally {
|
|
302
|
+
closed = true;
|
|
303
|
+
clearTimeout(timer);
|
|
304
|
+
for (const channel of streams.keys()) release(channel);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const command = args.join(" ");
|
|
309
|
+
try {
|
|
310
|
+
if (command === "--version" || command === "-V") console.log(`hc ${version} (Herdgate ${mode} TUI adapter)`);
|
|
311
|
+
else if (command === "server status" || command === "server status --json") console.log(JSON.stringify(await status()));
|
|
312
|
+
else if (command === "connect" || command === "connect --json") {
|
|
313
|
+
await serve();
|
|
314
|
+
} else {
|
|
315
|
+
console.error("herdgate: TUI adapter supports only connect, --version, and server status");
|
|
316
|
+
process.exitCode = 111;
|
|
317
|
+
}
|
|
318
|
+
} catch {
|
|
319
|
+
console.error("herdgate: could not query the local Herdr TUI");
|
|
320
|
+
process.exitCode = 111;
|
|
321
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// Native Herdr terminal controller. Never grants takeover and never interprets a shell command.
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
|
|
4
|
+
const maxLine = 1024 * 1024;
|
|
5
|
+
|
|
6
|
+
export async function openTerminal(bin, id, cols, rows) {
|
|
7
|
+
const child = spawn(bin, ["terminal", "session", "control", id, "--cols", String(cols), "--rows", String(rows)], {
|
|
8
|
+
stdio: ["pipe", "pipe", "ignore"], windowsHide: true, shell: false,
|
|
9
|
+
});
|
|
10
|
+
child.on("error", () => child.stdout.destroy());
|
|
11
|
+
child.stdin.on("error", () => child.stdout.destroy());
|
|
12
|
+
const frames = readFrames(child.stdout);
|
|
13
|
+
let closed = false;
|
|
14
|
+
function close() {
|
|
15
|
+
if (closed) return;
|
|
16
|
+
closed = true;
|
|
17
|
+
child.stdin.end(); // EOF asks Herdr to release the controller.
|
|
18
|
+
const kill = setTimeout(() => child.kill(), 750);
|
|
19
|
+
kill.unref();
|
|
20
|
+
child.once("close", () => clearTimeout(kill));
|
|
21
|
+
}
|
|
22
|
+
const deadline = setTimeout(() => child.stdout.destroy(new Error("Herdr attach timed out")), 4000);
|
|
23
|
+
try {
|
|
24
|
+
const first = await frames.next();
|
|
25
|
+
if (first.done) throw new Error("Herdr declined terminal attach");
|
|
26
|
+
return {
|
|
27
|
+
first: first.value, frames, close,
|
|
28
|
+
send: (message) => new Promise((resolve, reject) => {
|
|
29
|
+
if (closed || !child.stdin.writable) return reject(new Error("Herdr terminal closed"));
|
|
30
|
+
child.stdin.write(JSON.stringify(message) + "\n", (err) => err ? reject(err) : resolve());
|
|
31
|
+
}),
|
|
32
|
+
};
|
|
33
|
+
} catch (err) {
|
|
34
|
+
close();
|
|
35
|
+
throw err;
|
|
36
|
+
} finally {
|
|
37
|
+
clearTimeout(deadline);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function* readFrames(stdout) {
|
|
42
|
+
let pending = Buffer.alloc(0);
|
|
43
|
+
for await (const chunk of stdout) {
|
|
44
|
+
pending = Buffer.concat([pending, chunk]);
|
|
45
|
+
for (;;) {
|
|
46
|
+
const end = pending.indexOf(10);
|
|
47
|
+
if (end > maxLine || (end < 0 && pending.length > maxLine)) throw new Error("Herdr terminal frame too large");
|
|
48
|
+
if (end < 0) break;
|
|
49
|
+
const msg = JSON.parse(pending.subarray(0, end).toString("utf8"));
|
|
50
|
+
pending = pending.subarray(end + 1);
|
|
51
|
+
if (msg.type === "terminal.closed") return;
|
|
52
|
+
if (msg.type !== "terminal.frame" || msg.encoding !== "ansi" || typeof msg.bytes !== "string") continue;
|
|
53
|
+
if (!validDimension(msg.width) || !validDimension(msg.height)) throw new Error("Invalid Herdr terminal geometry");
|
|
54
|
+
yield { cols: msg.width, rows: msg.height, bytes: Buffer.from(msg.bytes, "base64") };
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function validDimension(value) {
|
|
60
|
+
return Number.isInteger(value) && value > 0 && value <= 65535;
|
|
61
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// Opt-in Windows pilot. Run as the same user as the local Herdr TUI.
|
|
2
|
+
import { execFile } from "node:child_process";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { realpathSync, statSync } from "node:fs";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { promisify } from "node:util";
|
|
9
|
+
import { readConfig } from "./common.mjs";
|
|
10
|
+
import { publisherStatus, startPublisher, stopPublisher } from "./publisher-tui-lifecycle.mjs";
|
|
11
|
+
|
|
12
|
+
const run = promisify(execFile);
|
|
13
|
+
try {
|
|
14
|
+
const appHome = process.env.HERDR_APP_HOME || join(homedir(), ".config", "herdr-app");
|
|
15
|
+
const base = join(appHome, "herdgate");
|
|
16
|
+
const state = join(base, "state");
|
|
17
|
+
const [action, exe, ...args] = process.argv.slice(2);
|
|
18
|
+
if (action === "status" || action === "stop") {
|
|
19
|
+
if (exe || args.length) throw new Error(`usage: publish-tui.mjs ${action}`);
|
|
20
|
+
const result = action === "status" ? publisherStatus(state) : await stopPublisher(state);
|
|
21
|
+
console.log(JSON.stringify(result));
|
|
22
|
+
if (action === "stop" && result.state !== "stopped") process.exitCode = 1;
|
|
23
|
+
} else {
|
|
24
|
+
const bin = ["start", "check", "--worker"].includes(action) ? exe : action;
|
|
25
|
+
if (args.length && (args.length !== 2 || !["--hc", "--mobile-tui", "--mobile-tui-act"].includes(args[0]) || !args[1])) throw new Error("expected --hc <path to herdr-core.exe>, --mobile-tui <read device ID>, or --mobile-tui-act <act device ID>");
|
|
26
|
+
const mobile = args[0] === "--mobile-tui" || args[0] === "--mobile-tui-act" ? args[1] : "";
|
|
27
|
+
const mobileScope = args[0] === "--mobile-tui-act" ? "act" : "read";
|
|
28
|
+
if (mobile && !/^d_[A-Za-z0-9]{1,32}$/.test(mobile)) throw new Error(`the Mobile TUI option requires a paired ${mobileScope} device ID (d_…)`);
|
|
29
|
+
await launch({ action, bin, hc: args[0] === "--hc" ? args[1] : undefined, mobile, mobileScope, base, state });
|
|
30
|
+
}
|
|
31
|
+
} catch (e) {
|
|
32
|
+
console.error(`herdgate: ${e instanceof Error ? e.message : String(e)}`);
|
|
33
|
+
process.exitCode = 1;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function launch({ action, bin, hc, mobile, mobileScope, base, state }) {
|
|
37
|
+
if (process.platform !== "win32") throw new Error("this publisher launcher is for Windows");
|
|
38
|
+
if (typeof globalThis.WebSocket !== "function") throw new Error("use Node 22+ with WebSocket enabled to install and run the publisher");
|
|
39
|
+
if (!bin || !/^[a-z]:[\\/]/i.test(bin) || !/\.exe$/i.test(bin) || !statSync(bin).isFile()) {
|
|
40
|
+
throw new Error("usage: node publish-tui.mjs start <absolute path to herdr.exe> | status | stop");
|
|
41
|
+
}
|
|
42
|
+
const real = realpathSync.native(bin);
|
|
43
|
+
if (!/^[a-z]:[\\/]/i.test(real)) throw new Error("Herdr must be installed on a local drive");
|
|
44
|
+
const cfg = readConfig(join(base, "config", "herdgate.env"));
|
|
45
|
+
if (!cfg.HERDGATE_URL || !cfg.HERDGATE_ROOM_TOKEN) throw new Error("pair this laptop in the Herdgate panel first");
|
|
46
|
+
const gate = new URL(cfg.HERDGATE_URL);
|
|
47
|
+
if (gate.protocol !== "https:" || gate.username || gate.password || cfg.HERDGATE_AGENT_LOOPBACK_PORT) {
|
|
48
|
+
throw new Error("the Windows pilot requires an HTTPS gate and does not use loopback mode");
|
|
49
|
+
}
|
|
50
|
+
if (cfg.HERDGATE_HERDR_SESSION && cfg.HERDGATE_HERDR_SESSION !== "default") {
|
|
51
|
+
throw new Error("this pilot exposes only the default TUI session");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
let mobileHcBin = "";
|
|
55
|
+
if (hc !== undefined) {
|
|
56
|
+
if (!/^[a-z]:[\\/]/i.test(hc) || !/\.exe$/i.test(hc) || !statSync(hc).isFile()) {
|
|
57
|
+
throw new Error("--hc needs the absolute path to herdr-core.exe on a local drive");
|
|
58
|
+
}
|
|
59
|
+
mobileHcBin = realpathSync.native(hc);
|
|
60
|
+
if (!/^[a-z]:[\\/]/i.test(mobileHcBin) || !/\.exe$/i.test(mobileHcBin)) throw new Error("herdr-core must be a local executable");
|
|
61
|
+
const result = await run(mobileHcBin, ["--version"], { timeout: 5_000, shell: false, windowsHide: true });
|
|
62
|
+
if (!/\bhc\s+\d+\.\d+\.\d+\b|\bherdr-core\s+\d+\.\d+\.\d+\b/i.test(result.stdout)) {
|
|
63
|
+
throw new Error("--hc did not identify itself as herdr-core");
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const env = {
|
|
67
|
+
...process.env,
|
|
68
|
+
HERDGATE_MOBILE_HC_BIN: mobileHcBin,
|
|
69
|
+
HERDGATE_MOBILE_TUI_DEVICE: mobile,
|
|
70
|
+
HERDGATE_MOBILE_TUI_SCOPE: mobileScope,
|
|
71
|
+
...(mobile ? { HERDGATE_HOST_NAME: `${process.env.COMPUTERNAME || "windows"}-TUI` } : {}),
|
|
72
|
+
HERDR_BIN_PATH: bin,
|
|
73
|
+
HERDGATE_HERDR_BIN: bin,
|
|
74
|
+
HERDR_SESSION: "default",
|
|
75
|
+
HERDGATE_HERDR_SESSION: "default",
|
|
76
|
+
HERDR_PLUGIN_ID: "dev.herdgate.host",
|
|
77
|
+
HERDR_PLUGIN_CONFIG_DIR: join(base, "config"),
|
|
78
|
+
HERDR_PLUGIN_STATE_DIR: state,
|
|
79
|
+
HERDGATE_SETTINGS: join(base, "settings.json"),
|
|
80
|
+
HERDGATE_TUI_ONLY: "1",
|
|
81
|
+
HERDGATE_PUBLISHER_CHILD: "1",
|
|
82
|
+
};
|
|
83
|
+
const status = async (target) => JSON.parse((await run(bin, ["status", target, "--json"], {
|
|
84
|
+
env, timeout: 5_000, shell: false, windowsHide: true,
|
|
85
|
+
})).stdout);
|
|
86
|
+
const client = await status("client");
|
|
87
|
+
if (client.version !== "0.9.5" || client.remote_host_bridge !== true) {
|
|
88
|
+
throw new Error("use the standalone Herdr v0.9.5 Windows package with its bundled ConPTY support");
|
|
89
|
+
}
|
|
90
|
+
const server = await status("server");
|
|
91
|
+
if (!server.running || !server.capabilities?.detached_server_daemon) {
|
|
92
|
+
throw new Error("start the local Herdr 0.9.5 TUI (default session) before publishing");
|
|
93
|
+
}
|
|
94
|
+
if (server.version !== client.version) {
|
|
95
|
+
throw new Error(`the running Herdr server reports ${server.version}, expected ${client.version}; finish work in live panes before restarting Herdr`);
|
|
96
|
+
}
|
|
97
|
+
if (action === "check") return;
|
|
98
|
+
if (action === "start") {
|
|
99
|
+
const mode = mobile ? [mobileScope === "act" ? "--mobile-tui-act" : "--mobile-tui", mobile] : mobileHcBin ? ["--hc", mobileHcBin] : [];
|
|
100
|
+
const result = await startPublisher(state, [fileURLToPath(import.meta.url), "--worker", bin, ...mode], env);
|
|
101
|
+
console.log(JSON.stringify(result));
|
|
102
|
+
if (!["connected", "connecting", "starting"].includes(result.state)) process.exitCode = 1;
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
if (action === "--worker" && !env.HERDGATE_TUI_RUN_ID) throw new Error("use start to launch the background publisher");
|
|
106
|
+
if (action !== "--worker") {
|
|
107
|
+
env.HERDGATE_TUI_RUN_ID = randomUUID();
|
|
108
|
+
console.error("herdgate: publishing in the foreground; Ctrl+C stops publishing");
|
|
109
|
+
}
|
|
110
|
+
Object.assign(process.env, env);
|
|
111
|
+
process.argv[2] = "serve";
|
|
112
|
+
await import("./index.mjs");
|
|
113
|
+
}
|