@bom0792/herdgate 0.9.36 → 0.9.38

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.
@@ -1,20 +1,41 @@
1
1
  #!/usr/bin/env node
2
2
  // Subset of the Core API for TUI panes. Input requires explicit local opt-in.
3
- import { execFile } from "node:child_process";
4
3
  import { createHash } from "node:crypto";
4
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
5
+ import { open as openFile } from "node:fs/promises";
5
6
  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";
7
+ import { dirname, join } from "node:path";
8
+ import { stripVTControlCharacters } from "node:util";
9
+ import { cksum, openShellManager, openTerminal, PaneLiveInputQueue, validDimension } from "./mobile-tui-stream.mjs";
9
10
 
10
- const invoke = promisify(execFile);
11
11
  const herdr = process.env.HERDR_BIN_PATH || join(homedir(), ".local/bin/herdr");
12
12
  const name = process.env.HERDGATE_HOST_NAME || "home-tui-mobile";
13
13
  const digest = (text) => createHash("sha256").update(text).digest("hex");
14
14
  const core = { id: digest(`herdgate-tui:${hostname()}:${name}`).slice(0, 32), name };
15
15
  const version = "0.1.21"; // Core wire compatibility target, not a running Core binary.
16
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"];
17
+ const inputMethods = ["terminal.send", "terminal.keys", "terminal.interrupt", "terminal.run", "terminal.kill", "terminal.label", "terminal.keep", "doc.set"];
18
+
19
+ // Labels the app sets on panes outlive the adapter in a sidecar; seating labels stay ours.
20
+ const labelsFile = join(homedir(), ".config", "herdgate", "tui-labels.json");
21
+ let appLabels = null;
22
+ function appLabelsFor(paneId) {
23
+ if (appLabels === null) {
24
+ try {
25
+ const stored = JSON.parse(readFileSync(labelsFile, "utf8"));
26
+ appLabels = new Map(Object.entries(stored).filter(([id, l]) => typeof id === "string" && l && typeof l === "object" && !Array.isArray(l)).slice(0, 500));
27
+ } catch { appLabels = new Map(); }
28
+ }
29
+ return appLabels.get(paneId) || {};
30
+ }
31
+ function saveAppLabels() {
32
+ try {
33
+ mkdirSync(dirname(labelsFile), { recursive: true });
34
+ const tmp = labelsFile + ".tmp";
35
+ writeFileSync(tmp, JSON.stringify(Object.fromEntries([...appLabels].slice(-500))));
36
+ renameSync(tmp, labelsFile);
37
+ } catch { /* labels are best-effort */ }
38
+ }
18
39
  const args = process.argv.slice(2);
19
40
  const interactive = args[0] === "--interactive";
20
41
  if (interactive) args.shift();
@@ -23,12 +44,22 @@ const inputText = (text) => typeof text === "string" && text.length > 0 && !text
23
44
  const frameKind = { data: 0, credit: 1, close: 2, resize: 3 };
24
45
  const cap = 128 * 1024;
25
46
  const windowBytes = 64 * 1024;
26
- const maxStreams = 2;
27
- const pollMs = 1_250;
47
+ const maxStreams = 16; // A desktop space shows several panes at once; the phone showed one or two.
48
+ const pollMs = Math.max(250, Number.parseInt(process.env.HERDGATE_TUI_POLL_MS ?? "1250", 10) || 1250);
28
49
  const startedAt = Date.now();
29
50
  let cache;
30
51
  let cacheUntil = 0;
31
- const run = async (args) => (await invoke(herdr, args, { timeout: 4_000, maxBuffer: 512 * 1024, windowsHide: true, shell: false })).stdout;
52
+ // One persistent /bin/sh speaks for every Herdr call: each request is framed by a unique
53
+ // marker, the shell is probed (`true`) before it counts as alive, and one channel failure
54
+ // kills the whole generation — the written request is never retried, later requests fall
55
+ // back to one exec per command, and only an explicit reinit() opens the next generation.
56
+ const shells = openShellManager();
57
+ const shellQuote = (word) => `'${String(word).replace(/'/g, "'\\''")}'`;
58
+ const run = async (args) => {
59
+ const { stdout, code } = await shells.execute([herdr, ...args].map(shellQuote).join(" "));
60
+ if (code !== 0) throw Object.assign(new Error(`herdr ${args[0]} exited ${code}`), { definitive: true });
61
+ return stdout.toString("utf8");
62
+ };
32
63
 
33
64
  async function panes() {
34
65
  if (cache && Date.now() < cacheUntil) return cache;
@@ -36,18 +67,421 @@ async function panes() {
36
67
  if (!Array.isArray(parsed?.result?.panes)) throw new Error("Herdr pane list unavailable");
37
68
  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
69
  .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: {
70
+ let title = clip(p.terminal_title_stripped || p.terminal_title || p.pane_id, 120);
71
+ // Herdr's per-pane agent state feeds the core's own status word (a 7501 record
72
+ // shape: an object with a state, never a bare string).
73
+ const status = p.agent_status === "working" ? { state: "working" } : null;
74
+ const ws = typeof p.workspace_id === "string" && /^[a-zA-Z0-9_:.-]{1,128}$/.test(p.workspace_id) ? p.workspace_id : null;
75
+ const tab = typeof p.tab_id === "string" && /^[a-zA-Z0-9_:.-]{1,128}$/.test(p.tab_id) ? p.tab_id : null;
76
+ // The desktop app seats terminals by these labels; ids stay stable per workspace/tab.
77
+ const labels = { ...appLabelsFor(p.pane_id), ...(ws && tab ? { "herdr.space": "sp" + digest("space:" + ws).slice(0, 30), "herdr.tab": "tb" + digest("tab:" + tab).slice(0, 30) } : {}), where: clip(p.workspace_id, 128) };
78
+ return { id: p.pane_id, workspace: ws, tab, target: typeof p.terminal_id === "string" && /^term_[a-zA-Z0-9]{1,96}$/.test(p.terminal_id) ? p.terminal_id : null, terminal: {
41
79
  address: "t" + digest(p.pane_id).slice(0, 12), title, name: null, argv: [], cwd: clip(p.cwd, 512),
42
80
  state: "live", created_ms: 0, screen: "inexact", cols: 80, rows: 24,
43
- labels: { where: clip(p.workspace_id, 128) }, turn: 0,
81
+ labels, turn: 0, status,
44
82
  } };
45
83
  });
46
84
  cacheUntil = Date.now() + 1_000;
47
85
  return cache;
48
86
  }
49
87
 
