@bom0792/herdgate 0.9.19 → 0.9.20

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bom0792/herdgate",
3
- "version": "0.9.19",
3
+ "version": "0.9.20",
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": {
@@ -64,6 +64,33 @@ export async function herdrSnapshot(bin, timeoutMs = 8_000) {
64
64
  return parsed?.result?.snapshot ?? parsed?.snapshot ?? parsed;
65
65
  }
66
66
 
67
+ /** Live panes — the PWA's terminal picker. One row per pane, grouped by workspace there. */
68
+ export async function herdrPanes(bin, timeoutMs = 8_000) {
69
+ const { stdout } = await run(bin, ["pane", "list"], { timeout: timeoutMs, maxBuffer: 8 << 20 });
70
+ const parsed = JSON.parse(stdout);
71
+ const panes = parsed?.result?.panes ?? parsed?.panes ?? [];
72
+ return panes
73
+ .filter((p) => p && typeof p.pane_id === "string")
74
+ .map((p) => ({
75
+ id: p.pane_id,
76
+ workspace: typeof p.workspace_id === "string" ? p.workspace_id : "",
77
+ agent: typeof p.agent === "string" ? p.agent : null,
78
+ status: typeof p.agent_status === "string" ? p.agent_status : "unknown",
79
+ cwd: typeof p.cwd === "string" ? p.cwd : "",
80
+ title: typeof p.terminal_title_stripped === "string" ? p.terminal_title_stripped : typeof p.terminal_title === "string" ? p.terminal_title : "",
81
+ }));
82
+ }
83
+
84
+ /** One pane's screen as ANSI text — the PWA renders the colors itself. */
85
+ export async function herdrRead(bin, target, lines = 40, timeoutMs = 8_000) {
86
+ const { stdout } = await run(
87
+ bin,
88
+ ["agent", "read", String(target), "--source", "visible", "--lines", String(lines), "--format", "ansi"],
89
+ { timeout: timeoutMs, maxBuffer: 8 << 20 },
90
+ );
91
+ return stdout;
92
+ }
93
+
67
94
  export function summarize(snap) {
68
95
  const ws = Array.isArray(snap?.workspaces) ? snap.workspaces : [];
69
96
  const agents = Array.isArray(snap?.agents) ? snap.agents : [];
@@ -10,7 +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 { dirs, readConfig, writeConfig, readState, writeState, herdrSnapshot, summarize } from "./common.mjs";
13
+ import { dirs, readConfig, writeConfig, readState, writeState, herdrSnapshot, summarize, herdrPanes, herdrRead } from "./common.mjs";
14
14
  import { createSshBridge } from "./ssh.mjs";
15
15
  import { HostChannel, b64d, b64e, fingerprint, generateKeyPair } from "./e2e.mjs";
16
16
 
@@ -198,7 +198,9 @@ async function publisherLoop() {
198
198
  }
199
199
  return e2eSelf;
200
200
  };
201
- const e2eSessions = new Map(); // deviceId → HostChannel
201
+ const e2eSessions = new Map();
202
+ /** Per-device last-call times for the subprocess-backed term.* ops (1/s each). */
203
+ const termThrottle = new Map();
202
204
  /** null = not an e2e payload; {reply} = handshake answer to send; {inner} = decrypted device payload. */
