@bom0792/herdgate 0.9.21 → 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 CHANGED
@@ -181,13 +181,27 @@ client-to-publisher Noise E2E. No third-party relay or inbound client port is ne
181
181
  ### Windows as a TUI host
182
182
 
183
183
  Use this only where remote control is approved by the machine's owner/IT.
184
- With Node 22+ on Windows:
184
+ With Node 22+ on Windows and an existing Gate pairing, use one command to
185
+ install and start the TUI publisher (add the relevant Mobile flag if enabled):
185
186
 
186
187
  ```powershell
187
- npx --yes @bom0792/herdgate@latest install-tui
188
+ npx --yes @bom0792/herdgate@latest tui setup --mobile-tui-act d_device
188
189
  npx --yes @bom0792/herdgate@latest tui status
189
190
  ```
190
191
 
192
+ Omit `--mobile-tui-act d_device` for TUI-only setup. The first setup or
193
+ migration from a manual install needs the desired mode once; it is saved
194
+ locally only after the publisher connects. For subsequent updates:
195
+
196
+ ```powershell
197
+ npx --yes @bom0792/herdgate@latest tui update
198
+ ```
199
+
200
+ The update validates the new release before touching the old publisher. It
201
+ preserves the device ID and mode, restarts only the publisher if needed, and
202
+ tries to restore the old release if the new worker cannot connect. Pairing
203
+ and SSH keys are not rewritten. Use `install-tui` for install without starting.
204
+
191
205
  The ZIP remains an alternative: extract it and run `node .\windows\install-cli.mjs`.
192
206
 
193
207
  The installer stores each build under `%LOCALAPPDATA%\Herdgate\cli\releases`.
@@ -206,7 +220,57 @@ When `herdgate-tui status` shows `connected`, you can close PowerShell.
206
220
  port, no Windows SSH server. The publisher reuses the existing laptop pairing.
207
221
  The controlling machine still needs its own approved `act` device and SSH key.
208
222
  Add the saved machine with `herdr machine add <alias> --label laptop --remote-session default`.
209
- This does not enable Windows APP/HC hosting.
223
+ The default publisher does not expose `hc`. If remote control is approved, opt
224
+ in to Herdr Mobile support with the installed Core executable:
225
+
226
+ ```powershell
227
+ $hc = (Get-Command herdr-core.exe -ErrorAction Stop).Source
228
+ & $hc server status --json
229
+ herdgate-tui stop
230
+ herdgate-tui start --hc "$hc"
231
+ ```
232
+
233
+ If Core is not running, start it locally with `& $hc server start`. The `--hc`
234
+ flag keeps the TUI bridge enabled and adds Core access for `act` devices only.
235
+ The publisher restart interrupts remote connections, not the local TUI server.
236
+ In `--hc` mode, Herdr Mobile sees Core terminals, not TUI panes.
237
+ To expose TUI panes directly instead, use `herdgate-tui start --mobile-tui d_device`
238
+ with the ID of a paired `read` device in this laptop’s room. This opt-in mode
239
+ serves only that device with a read-only Core protocol adapter, needs no `hc`
240
+ binary, and leaves the normal TUI bridge and its existing `act` devices intact.
241
+ Opening an individual pane in Herdr Mobile shows a periodically refreshed
242
+ text snapshot of its visible screen. The adapter does not forward keystrokes,
243
+ resize the pane, or reproduce its full ANSI rendering or scrollback.
244
+
245
+ For a phone explicitly approved to control this laptop, start the publisher
246
+ with `--mobile-tui-act d_device` instead. The device must already have `act`
247
+ scope, and the setting only enables the Core adapter for that device ID.
248
+ Non-observe attach uses Herdr's native terminal session to forward ANSI output,
249
+ keys and viewport resize. Resize changes the pane's real terminal size while
250
+ the controller is attached. Send (paste + Enter), named keys and Interrupt are
251
+ also mapped to TUI actions. The adapter does not implement Core-only features
252
+ such as templates, task lifecycle or file operations. Enable this mode only
253
+ where executing commands in existing panes from the phone is authorized.
254
+
255
+ For the Linux home TUI bridge (laptop → home), the paired host can run:
256
+
257
+ ```sh
258
+ npx --yes @bom0792/herdgate@latest home-tui setup
259
+ npx --yes @bom0792/herdgate@latest home-tui status
260
+ ```
261
+
262
+ Use `home-tui setup --adopt` to migrate the previous home unit created by
263
+ Herdgate; other custom units are not overwritten. The command installs a
264
+ persistent systemd user service, reuses the existing room and TUI socket,
265
+ and does not restart Herdr. Repeat `setup` to update the publisher.
266
+
267
+ On Linux, use `npm run mobile-tui` (or `node src/host/mobile-tui.ts`) as the
268
+ user running Herdr, with
269
+ `HERDGATE_URL`, a dedicated `HERDGATE_ROOM_TOKEN`, and `HERDR_BIN_PATH` set.
270
+ Set `HERDR_SOCKET_PATH` if needed to select the existing TUI session. Without
271
+ `HERDGATE_MOBILE_TUI_ACT_DEVICE`, this publisher is read-only. For interactive
272
+ mode, use a separate room and set that variable to the exact existing `act`
273
+ device ID. The publisher never auto-approves new `act` pairings.
210
274
 