88
+ let rectCache = new Map(); // pane_id → { x, y, width, height }
89
+ let rectCacheAt = 0;
90
+ /** pane_id → rect from `pane layout` (one call per tab); empty when the TUI lacks it. */
91
+ async function paneRects() {
92
+ const live = await panes();
93
+ if (live.every((p) => rectCache.has(p.id))) return rectCache; // same panes → same rects
94
+ if (Date.now() < rectCacheAt) return rectCache; // a pane mid-create: keep the last snapshot a moment
95
+ const tabs = [...new Set(live.map((p) => p.tab).filter(Boolean))].slice(0, 40);
96
+ const next = new Map();
97
+ for (const tab of tabs) {
98
+ const probe = live.find((p) => p.tab === tab)?.id;
99
+ if (!probe) continue;
100
+ try {
101
+ const parsed = JSON.parse(await run(["pane", "layout", "--pane", probe]));
102
+ for (const pane of parsed?.result?.layout?.panes ?? []) {
103
+ if (typeof pane?.pane_id === "string" && pane?.rect && ["x", "y", "width", "height"].every((k) => Number.isFinite(pane.rect[k]))) {
104
+ next.set(pane.pane_id, { x: pane.rect.x, y: pane.rect.y, width: pane.rect.width, height: pane.rect.height });
105
+ }
106
+ }
107
+ } catch { /* an older TUI: fall back to a flat row */ }
108
+ }
109
+ rectCache = next;
110
+ rectCacheAt = Date.now() + 1_000;
111
+ return rectCache;
112
+ }
113
+
114
+ /** Split `items` by a clean cut on one axis; the most balanced cut wins. */
115
+ function bisect(items, axis, span) {
116
+ const edges = new Set();
117
+ for (const it of items) { edges.add(it.rect[axis]); edges.add(it.rect[axis] + it.rect[span]); }
118
+ let best = null;
119
+ for (const cut of edges) {
120
+ const left = items.filter((it) => it.rect[axis] + it.rect[span] <= cut);
121
+ const right = items.filter((it) => it.rect[axis] >= cut);
122
+ if (!left.length || !right.length || left.length + right.length !== items.length) continue;
123
+ const lo = Math.min(...items.map((it) => it.rect[axis]));
124
+ const hi = Math.max(...items.map((it) => it.rect[axis] + it.rect[span]));
125
+ const score = Math.abs((cut - lo) - (hi - cut));
126
+ if (!best || score < best.score) best = { cut, left, right, score, lo, hi };
127
+ }
128
+ return best;
129
+ }
130
+
131
+ /** The doc's layout tree for one tab's panes, from their on-screen rectangles. */
132
+ function layoutTree(items, nodeId) {
133
+ if (items.length <= 1) return { id: nodeId, type: "row", children: items.map(blockOf) };
134
+ const x = bisect(items, "x", "width"); // a vertical cut → children side by side
135
+ const y = bisect(items, "y", "height"); // a horizontal cut → children stacked
136
+ const pick = (c) => (c ? c.score / Math.max(1, c.hi - c.lo) : Infinity);
137
+ let cut, axis, span, type;
138
+ if (x && pick(x) <= pick(y)) { cut = x; axis = "x"; span = "width"; type = "row"; }
139
+ else if (y) { cut = y; axis = "y"; span = "height"; type = "column"; }
140
+ else return { id: nodeId, type: "row", children: items.map(blockOf) }; // no clean cut: flat
141
+ const total = cut.hi - cut.lo || 1;
142
+ const extent = (list) => Math.max(...list.map((it) => it.rect[axis] + it.rect[span])) - Math.min(...list.map((it) => it.rect[axis]));
143
+ const share = (list) => ({ weight: Math.max(0.01, Math.round((extent(list) / total) * 1000) / 1000) });
144
+ const child = (list, suffix) => list.length === 1 ? { ...blockOf(list[0]), size: share(list) } : { ...layoutTree(list, nodeId + suffix), size: share(list) };
145
+ return { id: nodeId, type, children: [child(cut.left, "l"), child(cut.right, "r")] };
146
+ }
147
+
148
+ const blockOf = (it) => ({ id: "p" + digest("pane:" + it.pane.id).slice(0, 30), type: "block", content: { terminal: it.pane.terminal.address } });
149
+
150
+ /** Terminal records as the viewers list them: panes with their on-screen geometry.
151
+ * Agent panes also carry their program (π) in name/argv — the app's programs table
152
+ * matches argv, so its agents mod and icons light up for them. */
153
+ async function terminalRecords() {
154
+ const rects = await paneRects();
155
+ const out = [];
156
+ for (const { id, terminal } of await panes()) {
157
+ const rect = rects.get(id);
158
+ let record = rect ? { ...terminal, cols: Math.max(2, Math.min(1000, rect.width)), rows: Math.max(2, Math.min(1000, rect.height)) } : { ...terminal };
159
+ const info = await agentInfo(id);
160
+ if (info.agent) record = { ...record, name: info.agent, argv: [info.agent] };
161
+ out.push(record);
162
+ }
163
+ return out;
164
+ }
165
+
166
+ /** Seating changes (workspace/tab/pane set) are what change the layout doc. */
167
+ function docFingerprint(records) {
168
+ return JSON.stringify(records.map((t) => [t.address, t.labels["herdr.space"] ?? null, t.labels["herdr.tab"] ?? null]));
169
+ }
170
+
171
+ /** What a viewer must hear about between polls: titles, folders, seating, life. */
172
+ function seenFingerprint(records) {
173
+ return new Map(records.map((t) => [t.address, [t.title, t.cwd, t.labels["herdr.space"] ?? null, t.labels["herdr.tab"] ?? null, t.status?.state ?? null]]));
174
+ }
175
+
50
176
  function clip(x, n) { return typeof x === "string" ? x.slice(0, n) : ""; }