203
205
  const e2eOnDevice = async (device, payload) => {
204
206
  if (payload && typeof payload === "object" && typeof payload.op === "string" && payload.op.startsWith("e2e")) log(`e2e: op ${payload.op} from ${device}`);
@@ -333,6 +335,38 @@ async function publisherLoop() {
333
335
  lastSig = "";
334
336
  return void publish(ws);
335
337
  }
338
+ // Live terminal access, read-only: the panes list and one pane's ANSI screen.
339
+ // Subprocess-backed, so both ops are throttled per device (a phone's poll must
340
+ // not fork `herdr` in a tight loop) and the target string is whitelisted hard.
341
+ if (op === "term.list") {
342
+ const now = Date.now();
343
+ const last = termThrottle.get(`list:${m.device}`) ?? 0;
344
+ if (now - last < 1_000) return void replyTo({ op: "error", code: "busy", message: "term.list is throttled (1/s)" });
345
+ termThrottle.set(`list:${m.device}`, now);
346
+ try {
347
+ const panes = await herdrPanes(D.herdrBin);
348
+ return void replyTo({ op: "term.list", panes });
349
+ } catch (e) {
350
+ return void replyTo({ op: "error", code: "herdr", message: `pane list failed: ${e instanceof Error ? e.message : String(e)}` });
351
+ }
352
+ }
353
+ if (op === "term.read") {
354
+ const target = typeof payload.target === "string" ? payload.target : "";
355
+ const lines = Math.max(10, Math.min(120, Number(payload.lines) || 40));
356
+ if (!/^[A-Za-z0-9_:.-]{1,64}$/.test(target)) {
357
+ return void replyTo({ op: "error", code: "bad-target", message: "term.read needs a pane id" });
358
+ }
359
+ const now = Date.now();
360
+ const last = termThrottle.get(`read:${m.device}`) ?? 0;
361
+ if (now - last < 1_000) return void replyTo({ op: "error", code: "busy", message: "term.read is throttled (1/s)" });
362
+ termThrottle.set(`read:${m.device}`, now);
363
+ try {
364
+ const ansi = await herdrRead(D.herdrBin, target, lines);
365
+ return void replyTo({ op: "term.read", target, ansi });
366
+ } catch (e) {
367
+ return void replyTo({ op: "error", code: "herdr", message: `read failed: ${e instanceof Error ? e.message : String(e)}` });
368
+ }
369
+ }
336
370
  return void replyTo({ op: "error", code: "read-only", message: `dev.herdgate.host has no op ${String(op)}` });
337
371
  }
338
372
  if (m.t === "pair.request") {
package/src/host/herdr.ts CHANGED
@@ -155,6 +155,46 @@ export async function readHerdrView(o: HerdrReadOptions = {}): Promise<HerdrView
155
155
  return mapSnapshot(parsed);
156
156
  }
157
157
 
158
+ export interface HerdrPane {
159
+ id: string;
160
+ workspace: string;
161
+ agent: string | null;
162
+ status: string;
163
+ cwd: string;
164
+ title: string;
165
+ }
166
+
167
+ /** Live panes (`herdr pane list`), mapped for the term.list op. */
168
+ export async function readHerdrPanes(o: HerdrReadOptions = {}): Promise<HerdrPane[]> {
169
+ const bin = o.bin ?? process.env.HERDGATE_HERDR_BIN ?? "herdr";
170
+ const { stdout } = await run(bin, ["pane", "list"], { timeout: o.timeoutMs ?? 5_000, maxBuffer: MAX_SNAPSHOT_BYTES, env: o.env ?? process.env });
171
+ const parsed = JSON.parse(stdout) as { result?: { panes?: unknown[] }; panes?: unknown[] };
172
+ const panes = parsed?.result?.panes ?? parsed?.panes ?? [];
173
+ return panes
174
+ .filter((p): p is Record<string, unknown> => Boolean(p) && typeof (p as Record<string, unknown>).pane_id === "string")
175
+ .map((p) => ({
176
+ id: String(p.pane_id),
177
+ workspace: typeof p.workspace_id === "string" ? p.workspace_id : "",
178
+ agent: typeof p.agent === "string" ? p.agent : null,
179
+ status: typeof p.agent_status === "string" ? p.agent_status : "unknown",
180
+ cwd: typeof p.cwd === "string" ? p.cwd : "",
181
+ title: typeof p.terminal_title_stripped === "string" ? p.terminal_title_stripped : typeof p.terminal_title === "string" ? p.terminal_title : "",
182
+ }));
183
+ }
184
+
185
+ /** One pane's visible screen as ANSI (`herdr agent read --format ansi`). */
186
+ export async function readHerdrTerm(target: string, lines = 40, o: HerdrReadOptions = {}): Promise<string> {
187
+ const bin = o.bin ?? process.env.HERDGATE_HERDR_BIN ?? "herdr";
188
+ if (!/^[A-Za-z0-9_:.-]{1,64}$/.test(target)) throw new Error("bad pane id");
189
+ const n = Math.max(10, Math.min(120, Math.trunc(lines) || 40));
190
+ const { stdout } = await run(bin, ["agent", "read", target, "--source", "visible", "--lines", String(n), "--format", "ansi"], {
191
+ timeout: o.timeoutMs ?? 5_000,
192
+ maxBuffer: MAX_SNAPSHOT_BYTES,
193
+ env: o.env ?? process.env,
194
+ });
195
+ return stdout;
196
+ }
197
+
158
198
  /** What the host can push/drive; the agent supplies it (see `HerdrAdapter.attach`). */