211
275
  ## The PWA (the device side)
212
276
 
package/bin/herdgate.mjs CHANGED
@@ -25,9 +25,15 @@ const help = `herdgate — every machine, one herd
25
25
 
26
26
  herdgate install-tui
27
27
  Install or update the per-user Windows TUI publisher. Does not start it.
28
+ herdgate tui setup [path-to-herdr.exe] [--mobile-tui d_read | --mobile-tui-act d_act | --hc <exe>]
29
+ Install, start and save the selected publisher mode (existing pairing required).
30
+ herdgate tui update
31
+ Install this npm version and restart only the publisher, preserving its mode.
28
32
  herdgate tui start [path-to-herdr.exe]
29
33
  herdgate tui status | stop | version | versions | use <release-id>
30
- Manage the installed publisher without adding it to PATH.`;
34
+ Manage the installed publisher without adding it to PATH.
35
+ herdgate home-tui setup [--adopt] | status | restart | stop
36
+ Manage the Linux TUI publisher as a systemd user service.`;
31
37
 
32
38
  function arg(name, fallback = undefined) {
33
39
  const i = process.argv.indexOf(`--${name}`);
@@ -264,9 +270,11 @@ function runInstalledTui(args) {
264
270
 
265
271
  const [cmd, ...args] = process.argv.slice(2);
266
272
  if (cmd === "setup-host") setupHost();
267
- else if (cmd === "install-tui" || cmd === "tui") {
273
+ else if (["install-tui", "tui", "home-tui"].includes(cmd)) {
268
274
  try {
269
- if (cmd === "install-tui") runNode(join(ROOT, "windows", "install-cli.mjs"), args);
275
+ if (cmd === "home-tui") runNode(join(HERE, "home-tui.mjs"), args);
276
+ else if (cmd === "install-tui") runNode(join(ROOT, "windows", "install-cli.mjs"), args);
277
+ else if (["setup", "update"].includes(args[0])) runNode(join(ROOT, "windows", "setup-tui.mjs"), args);
270
278
  else runInstalledTui(args);
271
279
  } catch (e) {
272
280
  console.error(`herdgate: ${e instanceof Error ? e.message : String(e)}`);
@@ -0,0 +1,121 @@
1
+ // Linux user service, with a durable release outside npm's cache.
2
+ import { execFileSync } from 'node:child_process';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
5
+ import { createRequire } from 'node:module';
6
+ import { homedir } from 'node:os';
7
+ import { dirname, isAbsolute, join } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { readConfig } from '../plugin/server/common.mjs';
10
+
11
+ const unit = 'herdgate-home-tui.service';
12
+ const marker = '# Managed by Herdgate CLI\n';
13
+ const configHome = process.env.XDG_CONFIG_HOME || join(homedir(), '.config');
14
+ const dataHome = process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share');
15
+ const appHome = process.env.HERDR_APP_HOME || join(homedir(), '.config', 'herdr-app');
16
+ const root = join(dataHome, 'herdgate', 'home-tui');
17
+ const unitFile = join(configHome, 'systemd', 'user', unit);
18
+ const systemctl = (...args) => execFileSync('systemctl', ['--user', ...args], { stdio: 'inherit', timeout: 25_000 });
19
+ function replace(path, value) {
20
+ const tmp = `${path}.${randomUUID()}`;
21
+ try {
22
+ writeFileSync(tmp, value, { flag: 'wx', mode: 0o600 });
23
+ renameSync(tmp, path);
24
+ } finally { rmSync(tmp, { force: true }); }
25
+ }
26
+ function installedUnit() {
27
+ if (!existsSync(unitFile)) return null;
28
+ if (!lstatSync(unitFile).isFile()) throw new Error(`refusing to use a non-regular unit: ${unitFile}`);
29
+ return readFileSync(unitFile, 'utf8');
30
+ }
31
+ function legacyUnit(text) {
32
+ return text.startsWith('[Unit]\nDescription=Herdgate publisher for the home Herdr TUI\n') &&
33
+ text.includes('Environment=HERDR_PLUGIN_CONFIG_DIR=%h/.config/herdr-app/herdgate/config\n') &&
34
+ /^ExecStart=%h\/\.nvm\/versions\/node\/v\d+\.\d+\.\d+\/bin\/node %h\/source\/herdgate\/plugin\/server\/index\.mjs serve$/m.test(text);
35
+ }
36
+ const sysPath = (value) => {
37
+ if (!isAbsolute(value) || /[\r\n\0]/.test(value)) throw new Error('systemd paths must be absolute and on one line');
38
+ return '"' + value.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('%', '%%') + '"';
39
+ };
40
+ function release() {
41
+ const server = fileURLToPath(new URL('../plugin/server/', import.meta.url));
42
+ const require = createRequire(import.meta.url);
43
+ const wsManifest = require.resolve('ws/package.json');
44
+ const runtime = readdirSync(server).filter(n => n.endsWith('.mjs')).sort();
45
+ const hash = createHash('sha256').update(readFileSync(wsManifest));
46
+ for (const name of runtime) hash.update(name + '\0').update(readFileSync(join(server, name)));
47
+ const releases = join(root, 'releases');
48
+ mkdirSync(releases, { recursive: true, mode: 0o700 });
49
+ const dest = join(releases, hash.digest('hex').slice(0, 24));
50
+ if (!existsSync(dest)) {
51
+ const stage = mkdtempSync(join(releases, '.stage-'));
52
+ try {
53
+ const plugin = join(stage, 'plugin', 'server');
54
+ mkdirSync(plugin, { recursive: true });
55
+ for (const name of runtime) cpSync(join(server, name), join(plugin, name));
56
+ mkdirSync(join(stage, 'node_modules'));
57
+ cpSync(dirname(wsManifest), join(stage, 'node_modules', 'ws'), { recursive: true });
58
+ renameSync(stage, dest);
59
+ } finally { rmSync(stage, { force: true, recursive: true }); }
60
+ }
61
+ if (!lstatSync(dest).isDirectory()) throw new Error('invalid installed TUI release');
62
+ return dest;
63
+ }
64
+ async function setup(args) {
65
+ const adopt = args.includes('--adopt');
66
+ if (args.some(a => a !== '--adopt')) throw new Error('usage: herdgate home-tui setup [--adopt]');
67
+ mkdirSync(root, { recursive: true, mode: 0o700 });
68
+ const lock = join(root, '.installing');
69
+ mkdirSync(lock);
70
+ try {
71
+ const old = installedUnit();
72
+ if (old && !old.startsWith(marker) && !(adopt && legacyUnit(old))) {
73
+ throw new Error('existing service is not CLI-managed; only the previous Herdgate home service can be migrated with --adopt');
74
+ }
75
+ const herdr = process.env.HERDR_BIN_PATH || join(homedir(), '.local', 'bin', 'herdr');
76
+ const socket = process.env.HERDR_SOCKET_PATH || join(configHome, 'herdr', 'herdr.sock');
77
+ const config = join(appHome, 'herdgate', 'config');
78
+ const state = join(appHome, 'herdgate', 'state');
79
+ const cfg = readConfig(join(config, 'herdgate.env'));
80
+ if (!cfg.HERDGATE_ROOM_TOKEN || !cfg.HERDGATE_URL) throw new Error('pair the home room first; herdgate.env is missing or incomplete');
81
+ const gate = new URL(cfg.HERDGATE_URL);
82
+ if (gate.protocol !== 'https:' || gate.username || gate.password) throw new Error('a credential-free HTTPS Gate URL is required');
83
+ for (const path of [herdr, socket, config, state, root]) sysPath(path);
84
+ const status = JSON.parse(execFileSync(herdr, ['status', 'server', '--json'], { encoding: 'utf8', timeout: 5_000, env: { ...process.env, HERDR_SOCKET_PATH: socket, HERDR_SESSION: 'default' } }));
85
+ if (!status.running || status.compatible !== true) throw new Error('start a compatible Herdr TUI server before running setup');
86
+ const runtime = release();
87
+ const env = { HERDGATE_PUBLISHER_CHILD:'1', HERDR_PLUGIN_ID:'dev.herdgate.host', HERDR_PLUGIN_CONFIG_DIR:config, HERDR_PLUGIN_STATE_DIR:state, HERDR_BIN_PATH:herdr, HERDR_SOCKET_PATH:socket, HERDGATE_HERDR_SESSION:'default' };
88
+ const lines = Object.entries(env).map(([k, v]) => `Environment=${isAbsolute(v) ? sysPath(`${v}`).replace(/^"/, `"${k}=`) : `${k}=${v}`}`).join('\n');
89
+ const next = `${marker}[Unit]\nDescription=Herdgate publisher for the home Herdr TUI\nAfter=network.target herdgate.service\n\n[Service]\nType=simple\n${lines}\nExecStart=:${sysPath(process.execPath)} ${sysPath(join(runtime,'plugin/server/index.mjs'))} serve\nRestart=always\nRestartSec=2\nUMask=0077\nNoNewPrivileges=true\n\n[Install]\nWantedBy=default.target\n`;
90
+ mkdirSync(dirname(unitFile), { recursive: true });
91
+ if (old !== next) replace(unitFile, next);
92
+ try {
93
+ if (old !== next) systemctl('daemon-reload');
94
+ if (old && old !== next) {
95
+ systemctl('enable', unit);
96
+ systemctl('restart', unit);
97
+ } else systemctl('enable', '--now', unit);
98
+ } catch (error) {
99
+ if (old !== next) {
100
+ if (old) replace(unitFile, old); else rmSync(unitFile, { force: true });
101
+ systemctl('daemon-reload');
102
+ if (old) systemctl('restart', unit);
103
+ }
104
+ throw error;
105
+ }
106
+ console.log('Herdgate home publisher service started; no Herdr process was restarted.');
107
+ } finally { rmSync(lock, { recursive: true, force: true }); }
108
+ }
109
+ try {
110
+ const [action, ...args] = process.argv.slice(2);
111
+ if (process.platform !== 'linux') throw new Error('home-tui requires Linux with a systemd user manager');
112
+ if (action === 'setup') await setup(args);
113
+ else if (!args.length && ['status', 'restart', 'stop'].includes(action)) {
114
+ const existing = installedUnit();
115
+ if (!existing || !(existing.startsWith(marker) || legacyUnit(existing))) throw new Error('run herdgate home-tui setup first');
116
+ systemctl(action, ...(action === 'status' ? ['--no-pager'] : []), unit);
117
+ } else throw new Error('usage: herdgate home-tui setup [--adopt] | status | restart | stop');
118
+ } catch (error) {
119
+ console.error('herdgate home-tui: ' + error.message);
120
+ process.exitCode = 1;
121
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bom0792/herdgate",
3
- "version": "0.9.21",
3
+ "version": "0.9.26",
4
4
  "description": "Cloud relay hub for herdr-core: every machine dials out, phones and browsers follow (PWA + SSH leg, E2E payloads).",
5
5
  "type": "module",
6
6
  "engines": {
@@ -13,6 +13,8 @@
13
13
  "test": "node --test test/*.test.ts",
14
14
  "check": "tsc -p tsconfig.json",
15
15
  "ssh-bridge": "node src/cloud/ssh-bridge.ts",
16
+ "ssh-tcp-edge": "node src/cloud/ssh-tcp-edge.ts",
17
+ "mobile-tui": "node src/host/mobile-tui.ts",
16
18
  "postinstall": "node scripts/patch-ssh2.mjs"
17
19
  },
18
20
  "dependencies": {
@@ -10,6 +10,7 @@ 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";
15
16
  import { registerPublisher } from "./publisher-tui-lifecycle.mjs";
@@ -259,6 +260,12 @@ async function publisherLoop() {
259
260
  const ssh = createSshBridge({
260
261
  session: cfg.HERDGATE_HERDR_SESSION || undefined,
261
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,
262
269
  send: (device, payload) => {
263
270
  // sshd is the SSH endpoint; a concurrent PWA session must not seal these frames.
264
271
  if (wsRef?.readyState === 1) wsRef.send(JSON.stringify({ v: 1, t: "frame", device, payload }));
@@ -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
+ }