177
+
178
+ let wsLabels = new Map();
179
+ let wsLabelsUntil = 0;
180
+ /** workspace_id → label; empty when the TUI lacks `workspace list` (spaces then go unnamed). */
181
+ async function workspaceLabels() {
182
+ if (Date.now() < wsLabelsUntil) return wsLabels;
183
+ try {
184
+ const parsed = JSON.parse(await run(["workspace", "list"]));
185
+ wsLabels = new Map((Array.isArray(parsed?.result?.workspaces) ? parsed.result.workspaces : [])
186
+ .filter((w) => typeof w?.workspace_id === "string" && typeof w?.label === "string")
187
+ .map((w) => [w.workspace_id, clip(w.label, 120)]));
188
+ } catch { wsLabels = new Map(); }
189
+ wsLabelsUntil = Date.now() + 5_000;
190
+ return wsLabels;
191
+ }
192
+
193
+ /**
194
+ * The `herdr-app` layout document the desktop app renders: each TUI workspace becomes a
195
+ * space (named by its label, placed by its first pane's cwd), each tab a tab, each pane a
196
+ * terminal block. Read-only: structural edits stay in the TUI (doc.set is not offered).
197
+ */
198
+ // Seating maps for doc writes: the doc's digest ids back to Herdr's own ids.
199
+ const seatWorkspace = new Map(); // spaceId → workspace_id
200
+ const seatTab = new Map(); // tabId → { ws, tab }
201
+ const seatPane = new Map(); // terminal address → pane_id
202
+
203
+ let tabLabels = new Map();
204
+ let tabLabelsUntil = 0;
205
+ /** tab_id → label; empty when the TUI lacks `tab list`. */
206
+ async function tabLabelMap() {
207
+ if (Date.now() < tabLabelsUntil) return tabLabels;
208
+ try {
209
+ const parsed = JSON.parse(await run(["tab", "list"]));
210
+ tabLabels = new Map((Array.isArray(parsed?.result?.tabs) ? parsed.result.tabs : [])
211
+ .filter((t) => typeof t?.tab_id === "string" && typeof t?.label === "string")
212
+ .map((t) => [t.tab_id, clip(t.label, 120)]));
213
+ } catch { tabLabels = new Map(); }
214
+ tabLabelsUntil = Date.now() + 5_000;
215
+ return tabLabels;
216
+ }
217
+
218
+ async function layoutDoc() {
219
+ const labels = await workspaceLabels();
220
+ const tabNames = await tabLabelMap();
221
+ const rects = await paneRects();
222
+ const byTab = new Map();
223
+ for (const p of await panes()) {
224
+ if (!p.workspace || !p.tab) continue; // a pane outside every workspace stays off the app's screens
225
+ if (!byTab.has(p.tab)) byTab.set(p.tab, { workspace: p.workspace, panes: [] });
226
+ byTab.get(p.tab).panes.push(p);
227
+ }
228
+ const spaces = new Map();
229
+ for (const [tab, { workspace, panes: tabPanes }] of byTab) {
230
+ const spaceId = "sp" + digest("space:" + workspace).slice(0, 30);
231
+ if (!spaces.has(workspace)) spaces.set(workspace, { id: spaceId, name: labels.get(workspace) || "", folder: tabPanes[0]?.terminal.cwd || "", tabs: new Map() });
232
+ const space = spaces.get(workspace);
233
+ seatWorkspace.set(spaceId, workspace);
234
+ if (!space.folder && tabPanes[0]?.terminal.cwd) space.folder = tabPanes[0].terminal.cwd;
235
+ const tabId = "tb" + digest("tab:" + tab).slice(0, 30);
236
+ seatTab.set(tabId, { ws: workspace, tab });
237
+ let root;
238
+ if (tabPanes.every((p) => rects.has(p.id))) {
239
+ // The TUI's real split structure, rebuilt from the panes' on-screen rectangles.
240
+ const items = tabPanes.map((p) => ({ pane: p, rect: rects.get(p.id) })).sort((a, b) => a.rect.y - b.rect.y || a.rect.x - b.rect.x);
241
+ root = layoutTree(items, tabId);
242
+ } else {
243
+ root = { id: tabId, type: "row", children: tabPanes.map((p) => blockOf({ pane: p })) };
244
+ }
245
+ for (const p of tabPanes) seatPane.set(p.terminal.address, p.id);
246
+ space.tabs.set(tab, { id: tabId, name: tabNames.get(tab) || "", root });
247
+ }
248
+ return { spaces: [...spaces.values()].map((s) => ({ id: s.id, name: s.name, folder: s.folder, tabs: [...s.tabs.values()] })) };
249
+ }
250
+
251
+ const versionOf = (value) => Number.parseInt(digest(JSON.stringify(value)).slice(0, 12), 16);
252
+
253
+ /** Wrap text to a viewer's width, breaking long tokens — a transcript that reads like the pane. */
254
+ function wrapFor(width, text) {
255
+ const cols = Math.max(20, Math.min(200, width - 2));
256
+ const out = [];
257
+ for (const para of text.split("\n")) {
258
+ if (!para.trim()) { out.push(""); continue; }
259
+ let line = "";
260
+ for (let word of para.trim().split(/\s+/)) {
261
+ while (word.length > cols) { // paths and URLs: split rather than overflow
262
+ if (line) { out.push(line); line = ""; }
263
+ out.push(word.slice(0, cols));
264
+ word = word.slice(cols);
265
+ }
266
+ if (!word) continue;
267
+ if (line && line.length + 1 + word.length > cols) { out.push(line); line = word; }
268
+ else line = line ? line + " " + word : word;
269
+ }
270
+ if (line) out.push(line);
271
+ }
272
+ return out.join("\r\n");
273
+ }
274
+
275
+ const sessionCache = new Map(); // pane_id → { session, agent, until } — pane get is a per-read cost otherwise
276
+ async function agentInfo(paneId) {
277
+ const cached = sessionCache.get(paneId);
278
+ if (cached && Date.now() < cached.until) return cached;
279
+ let session = null;
280
+ let agent = null;
281
+ try {
282
+ const parsed = JSON.parse(await run(["pane", "get", paneId]));
283
+ const pane = parsed?.result?.pane;
284
+ const value = pane?.agent_session?.value;
285
+ if (typeof value === "string" && value.endsWith(".jsonl") && value.startsWith(homedir() + "/")) session = value;
286
+ if (typeof pane?.agent === "string" && pane.agent) agent = clip(pane.agent, 32);
287
+ } catch { /* a pane without an agent session simply has no transcript */ }
288
+ const info = { session, agent, until: Date.now() + 30_000 };
289
+ sessionCache.set(paneId, info);
290
+ return info;
291
+ }
292
+
293
+ async function agentSession(hit) {
294
+ return (await agentInfo(hit.id)).session;
295
+ }
296
+
297
+ /** The pane's recent chat as structured blocks — the history that lives inside the agent
298
+ * (π) and never was in the terminal stream. */
299
+ async function transcriptBlocks(hit) {
300
+ const session = await agentSession(hit);
301
+ if (!session) return null;
302
+ try {
303
+ const fh = await openFile(session, "r");
304
+ let chunk;
305
+ try {
306
+ const { size } = await fh.stat();
307
+ const len = Math.min(size, 256 * 1024);
308
+ chunk = Buffer.alloc(len);
309
+ await fh.read(chunk, 0, len, size - len);
310
+ } finally {
311
+ await fh.close();
312
+ }
313
+ const lines = chunk.toString("utf8").split("\n").slice(1); // the head line is usually cut mid-record
314
+ const blocks = [];
315
+ for (const raw of lines.slice(-300)) {
316
+ let entry;
317
+ try { entry = JSON.parse(raw); } catch { continue; }
318
+ if (entry?.type !== "message") continue;
319
+ const message = entry.message ?? {};
320
+ const role = message.role;
321
+ if (role !== "user" && role !== "assistant") continue; // tool chatter stays out of the transcript
322
+ const content = message.content;
323
+ const text = (typeof content === "string" ? content : Array.isArray(content) ? content.filter((x) => x?.type === "text").map((x) => x?.text ?? "").join(" ") : "").trim();
324
+ if (!text) continue;
325
+ blocks.push({ role, text: text.slice(0, 4000) });
326
+ }
327
+ // Newest whole messages first; the oldest drops off whole, never cut mid-thought.
328
+ const kept = blocks.slice(-40);
329
+ let size = kept.reduce((n, b) => n + b.text.length, 0);
330
+ while (kept.length > 1 && size > 40_000) size -= kept.shift().text.length;
331
+ return kept.length ? kept : null;
332
+ } catch {
333
+ return null; // best-effort
334
+ }
335
+ }
336
+
337
+ /** Transcript blocks as the plain lines a text reader (the phone's history view) shows.
338
+ * With `joinScreen`, the current screen follows: the in-flight turn is not in the
339
+ * session file yet (π writes it when the turn ends), so the visible screen is the
340
+ * only bridge — history then flows straight into what the viewer renders below. */
341
+ async function transcriptText(hit, { joinScreen = false } = {}) {
342
+ const blocks = await transcriptBlocks(hit);
343
+ const parts = [];
344
+ if (blocks) parts.push(blocks.map((b) => (b.role === "user" ? "❯ " : "● ") + b.text).join("\n"));
345
+ if (joinScreen) {
346
+ try {
347
+ // A text view wants words, not terminal paint: drop OSC replies and every CSI
348
+ // (colors included) — the seed path keeps its paint, this one reads clean.
349
+ const screen = (await run(["pane", "read", hit.id, "--source", "visible", "--format", "text", "--raw"]))
350
+ .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)?/g, "").replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, "").replace(/\s+$/, "");
351
+ if (screen) {
352
+ if (parts.length) parts.push("──── trở lại hiện tại ────");
353
+ parts.push(screen);
354
+ }
355
+ } catch { /* best-effort seam */ }
356
+ }
357
+ return parts.length ? parts.join("\n") : null;
358
+ }
359
+
360
+ // Input from the phone rides a bounded, coalescing FIFO with in-order acks: adjacent
361
+ // keystroke batches for one pane leave as a single send-keys, every input is acked in
362
+ // submission order, and any ambiguous delivery flips the queue to needsResync — the
363
+ // viewer must re-read the pane, and queued input is never replayed at it.
364
+ let inputQueue = null;
365
+ let inputStamp = 0; // advanced once a write has landed: snapshots older than it are stale
366
+ async function applyInput(event) {
367
+ if (event.kind === "text") await run(["pane", "run", event.paneId, event.text]);
368
+ else await run(["pane", "send-keys", event.paneId, ...event.keys]);
369
+ inputStamp++;
370
+ }
371
+ async function queuedInput(paneId, kind, payload) {
372
+ if (!inputQueue) { // a queue-less path (never in this adapter today) still writes in order
373
+ await applyInput({ paneId, kind, ...payload });
374
+ return null;
375
+ }
376
+ try {
377
+ return await inputQueue.enqueue(paneId, kind, payload);
378
+ } catch (err) {
379
+ if (err?.kind === "needs_resync") throw new RpcError(-32000, "Pane input needs a resync; re-read the pane, never replay", "needs_resync");
380
+ throw err;
381
+ }
382
+ }
383
+ // In-flight snapshot sharing: concurrent readers of one pane share a single read, and a
384
+ // read that began before a write is never served to a caller after it (the `fresh` rule).
385
+ const stitchedInFlight = new Map(); // pane_id → { after, promise }
386
+ async function stitchedRead(hit) {
387
+ const current = stitchedInFlight.get(hit.id);
388
+ if (current && current.after === inputStamp) return current.promise;
389
+ const promise = transcriptText(hit, { joinScreen: true });
390
+ stitchedInFlight.set(hit.id, { after: inputStamp, promise });
391
+ try { return await promise; } finally { if (stitchedInFlight.get(hit.id)?.promise === promise) stitchedInFlight.delete(hit.id); }
392
+ }
393
+
394
+ /** The terminal addresses a doc tree shows. */
395
+ function collectTerminals(node, out = []) {
396
+ if (!node || typeof node !== "object") return out;
397
+ if (node.type === "block" && node.content?.terminal) out.push(node.content.terminal);
398
+ for (const child of Array.isArray(node.children) ? node.children : []) collectTerminals(child, out);
399
+ return out;
400
+ }
401
+
402
+ const firstLeaf = (node) => {
403
+ let cur = node;
404
+ for (let depth = 0; cur && depth < 32; depth++) {
405
+ if (cur.type === "block") return cur.content?.terminal ?? null;
406
+ cur = Array.isArray(cur.children) && cur.children.length ? cur.children[0] : null;
407
+ }
408
+ return null;
409
+ };
410
+
411
+ /** Divider drags: weight changes between siblings become pane resize steps. */
412
+ function treeDiffResize(cur, nxt, ops) {
413
+ if (!cur || !nxt || cur.type !== nxt.type) return;
414
+ if ((cur.type !== "row" && cur.type !== "column") || !Array.isArray(cur.children) || cur.children.length !== nxt.children?.length) return;
415
+ const axis = cur.type === "row" ? ["right", "left"] : ["down", "up"];
416
+ for (let i = 0; i < cur.children.length; i++) {
417
+ const c = cur.children[i], x = nxt.children[i];
418
+ const cw = c?.size?.weight, xw = x?.size?.weight;
419
+ if (Number.isFinite(cw) && Number.isFinite(xw) && Math.abs(xw - cw) > 0.01 && xw > cw) {
420
+ // This child grows; the sibling it takes from says which edge moves.
421
+ const j = nxt.children.findIndex((s, k) => k !== i && Number.isFinite(cur.children[k]?.size?.weight) && (s?.size?.weight ?? 1) < (cur.children[k]?.size?.weight ?? 1));
422
+ const leaf = firstLeaf(c) ?? firstLeaf(cur.children[i]);
423
+ if (j >= 0 && leaf && seatPane.has(leaf)) ops.push(["pane", "resize", "--pane", seatPane.get(leaf), "--direction", axis[j > i ? 0 : 1], "--amount", String(Math.min(0.5, Math.round((xw - cw) * 1000) / 1000))]);
424
+ }
425
+ treeDiffResize(c, x, ops);
426
+ }
427
+ }
428
+
429
+ const labelArg = (name) => typeof name === "string" && name.trim() && !name.trim().startsWith("-") ? name.trim().slice(0, 120) : null;
430
+ const renameArg = (name) => typeof name === "string" && !name.trim().startsWith("-") ? name.trim().slice(0, 120) : null; // a rename may clear the label
431
+
432
+ /** A doc.set is a diff against the live layout: adds, removals, renames and divider drags. */
433
+ async function applyDocEdit(cur, nxt) {
434
+ if (!nxt || !Array.isArray(nxt.spaces)) throw invalid();
435
+ const ops = [];
436
+ const nextSpaceIds = new Set();
437
+ for (const space of nxt.spaces.slice(0, 40)) {
438
+ if (!space || typeof space.id !== "string" || !Array.isArray(space.tabs)) continue;
439
+ nextSpaceIds.add(space.id);
440
+ const before = cur.spaces.find((s) => s.id === space.id);
441
+ const name = labelArg(space.name);
442
+ if (!before) {
443
+ if (name) ops.push(["workspace", "create", "--label", name]);
444
+ continue; // its tabs arrive with the panes Herdr seats there
445
+ }
446
+ const wsId = seatWorkspace.get(space.id);
447
+ const newName = renameArg(space.name);
448
+ if (newName !== null && newName !== before.name && wsId) ops.push(["workspace", "rename", wsId, newName]);
449
+ const nextTabIds = new Set();
450
+ for (const tab of space.tabs.slice(0, 40)) {
451
+ if (!tab || typeof tab.id !== "string" || !tab.root) continue;
452
+ nextTabIds.add(tab.id);
453
+ const seat = seatTab.get(tab.id);
454
+ const tabName = renameArg(tab.name);
455
+ const curTab = before.tabs.find((t) => t.id === tab.id);
456
+ if (!curTab && seat) ops.push(["tab", "create", "--workspace", seat.ws, ...(labelArg(tab.name) ? ["--label", labelArg(tab.name)] : [])]);
457
+ else if (curTab && tabName !== null && tabName !== curTab.name && seat) ops.push(["tab", "rename", seat.tab, tabName]);
458
+ if (curTab) {
459
+ const keep = new Set(collectTerminals(tab.root));
460
+ for (const addr of collectTerminals(curTab.root)) if (!keep.has(addr) && seatPane.has(addr)) ops.push(["pane", "close", seatPane.get(addr)]);
461
+ }
462
+ }
463
+ for (const tabId of before.tabs.map((t) => t.id)) {
464
+ const seat = seatTab.get(tabId);
465
+ if (!nextTabIds.has(tabId) && seat) ops.push(["tab", "close", seat.tab]);
466
+ }
467
+ }
468
+ for (const space of cur.spaces) {
469
+ const wsId = seatWorkspace.get(space.id);
470
+ if (!nextSpaceIds.has(space.id) && wsId) ops.push(["workspace", "close", wsId]);
471
+ }
472
+ for (const space of nxt.spaces) {
473
+ const before = cur.spaces.find((s) => s.id === space.id);
474
+ if (!before) continue;
475
+ for (const tab of space.tabs ?? []) {
476
+ const curTab = before.tabs.find((t) => t.id === tab.id);
477
+ if (curTab?.root && tab.root) treeDiffResize(curTab.root, tab.root, ops);
478
+ }
479
+ }
480
+ for (const op of ops.slice(0, 40)) {
481
+ try { await run(op); } catch { /* a step that races the TUI must not block the rest */ }
482
+ }
483
+ }
484
+
51
485
  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