159
199
  export interface HostLink {
160
200
  send(device: string, payload: unknown): void;
@@ -191,6 +231,8 @@ export class HerdrAdapter implements AgentAdapter {
191
231
  readonly #log: (line: string) => void;
192
232
  #link: HostLink | null = null;
193
233
  #view: HerdrView | null = null;
234
+ /** Per-device last-call times for the subprocess-backed term.* ops (1/s each). */
235
+ #termThrottle = new Map<string, number>();
194
236
  #sig = "";
195
237
  #lastError: string | null = null;
196
238
  #timer: NodeJS.Timeout | null = null;
@@ -257,6 +299,30 @@ export class HerdrAdapter implements AgentAdapter {
257
299
  }
258
300
  case "ping":
259
301
  return link.send(device, { op: "pong", n: (payload as { n?: unknown }).n ?? null, at: (this.#o.now?.() ?? new Date()).toISOString() });
302
+ case "term.list": {
303
+ // Subprocess-backed: throttle per device so a poll loop cannot fork herdr hot.
304
+ const now = this.#o.now?.() ?? new Date();
305
+ const last = this.#termThrottle.get(`list:${device}`) ?? 0;
306
+ if (now.getTime() - last < 1_000) return link.send(device, { op: "error", code: "busy", message: "term.list is throttled (1/s)" });
307
+ this.#termThrottle.set(`list:${device}`, now.getTime());
308
+ readHerdrPanes()
309
+ .then((panes) => link.send(device, { op: "term.list", panes }))
310
+ .catch((e: unknown) => link.send(device, { op: "error", code: "herdr", message: `pane list failed: ${e instanceof Error ? e.message : String(e)}` }));
311
+ return;
312
+ }
313
+ case "term.read": {
314
+ const target = typeof (payload as { target?: unknown }).target === "string" ? (payload as { target: string }).target : "";
315
+ if (!/^[A-Za-z0-9_:.-]{1,64}$/.test(target)) return link.send(device, { op: "error", code: "bad-target", message: "term.read needs a pane id" });
316
+ const lines = Math.max(10, Math.min(120, Number((payload as { lines?: unknown }).lines) || 40));
317
+ const nowT = this.#o.now?.() ?? new Date();
318
+ const lastT = this.#termThrottle.get(`read:${device}`) ?? 0;
319
+ if (nowT.getTime() - lastT < 1_000) return link.send(device, { op: "error", code: "busy", message: "term.read is throttled (1/s)" });
320
+ this.#termThrottle.set(`read:${device}`, nowT.getTime());
321
+ readHerdrTerm(target, lines)
322
+ .then((ansi) => link.send(device, { op: "term.read", target, ansi }))
323
+ .catch((e: unknown) => link.send(device, { op: "error", code: "herdr", message: `read failed: ${e instanceof Error ? e.message : String(e)}` }));
324
+ return;
325
+ }
260
326
  default:
261
327
  // The read-only invariant lives HERE: the cloud cannot inspect payloads, so the
262
328
  // host is the last trusted decision point for "this device may not do that".
package/src/web/app.css CHANGED
@@ -310,3 +310,22 @@ dialog::backdrop {
310
310
  border-radius: 6px;
311
311
  }
312
312
  .sshkeys .keyrow { margin-top: 8px; }
313
+
314
+ /* Live terminals (read-only) */
315
+ .termbody { display: flex; flex-direction: column; gap: 8px; }
316
+ .termlist .termname { text-align: left; }
317
+ .termrow { padding: 2px 0; }
318
+ .termbar { display: flex; justify-content: space-between; align-items: center; gap: 8px; }
319
+ .termscreen {
320
+ max-height: 60vh;
321
+ overflow: auto;
322
+ background: #14161a; /* a terminal is dark: keep it dark in light mode too */
323
+ color: #cfd3da;
324
+ border: 1px solid #2a2d33;
325
+ border-radius: 8px;
326
+ padding: 10px 12px;
327
+ font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace;
328
+ white-space: pre-wrap;
329
+ word-break: break-word;
330
+ margin: 0;
331
+ }
package/src/web/app.js CHANGED
@@ -11,7 +11,7 @@
11
11
  // - the token lives in localStorage on this device and is never sent anywhere but the
12
12
  // cloud's own WS endpoint.
13
13
 
14
- const BUILD = "v0.9.19";
14
+ const BUILD = "v0.9.20";
15
15
 
16
16
  const $ = (id) => document.getElementById(id);
17
17
  const TOKEN_KEY = "herdgate.token";
@@ -107,6 +107,12 @@ const state = {
107
107
  roomId: null,
108
108
  view: null,
109
109
  viewError: null,
110
+ terms: null,
111
+ termTarget: null,
112
+ termAnsi: null,
113
+ termTimer: null,
114
+ termBody: null,
115
+ termPre: null,
110
116
  retry: 0,
111
117
  closedByUs: false,
112
118
  };
@@ -267,6 +273,30 @@ function renderRoom() {
267
273
  box.append(p);
268
274
  }
269
275
 
276
+ // Live terminals (read-only): the host's own panes — pick one and watch its
277
+ // ANSI screen. Everything rides the same frames (E2E when paired), no new trust.
278
+ if (room?.online) {
279
+ const tblock = document.createElement("details");
280
+ tblock.className = "terms";
281
+ const ts = document.createElement("summary");
282
+ ts.textContent = "Live terminals — this machine's panes, read-only";
283
+ tblock.append(ts);
284
+ const tbody = document.createElement("div");
285
+ tbody.className = "termbody";
286
+ tblock.append(tbody);
287
+ tblock.addEventListener("toggle", () => {
288
+ if (tblock.open && !state.terms) send({ t: "frame", payload: { op: "term.list" } });
289
+ });
290
+ box.append(tblock);
291
+ state.termBody = tbody;
292
+ renderTerms();
293
+ if (state.termTarget) {
294
+ // The view rebuilds this node; keep the live pane ticking without a new poll.
295
+ paintTerm();
296
+ if (!state.termTimer) startTerm(state.termTarget);
297
+ }
298
+ }
299
+
270
300
  // The SSH leg: this device's own key dials the gate. In the Herdr phone app, add a
271
301
  // machine with this host/port and the key shown once at pair time.
272
302
  if (state.deviceSecret && state.deviceId) {
@@ -474,6 +504,162 @@ function renderRoom() {
474
504
  }
475
505
  }
476
506
 
507
+ // ---- live terminals (read-only) ---------------------------------------------
508
+
509
+ function startTerm(target) {
510
+ stopTerm(false);
511
+ state.termTarget = target;
512
+ state.termAnsi = null;
513
+ send({ t: "frame", payload: { op: "term.read", target, lines: 40 } });
514
+ state.termTimer = setInterval(() => {
515
+ if (!state.termTarget || !state.roomId) return stopTerm();
516
+ send({ t: "frame", payload: { op: "term.read", target: state.termTarget, lines: 40 } });
517
+ }, 2_000);
518
+ renderTerms();
519
+ }
520
+
521
+ function stopTerm(rerender = true) {
522
+ if (state.termTimer) clearInterval(state.termTimer);
523
+ state.termTimer = null;
524
+ state.termTarget = null;
525
+ state.termAnsi = null;
526
+ if (rerender) renderTerms();
527
+ }
528
+
529
+ /** The panes list + the live pane, inside the details' body (survives view re-renders). */
530
+ function renderTerms() {
531
+ const body = state.termBody;
532
+ if (!body) return;
533
+ body.replaceChildren();
534
+ if (state.termTarget) {
535
+ const bar = document.createElement("div");
536
+ bar.className = "termbar";
537
+ const name = document.createElement("span");
538
+ name.className = "muted small";
539
+ name.textContent = `${state.termTarget} — live, refreshes every 2s`;
540
+ const stop = document.createElement("button");
541
+ stop.type = "button";
542
+ stop.className = "link";
543
+ stop.textContent = "close";
544
+ stop.addEventListener("click", () => stopTerm());
545
+ bar.append(name, stop);
546
+ body.append(bar);
547
+ const pre = document.createElement("pre");
548
+ pre.className = "termscreen";
549
+ pre.textContent = state.termAnsi ?? "waiting for the pane…";
550
+ body.append(pre);
551
+ state.termPre = pre;
552
+ paintTerm();
553
+ return;
554
+ }
555
+ const list = document.createElement("div");
556
+ list.className = "termlist";
557
+ const btn = document.createElement("button");
558
+ btn.type = "button";
559
+ btn.className = "link";
560
+ btn.textContent = "refresh the pane list";
561
+ btn.addEventListener("click", () => send({ t: "frame", payload: { op: "term.list" } }));
562
+ list.append(btn);
563
+ const panes = state.terms ?? null;
564
+ if (panes === null) {
565
+ list.append(note("loading…", "muted"));
566
+ } else if (!panes.length) {
567
+ list.append(note("no panes — is a workspace open on the machine?", "muted"));
568
+ } else {
569
+ const labels = new Map((state.view?.workspaces ?? []).map((w) => [w.id, w.label]));
570
+ for (const p of panes) {
571
+ const row = document.createElement("div");
572
+ row.className = "keyrow termrow";
573
+ const label = document.createElement("button");
574
+ label.type = "button";
575
+ label.className = "link termname";
576
+ const ws = labels.get(p.workspace) || p.workspace;
577
+ label.textContent = `${ws} · ${p.agent ? `${p.agent} (${p.status})` : p.title || "terminal"}`;
578
+ label.title = `${p.cwd} — ${p.id}`;
579
+ label.addEventListener("click", () => startTerm(p.id));
580
+ row.append(label);
581
+ list.append(row);
582
+ }
583
+ }
584
+ body.append(list);
585
+ }
586
+
587
+ function paintTerm() {
588
+ const pre = state.termPre;
589
+ if (!pre || !state.termAnsi) return;
590
+ pre.replaceChildren(...ansiToNodes(state.termAnsi));
591
+ pre.scrollTop = pre.scrollHeight;
592
+ }
593
+
594
+ /** SGR-only ANSI → DOM nodes: colors (palette + truecolor), bold. Cursor and other
595
+ * sequences are dropped — this is a reading view, not an emulator. No innerHTML:
596
+ * every byte from the wire becomes text nodes, never markup. */
597
+ function ansiToNodes(s) {
598
+ const pal = ["#5b5b5b", "#d54e53", "#5db542", "#e5c07b", "#61afef", "#c678dd", "#56b6c2", "#acacac", "#8a8a8a", "#ff6f6f", "#8ce07d", "#ffe08a", "#93c5fd", "#e2a2ff", "#8be9fd", "#ffffff"];
599
+ const out = [];
600
+ let fg = null;
601
+ let bg = null;
602
+ let bold = false;
603
+ let i = 0;
604
+ s = String(s).replace(/\r\n?/g, "\n");
605
+ const flush = (text) => {
606
+ if (!text) return;
607
+ if (fg === null && bg === null && !bold) {
608
+ out.push(document.createTextNode(text));
609
+ return;
610
+ }
611
+ const span = document.createElement("span");
612
+ if (fg) span.style.color = bold ? `color-mix(in srgb, ${fg} 70%, white)` : fg;
613
+ if (bg) span.style.background = bg;
614
+ if (bold && !fg) span.style.fontWeight = "600";
615
+ span.textContent = text;
616
+ out.push(span);
617
+ };
618
+ while (i < s.length) {
619
+ if (s.charCodeAt(i) === 27) {
620
+ const rest = s.slice(i);
621
+ let m = /^\x1b\[([0-9;]*)([A-Za-z])/.exec(rest);
622
+ if (m) {
623
+ if (m[2] === "m") {
624
+ const parts = m[1] === "" ? [0] : m[1].split(";").map((x) => (x === "" ? 0 : Number(x)));
625
+ for (let k = 0; k < parts.length; k += 1) {
626
+ const p = parts[k];
627
+ if (p === 0) { fg = bg = null; bold = false; }
628
+ else if (p === 1) bold = true;
629
+ else if (p === 22) bold = false;
630
+ else if (p === 39) fg = null;
631
+ else if (p === 49) bg = null;
632
+ else if (p >= 30 && p <= 37) fg = pal[p - 30];
633
+ else if (p >= 90 && p <= 97) fg = pal[p - 90 + 8];
634
+ else if (p >= 40 && p <= 47) bg = pal[p - 40];
635
+ else if (p >= 100 && p <= 107) bg = pal[p - 100 + 8];
636
+ else if ((p === 38 || p === 48) && parts[k + 1] === 2) {
637
+ const c = `rgb(${parts[k + 2] || 0},${parts[k + 3] || 0},${parts[k + 4] || 0})`;
638
+ if (p === 38) fg = c; else bg = c;
639
+ k += 4;
640
+ } else if ((p === 38 || p === 48) && parts[k + 1] === 5) {
641
+ const n8 = parts[k + 2] || 0;
642
+ const c = pal[n8 % 16];
643
+ if (p === 38) fg = c; else bg = c;
644
+ k += 2;
645
+ }
646
+ }
647
+ }
648
+ i += m[0].length;
649
+ continue;
650
+ }
651
+ m = /^\x1b\][^\x07]*(?:\x07|\x1b\\)/.exec(rest) || /^\x1b./.exec(rest);
652
+ i += m ? m[0].length : 1;
653
+ continue;
654
+ }
655
+ let j = s.indexOf("\x1b", i);
656
+ if (j < 0) j = s.length;
657
+ flush(s.slice(i, j));
658
+ i = j;
659
+ }
660
+ return out;
661
+ }
662
+
477
663
  function note(message, kind) {
478
664
  const p = document.createElement("p");
479
665
  p.className = kind === "error" ? "error" : "muted";
@@ -688,6 +874,18 @@ function applyPayload(payload) {
688
874
  if (payload && typeof payload === "object" && payload.op === "view") {
689
875
  state.view = payload.view;
690
876
  state.viewError = null;
877
+ } else if (payload && typeof payload === "object" && payload.op === "term.list") {
878
+ state.terms = Array.isArray(payload.panes) ? payload.panes : [];
879
+ renderTerms();
880
+ return;
881
+ } else if (payload && typeof payload === "object" && payload.op === "term.read") {
882
+ if (payload.target === state.termTarget && typeof payload.ansi === "string") {
883
+ state.termAnsi = payload.ansi;
884
+ paintTerm();
885
+ }
886
+ return;
887
+ } else if (payload && typeof payload === "object" && payload.op === "error" && payload.code === "busy") {
888
+ return; // our poll raced the host's 1/s throttle — the next tick catches up
691
889
  } else if (payload && typeof payload === "object" && payload.op === "error") {
692
890
  // The host refused or could not answer: an op we may not use, or its Herdr is down.
693
891
  state.viewError = payload.message ?? payload.code ?? "the host refused";
Binary file
package/src/web/sw.js CHANGED
@@ -3,7 +3,7 @@
3
3
  //
4
4
  // Bump VERSION when a shell file changes; old caches are dropped on activate.
5
5
 
6
- const VERSION = "herdgate-v10";
6
+ const VERSION = "herdgate-v11";
7
7
  const SHELL = ["/", "/app.css", "/e2e.js", "/app.js", "/app.webmanifest", "/icons/icon.svg"];
8
8
 
9
9
  self.addEventListener("install", (event) => {