486
  class RpcError extends Error {
53
487
  constructor(code, message, kind) { super(message); this.code = code; this.kind = kind; }
@@ -61,19 +495,25 @@ async function findPane(terminal) {
61
495
  return hit;
62
496
  }
63
497
 
64
- async function call(method, p, framed, attach) {
498
+ async function call(method, p, framed, attach, startEvents) {
65
499
  switch (method) {
66
500
  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 };
501
+ return { core, version, generation: 1, framed, features: framed ? ["framed", "attach", "status", "checksum_reads", ...(interactive ? ["resize_notifications", "input_ack"] : [])] : ["status", "checksum_reads"], methods: [...methods, ...(framed ? ["terminal.attach"] : []), ...(interactive ? inputMethods : [])], keeps_running_after_logout: true };
68
502
  case "server.status": return status();
69
- case "terminal.list":
70
- case "events.subscribe": {
503
+ case "terminal.list": {
71
504
  const filters = p.labels ?? {};
72
505
  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))) &&
506
+ const terminals = (await terminalRecords()).filter((t) =>
75
507
  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 };
508
+ return { terminals, hidden_finished: 0, machines: [] };
509
+ }
510
+ case "events.subscribe": {
511
+ // A real event stream: the app re-reads the layout doc and terminal list from these,
512
+ // without them it never notices a pane opened or closed on the TUI.
513
+ if (!framed) throw new RpcError(-32000, "Framed connection required", "needs_framed");
514
+ const records = await terminalRecords();
515
+ const channel = startEvents(records);
516
+ return { terminals: records, seq: 0, channel };
77
517
  }
78
518
  case "terminal.send":
79
519
  case "terminal.keys":
@@ -83,33 +523,144 @@ async function call(method, p, framed, attach) {
83
523
  const { turn } = terminal;
84
524
  if (method === "terminal.send") {
85
525
  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 };
526
+ const ack = await queuedInput(id, "text", { text: p.text });
527
+ return { turn, status: null, started: null, wait: null, ...(ack === null ? {} : { ack }) };
528
+ }
529
+ if (method === "terminal.interrupt") {
530
+ // An interrupt must never sit behind typing already in the queue.
531
+ await run(["pane", "send-keys", id, "ctrl+c"]);
532
+ return { key: "ctrl+c", outcome: "unknown" };
89
533
  }
90
- const keys = method === "terminal.interrupt" ? ["ctrl+c"] : p.keys;
534
+ const keys = p.keys;
91
535
  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 };
536
+ const ack = await queuedInput(id, "keys", { keys });
537
+ return { turn, status: null, ...(ack === null ? {} : { ack }) };
538
+ }
539
+ case "terminal.run": {
540
+ if (!interactive) throw new RpcError(-32601, "This pairing is read-only", "forbidden");
541
+ if (!Array.isArray(p.argv) || !p.argv.length || p.argv.length > 16 || p.argv.some((a) => typeof a !== "string" || !a || a.length > 256 || a.includes("\0") || a.startsWith("-"))) throw invalid();
542
+ // The TUI owns placement: the new pane splits the seat the request labels (or the first pane), in the asked direction.
543
+ const before = await panes();
544
+ const space = p.labels && typeof p.labels["herdr.space"] === "string" ? p.labels["herdr.space"] : null;
545
+ const target = before.find((x) => x.terminal.labels["herdr.space"] === space && space) ?? before[0];
546
+ if (!target) throw new RpcError(-32000, "No pane to split", "unavailable");
547
+ const cwd = typeof p.cwd === "string" && p.cwd && !p.cwd.includes("\0") && p.cwd.length <= 512 && !p.cwd.startsWith("-") ? ["--cwd", p.cwd] : [];
548
+ await run(["pane", "split", "--pane", target.id, "--direction", p.place === "down" ? "down" : "right", ...cwd]);
549
+ // Wait briefly for the new pane to appear beside the one we split, then report it seated.
550
+ let record;
551
+ for (let i = 0; i < 10 && !record; i++) {
552
+ await new Promise((resolve) => setTimeout(resolve, 200));
553
+ cacheUntil = 0; // the pane list is cached a second; force a fresh look
554
+ const fresh = await panes();
555
+ const created = fresh.find((x) => x.tab === target.tab && !before.some((o) => o.id === x.id));
556
+ if (created) {
557
+ record = (await terminalRecords()).find((t) => t.address === created.terminal.address) ?? null;
558
+ try { await run(["pane", "run", created.id, p.argv.join(" ")]); } catch { /* the pane stands; the command is best-effort */ }
559
+ }
560
+ }
561
+ if (!record) throw new RpcError(-32000, "The new pane did not appear", "unavailable");
562
+ return { terminal: record, started: null, wait: null };
563
+ }
564
+ case "terminal.kill": {
565
+ if (!interactive) throw new RpcError(-32601, "This pairing is read-only", "forbidden");
566
+ const hit = await findPane(p.terminal);
567
+ await run(["pane", "close", hit.id]);
568
+ return {};
94
569
  }
95
570
  case "terminal.get":
96
571
  case "terminal.attach":
97
572
  case "terminal.read": {
98
573
  const hit = await findPane(p.terminal);
99
- if (method === "terminal.get") return hit.terminal;
574
+ const rect = (await paneRects()).get(hit.id);
575
+ const dims = { cols: Math.max(2, Math.min(1000, rect?.width ?? 80)), rows: Math.max(2, Math.min(1000, rect?.height ?? 24)) };
576
+ if (method === "terminal.get") return { ...hit.terminal, ...dims };
100
577
  if (method === "terminal.attach") {
101
578
  if (!framed) throw new RpcError(-32000, "Framed connection required", "needs_framed");
102
579
  if ([p.cols, p.rows].some((n) => n !== undefined && n !== 0 && !validDimension(n))) throw invalid();
103
- return attach(hit, p);
580
+ return attach(hit, p, rect);
104
581
  }
105
582
  const lines = p.lines ?? 0;
106
583
  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" };
584
+ // A checksum-stamped read: the viewer that already holds this text sends its stamp
585
+ // back and gets `unchanged` with no body when nothing moved (readChangedCommand
586
+ // semantics — POSIX cksum, no stat). Viewers without a stamp get the full body.
587
+ const prior = typeof p.checksum === "string" && /^[0-9]{1,10} [0-9]{1,20}$/.test(p.checksum) ? p.checksum : null;
588
+ // An agent pane keeps its chat inside itself: serve the transcript as "stitched"
589
+ // history (the core's term for a full-screen app read by scrolling it), joined to
590
+ // the live screen so the seam never shows a gap mid-turn.
591
+ const transcript = await stitchedRead(hit);
592
+ if (transcript) {
593
+ const all = transcript.split("\n");
594
+ const take = lines > 0 ? all.slice(-Math.min(2000, lines)) : all.slice(-24);
595
+ const text = take.join("\n").slice(0, 60 * 1024);
596
+ const stamp = cksum(Buffer.from(text, "utf8"));
597
+ if (prior !== null && prior === stamp) return { unchanged: true, checksum: stamp, complete: transcript.length <= 60 * 1024, how: "stitched", why: null };
598
+ return { text, checksum: stamp, complete: transcript.length <= 60 * 1024, how: "stitched", why: null };
599
+ }
600
+ // A shell pane: `recent` carries the history viewers scroll (the phone reads it);
601
+ // a pane with none — fresh — falls back to the on-screen text so it is not blank.
602
+ let text = await run(["pane", "read", hit.id, "--source", "recent", "--lines", String(Math.max(24, Math.min(120, lines + 24))), "--format", "text", "--raw"]);
603
+ let how = "history";
604
+ if (!text.trim()) {
605
+ text = await run(["pane", "read", hit.id, "--source", "visible", "--lines", String(dims.rows), "--format", "text", "--raw"]);
606
+ how = "screen";
607
+ }
608
+ return { text: text.slice(0, 32 * 1024), complete: text.length <= 32 * 1024, how };
109
609
  }
110
610
  case "templates.list": return { templates: [] };
111
611
  case "machine.list": return { machines: [] };
112
- case "doc.get": return { value: null, version: 0 };
612
+ case "terminal.label": {
613
+ if (!interactive) throw new RpcError(-32601, "This pairing is read-only", "forbidden");
614
+ const hit = await findPane(p.terminal);
615
+ const labels = p.labels ?? {};
616
+ if (!labels || typeof labels !== "object" || Array.isArray(labels)) throw invalid();
617
+ const clean = {};
618
+ for (const [k, v] of Object.entries(labels).slice(0, 16)) {
619
+ if (!/^[a-z0-9][a-z0-9._-]{0,63}$/i.test(k) || typeof v !== "string" || v.length > 200) throw invalid();
620
+ // Seating labels are the adapter's; everything else is the app's to keep.
621
+ if (k !== "herdr.space" && k !== "herdr.tab" && k !== "where") clean[k] = v;
622
+ }
623
+ if (Object.keys(clean).length) appLabels.set(hit.id, clean); else appLabels.delete(hit.id);
624
+ saveAppLabels();
625
+ cacheUntil = 0; // the next listing shows the new labels
626
+ return {};
627
+ }
628
+ case "terminal.keep": {
629
+ if (!interactive) throw new RpcError(-32601, "This pairing is read-only", "forbidden");
630
+ await findPane(p.terminal); // Herdr panes already outlive any one viewer
631
+ return {};
632
+ }
633
+ case "doc.set": {
634
+ // Layout edits arrive as a whole document; the TUI applies the difference.
635
+ if (!interactive) throw new RpcError(-32601, "This pairing is read-only", "forbidden");
636
+ if (typeof p.name !== "string" || p.name !== "herdr-app" || p.on) throw invalid();
637
+ if (!p.value || typeof p.value !== "object" || !Array.isArray(p.value.spaces)) throw invalid();
638
+ if (!Number.isSafeInteger(p.version) || p.version < 0) throw invalid();
639
+ const current = await layoutDoc();
640
+ if (p.version !== versionOf(current)) throw new RpcError(-32000, "The TUI layout moved on; read it again", "conflict");
641
+ await applyDocEdit(current, p.value);
642
+ // The edits land on the TUI asynchronously; wait briefly until the doc reflects them.
643
+ const before = versionOf(current);
644
+ let next = current;
645
+ for (let tries = 0; tries < 6; tries++) {
646
+ await new Promise((resolve) => setTimeout(resolve, 200));
647
+ cacheUntil = 0;
648
+ rectCacheAt = 0;
649
+ wsLabelsUntil = 0;
650
+ tabLabelsUntil = 0;
651
+ rectCache = new Map();
652
+ next = await layoutDoc();
653
+ if (versionOf(next) !== before) break;
654
+ }
655
+ return { version: versionOf(next) };
656
+ }
657
+ case "doc.get": {
658
+ if (typeof p.name !== "string" || !p.name || p.name.length > 128) throw invalid();
659
+ if (p.name !== "herdr-app") return { value: null, version: 0 };
660
+ const value = await layoutDoc();
661
+ // Content-derived, so the version is stable while the layout is unchanged.
662
+ return { value, version: versionOf(value) };
663
+ }
113
664
  default: throw new RpcError(-32601, "Method not available on this TUI adapter", "forbidden");
114
665
  }
115
666
  }
@@ -127,6 +678,7 @@ async function serve() {
127
678
  let framed = false;
128
679
  let buffer = Buffer.alloc(0);
129
680
  const streams = new Map();
681
+ inputQueue = interactive ? new PaneLiveInputQueue(applyInput) : null;
130
682
  let nextChannel = 1;
131
683
  let timer;
132
684
  let polling = false;
@@ -146,15 +698,57 @@ async function serve() {
146
698
  const body = Buffer.from(JSON.stringify(reply));
147
699
  return framed ? frame(0, frameKind.data, body) : output(Buffer.concat([body, Buffer.from("\n")]));
148
700
  }
149
- async function attach(hit, p) {
701
+ async function attach(hit, p, rect) {
150
702
  if (streams.size >= maxStreams || nextChannel > 0xffff_ffff) throw new RpcError(-32000, "Too many open terminal views", "unavailable");
151
703
  const writable = interactive && p.observe !== true;
152
704
  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;
705
+ // The viewer owns the size (herdr-core): attach at what it asked to render at, so the
706
+ // first frame is already its size and no repaint stacks an old screen into its scrollback.
707
+ const real = { cols: Math.min(500, Math.max(2, p.cols ?? rect?.width ?? hit.terminal.cols)), rows: Math.min(300, Math.max(2, p.rows ?? rect?.height ?? hit.terminal.rows)) };
708
+ let native = writable ? await openTerminal(herdr, hit.target, real.cols, real.rows) : null;
709
+ if (native) {
710
+ // History above the live screen: the agent's own transcript (every viewer), and the
711
+ // terminal scrollback when the viewer asked for it (the desktop app does; the phone
712
+ // does not, and its mirror stays as it was). Herdr streams only the live screen.
713
+ const parts = [];
714
+ const blocks = await transcriptBlocks(hit);
715
+ if (blocks) {
716
+ // Theme-neutral styling: bold/dim attributes only, no palette — π's own `system`
717
+ // theme takes colors from the terminal at runtime, and so does this seed.
718
+ const dim = "\x1b[2m", bold = "\x1b[1m", reset = "\x1b[0m";
719
+ const out = [dim + "──── lịch sử chat (mới nhất ở dưới) ────" + reset];
720
+ for (const b of blocks) {
721
+ const mark = b.role === "user" ? bold + "❯ " + reset : "● ";
722
+ const wrapped = wrapFor(real.cols, b.text).split("\r\n");
723
+ out.push(wrapped[0] ? mark + wrapped[0] : mark);
724
+ for (const line of wrapped.slice(1)) out.push(" " + line);
725
+ out.push("");
726
+ }
727
+ out.push(dim + "──── trở lại hiện tại ────" + reset);
728
+ // The seam: the in-flight turn lives only on the screen, so end the seed with
729
+ // the screen itself — the viewer's first paint then continues it, not jumps.
730
+ try {
731
+ const screen = (await run(["pane", "read", hit.id, "--source", "visible", "--format", "text", "--raw"])).replace(/\s+$/, "");
732
+ if (screen) out.push(screen);
733
+ } catch { /* best-effort seam */ }
734
+ parts.push(Buffer.from(out.join("\r\n") + "\r\n"));
735
+ }
736
+ if (!blocks && Number.isSafeInteger(p.history) && p.history > 0) {
737
+ try {
738
+ const back = await run(["pane", "read", hit.id, "--source", "recent", "--lines", String(Math.min(2000, p.history)), "--format", "ansi", "--raw"]);
739
+ const lines = back.split(/\r?\n/);
740
+ const history = lines.slice(0, Math.max(0, lines.length - real.rows)).join("\r\n")
741
+ // Colors stay; terminal replies, links and other noise would only confuse mirrors.
742
+ .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)?/g, "").replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, (m) => (m.endsWith("m") ? m : ""));
743
+ if (history.trim()) parts.push(Buffer.from(history + "\r\n"));
744
+ } catch { /* seeding is best-effort */ }
745
+ }
746
+ if (parts.length) native = { ...native, first: { ...native.first, bytes: Buffer.concat([...parts, native.first.bytes]) } };
747
+ }
154
748
  const channel = nextChannel++;
155
749
  const resize = Boolean(native && p.resize_notifications === true);
156
750
  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 });
751
+ streams.set(channel, { id: hit.id, rows: Math.min(120, real.rows), realCols: real.cols, realRows: real.rows, credit: windowBytes, last: null, ready: false, native, resize });
158
752
  return { channel, terminal, resize_notifications: resize, automatic_input: false };
159
753
  }
160
754
  function release(channel) {
@@ -197,7 +791,7 @@ async function serve() {
197
791
  finally { await closeStream(channel); }
198
792
  }
199
793
  function schedule(delay) {
200
- if (closed || polling || timer || ![...streams.values()].some((s) => !s.native)) return;
794
+ if (closed || polling || timer || ![...streams.values()].some((s) => !s.native && !s.events)) return;
201
795
  timer = setTimeout(() => {
202
796
  timer = undefined;
203
797
  void poll().catch(() => process.stdin.destroy());
@@ -209,7 +803,7 @@ async function serve() {
209
803
  try {
210
804
  for (const [channel, stream] of [...streams]) {
211
805
  // 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;
806
+ if (closed || streams.get(channel) !== stream || stream.native || stream.events || !stream.ready || stream.credit < windowBytes / 2) continue;
213
807
  let snapshot;
214
808
  try { snapshot = await paint(stream.id, stream.rows); }
215
809
  catch {
@@ -227,6 +821,63 @@ async function serve() {
227
821
  }
228
822
  }
229
823
 
824
+ const startEvents = (records) => {
825
+ const channel = nextChannel++;
826
+ streams.set(channel, { events: true, seq: 0, credit: windowBytes, docFp: docFingerprint(records), seen: seenFingerprint(records), ready: true });
827
+ scheduleEvents(0);
828
+ return channel;
829
+ };
830
+ const eventMs = Math.max(250, Number.parseInt(process.env.HERDGATE_TUI_EVENT_MS ?? "1500", 10) || 1500);
831
+ let eventTimer;
832
+ let eventing = false;
833
+ function scheduleEvents(delay) {
834
+ if (closed || eventTimer || ![...streams.values()].some((s) => s.events)) return;
835
+ eventTimer = setTimeout(() => {
836
+ eventTimer = undefined;
837
+ void pumpEvents().catch(() => process.stdin.destroy());
838
+ }, delay);
839
+ eventTimer.unref();
840
+ }
841
+ /** The layout doc and terminal records change on the TUI; retell the subscribers. */
842
+ async function pumpEvents() {
843
+ if (eventing) return;
844
+ eventing = true;
845
+ try {
846
+ const watchers = [...streams].filter(([, s]) => s.events);
847
+ if (!watchers.length) return;
848
+ let records;
849
+ try { records = await terminalRecords(); } catch { return; }
850
+ const docFp = docFingerprint(records);
851
+ const now = seenFingerprint(records);
852
+ for (const [channel, s] of watchers) {
853
+ if (closed || streams.get(channel) !== s) continue;
854
+ const out = [];
855
+ if (s.docFp !== docFp) out.push({ method: "event", params: { seq: ++s.seq, type: "doc" } });
856
+ for (const addr of s.seen.keys()) if (!now.has(addr)) out.push({ method: "event", params: { seq: ++s.seq, type: "removed", terminal: addr, data: {} } });
857
+ for (const t of records) {
858
+ const prev = s.seen.get(t.address);
859
+ if (prev === undefined) out.push({ method: "event", params: { seq: ++s.seq, type: "created", terminal: t.address, data: t } });
860
+ else if (prev.join("\0") !== now.get(t.address).join("\0")) {
861
+ const [title0, cwd0, space0, tabb0, status0] = prev;
862
+ const [title1, cwd1, space1, tabb1, status1] = now.get(t.address);
863
+ if (status0 !== status1) out.push({ method: "event", params: { seq: ++s.seq, type: "status", terminal: t.address, data: { status: t.status, records: {}, reported: t.status !== null } } });
864
+ out.push({ method: "event", params: { seq: ++s.seq, type: "labels", terminal: t.address, data: { record: t } } });
865
+ }
866
+ }
867
+ s.docFp = docFp;
868
+ s.seen = now;
869
+ if (out.length && s.credit > 4096) {
870
+ const body = Buffer.from(out.map((e) => JSON.stringify(e)).join("\n") + "\n");
871
+ s.credit -= body.length;
872
+ await frame(channel, frameKind.data, body);
873
+ }
874
+ }
875
+ } finally {
876
+ eventing = false;
877
+ scheduleEvents(eventMs);
878
+ }
879
+ }
880
+
230
881
  try {
231
882
  for await (const chunk of process.stdin) {
232
883
  buffer = Buffer.concat([buffer, chunk]);
@@ -251,10 +902,12 @@ async function serve() {
251
902
  if (stream && kind === frameKind.close && size === 0) await closeStream(channel);
252
903
  if (stream?.native) {
253
904
  try {
254
- if (kind === frameKind.data && size > 0) {
255
- if (size > 32 * 1024) throw invalid();
905
+ if (kind === frameKind.data || kind === 6 /* automatic input: program replies, e.g. cell-size reports */) {
906
+ if (kind === frameKind.data && size > 32 * 1024) throw invalid();
256
907
  await stream.native.send({ type: "terminal.input", bytes: body.toString("base64") });
257
908
  }
909
+ // The viewer owns the size (herdr-core semantics): forwarded, and Herdr
910
+ // restores the pane's own size when this stream closes.
258
911
  if (kind === frameKind.resize && size === 4) {
259
912
  const cols = body.readUInt16LE(0), rows = body.readUInt16LE(2);
260
913
  if (cols > 0 && rows > 0) await stream.native.send({ type: "terminal.resize", cols: Math.min(500, cols), rows: Math.min(300, rows) });
@@ -282,7 +935,7 @@ async function serve() {
282
935
  let result;
283
936
  try {
284
937
  if (msg.params != null && (typeof msg.params !== "object" || Array.isArray(msg.params))) throw invalid();
285
- result = await call(msg.method, msg.params ?? {}, nextFramed, attach);
938
+ result = await call(msg.method, msg.params ?? {}, nextFramed, attach, startEvents);
286
939
  } catch (err) {
287
940
  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
941
  await write({ ...reply, error });
@@ -301,21 +954,28 @@ async function serve() {
301
954
  } finally {
302
955
  closed = true;
303
956
  clearTimeout(timer);
957
+ clearTimeout(eventTimer);
304
958
  for (const channel of streams.keys()) release(channel);
959
+ inputQueue?.resync("connection closed");
960
+ shells.close();
305
961
  }
306
962
  }
307
963
 
308
964
  const command = args.join(" ");
309
965
  try {
310
966
  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()));
967
+ else if (command === "server status" || command === "server status --json") {
968
+ const out = JSON.stringify(await status());
969
+ shells.close();
970
+ console.log(out);
971
+ }
312
972
  else if (command === "connect" || command === "connect --json") {
313
973
  await serve();
314
974
  } else {
315
975
  console.error("herdgate: TUI adapter supports only connect, --version, and server status");
316
976
  process.exitCode = 111;
317
977
  }
318
- } catch {
319
- console.error("herdgate: could not query the local Herdr TUI");
978
+ } catch (e) {
979
+ console.error(`herdgate: could not query the local Herdr TUI: ${e?.message ?? e}`);
320
980
  process.exitCode = 111;
321
981
  }