@bom0792/herdgate 0.9.35 → 0.9.37

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.
@@ -2,8 +2,10 @@
2
2
  // Subset of the Core API for TUI panes. Input requires explicit local opt-in.
3
3
  import { execFile } from "node:child_process";
4
4
  import { createHash } from "node:crypto";
5
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
6
+ import { open as openFile } from "node:fs/promises";
5
7
  import { hostname, homedir } from "node:os";
6
- import { join } from "node:path";
8
+ import { dirname, join } from "node:path";
7
9
  import { promisify, stripVTControlCharacters } from "node:util";
8
10
  import { openTerminal, validDimension } from "./mobile-tui-stream.mjs";
9
11
 
@@ -14,7 +16,28 @@ const digest = (text) => createHash("sha256").update(text).digest("hex");
14
16
  const core = { id: digest(`herdgate-tui:${hostname()}:${name}`).slice(0, 32), name };
15
17
  const version = "0.1.21"; // Core wire compatibility target, not a running Core binary.
16
18
  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"];
19
+ const inputMethods = ["terminal.send", "terminal.keys", "terminal.interrupt", "terminal.run", "terminal.kill", "terminal.label", "terminal.keep", "doc.set"];
20
+
21
+ // Labels the app sets on panes outlive the adapter in a sidecar; seating labels stay ours.
22
+ const labelsFile = join(homedir(), ".config", "herdgate", "tui-labels.json");
23
+ let appLabels = null;
24
+ function appLabelsFor(paneId) {
25
+ if (appLabels === null) {
26
+ try {
27
+ const stored = JSON.parse(readFileSync(labelsFile, "utf8"));
28
+ appLabels = new Map(Object.entries(stored).filter(([id, l]) => typeof id === "string" && l && typeof l === "object" && !Array.isArray(l)).slice(0, 500));
29
+ } catch { appLabels = new Map(); }
30
+ }
31
+ return appLabels.get(paneId) || {};
32
+ }
33
+ function saveAppLabels() {
34
+ try {
35
+ mkdirSync(dirname(labelsFile), { recursive: true });
36
+ const tmp = labelsFile + ".tmp";
37
+ writeFileSync(tmp, JSON.stringify(Object.fromEntries([...appLabels].slice(-500))));
38
+ renameSync(tmp, labelsFile);
39
+ } catch { /* labels are best-effort */ }
40
+ }
18
41
  const args = process.argv.slice(2);
19
42
  const interactive = args[0] === "--interactive";
20
43
  if (interactive) args.shift();
@@ -23,8 +46,8 @@ const inputText = (text) => typeof text === "string" && text.length > 0 && !text
23
46
  const frameKind = { data: 0, credit: 1, close: 2, resize: 3 };
24
47
  const cap = 128 * 1024;
25
48
  const windowBytes = 64 * 1024;
26
- const maxStreams = 2;
27
- const pollMs = 1_250;
49
+ const maxStreams = 16; // A desktop space shows several panes at once; the phone showed one or two.
50
+ const pollMs = Math.max(250, Number.parseInt(process.env.HERDGATE_TUI_POLL_MS ?? "1250", 10) || 1250);
28
51
  const startedAt = Date.now();
29
52
  let cache;
30
53
  let cacheUntil = 0;
@@ -36,18 +59,356 @@ async function panes() {
36
59
  if (!Array.isArray(parsed?.result?.panes)) throw new Error("Herdr pane list unavailable");
37
60
  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
61
  .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: {
62
+ let title = clip(p.terminal_title_stripped || p.terminal_title || p.pane_id, 120);
63
+ // Herdr's per-pane agent state feeds the core's own status and foreground fields.
64
+ const status = p.agent_status === "working" ? "working" : null;
65
+ const foreground = typeof p.foreground_cwd === "string" && p.foreground_cwd ? { pid: null, name: null, argv: null, cwd: clip(p.foreground_cwd, 512) } : null;
66
+ const ws = typeof p.workspace_id === "string" && /^[a-zA-Z0-9_:.-]{1,128}$/.test(p.workspace_id) ? p.workspace_id : null;
67
+ const tab = typeof p.tab_id === "string" && /^[a-zA-Z0-9_:.-]{1,128}$/.test(p.tab_id) ? p.tab_id : null;
68
+ // The desktop app seats terminals by these labels; ids stay stable per workspace/tab.
69
+ 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) };
70
+ 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
71
  address: "t" + digest(p.pane_id).slice(0, 12), title, name: null, argv: [], cwd: clip(p.cwd, 512),
42
72
  state: "live", created_ms: 0, screen: "inexact", cols: 80, rows: 24,
43
- labels: { where: clip(p.workspace_id, 128) }, turn: 0,
73
+ labels, turn: 0, status, foreground,
44
74
  } };
45
75
  });
46
76
  cacheUntil = Date.now() + 1_000;
47
77
  return cache;
48
78
  }
49
79
 
80
+ let rectCache = new Map(); // pane_id → { x, y, width, height }
81
+ let rectCacheAt = 0;
82
+ /** pane_id → rect from `pane layout` (one call per tab); empty when the TUI lacks it. */
83
+ async function paneRects() {
84
+ const live = await panes();
85
+ if (live.every((p) => rectCache.has(p.id))) return rectCache; // same panes → same rects
86
+ if (Date.now() < rectCacheAt) return rectCache; // a pane mid-create: keep the last snapshot a moment
87
+ const tabs = [...new Set(live.map((p) => p.tab).filter(Boolean))].slice(0, 40);
88
+ const next = new Map();
89
+ for (const tab of tabs) {
90
+ const probe = live.find((p) => p.tab === tab)?.id;
91
+ if (!probe) continue;
92
+ try {
93
+ const parsed = JSON.parse(await run(["pane", "layout", "--pane", probe]));
94
+ for (const pane of parsed?.result?.layout?.panes ?? []) {
95
+ if (typeof pane?.pane_id === "string" && pane?.rect && ["x", "y", "width", "height"].every((k) => Number.isFinite(pane.rect[k]))) {
96
+ next.set(pane.pane_id, { x: pane.rect.x, y: pane.rect.y, width: pane.rect.width, height: pane.rect.height });
97
+ }
98
+ }
99
+ } catch { /* an older TUI: fall back to a flat row */ }
100
+ }
101
+ rectCache = next;
102
+ rectCacheAt = Date.now() + 1_000;
103
+ return rectCache;
104
+ }
105
+
106
+ /** Split `items` by a clean cut on one axis; the most balanced cut wins. */
107
+ function bisect(items, axis, span) {
108
+ const edges = new Set();
109
+ for (const it of items) { edges.add(it.rect[axis]); edges.add(it.rect[axis] + it.rect[span]); }
110
+ let best = null;
111
+ for (const cut of edges) {
112
+ const left = items.filter((it) => it.rect[axis] + it.rect[span] <= cut);
113
+ const right = items.filter((it) => it.rect[axis] >= cut);
114
+ if (!left.length || !right.length || left.length + right.length !== items.length) continue;
115
+ const lo = Math.min(...items.map((it) => it.rect[axis]));
116
+ const hi = Math.max(...items.map((it) => it.rect[axis] + it.rect[span]));
117
+ const score = Math.abs((cut - lo) - (hi - cut));
118
+ if (!best || score < best.score) best = { cut, left, right, score, lo, hi };
119
+ }
120
+ return best;
121
+ }
122
+
123
+ /** The doc's layout tree for one tab's panes, from their on-screen rectangles. */
124
+ function layoutTree(items, nodeId) {
125
+ if (items.length <= 1) return { id: nodeId, type: "row", children: items.map(blockOf) };
126
+ const x = bisect(items, "x", "width"); // a vertical cut → children side by side
127
+ const y = bisect(items, "y", "height"); // a horizontal cut → children stacked
128
+ const pick = (c) => (c ? c.score / Math.max(1, c.hi - c.lo) : Infinity);
129
+ let cut, axis, span, type;
130
+ if (x && pick(x) <= pick(y)) { cut = x; axis = "x"; span = "width"; type = "row"; }
131
+ else if (y) { cut = y; axis = "y"; span = "height"; type = "column"; }
132
+ else return { id: nodeId, type: "row", children: items.map(blockOf) }; // no clean cut: flat
133
+ const total = cut.hi - cut.lo || 1;
134
+ const extent = (list) => Math.max(...list.map((it) => it.rect[axis] + it.rect[span])) - Math.min(...list.map((it) => it.rect[axis]));
135
+ const share = (list) => ({ weight: Math.max(0.01, Math.round((extent(list) / total) * 1000) / 1000) });
136
+ const child = (list, suffix) => list.length === 1 ? { ...blockOf(list[0]), size: share(list) } : { ...layoutTree(list, nodeId + suffix), size: share(list) };
137
+ return { id: nodeId, type, children: [child(cut.left, "l"), child(cut.right, "r")] };
138
+ }
139
+
140
+ const blockOf = (it) => ({ id: "p" + digest("pane:" + it.pane.id).slice(0, 30), type: "block", content: { terminal: it.pane.terminal.address } });
141
+
142
+ /** Terminal records as the viewers list them: panes with their on-screen geometry. */
143
+ async function terminalRecords() {
144
+ const rects = await paneRects();
145
+ return (await panes()).map(({ id, terminal }) => {
146
+ const rect = rects.get(id);
147
+ return rect ? { ...terminal, cols: Math.max(2, Math.min(1000, rect.width)), rows: Math.max(2, Math.min(1000, rect.height)) } : terminal;
148
+ });
149
+ }
150
+
151
+ /** Seating changes (workspace/tab/pane set) are what change the layout doc. */
152
+ function docFingerprint(records) {
153
+ return JSON.stringify(records.map((t) => [t.address, t.labels["herdr.space"] ?? null, t.labels["herdr.tab"] ?? null]));
154
+ }
155
+
156
+ /** What a viewer must hear about between polls: titles, folders, seating, life. */
157
+ function seenFingerprint(records) {
158
+ return new Map(records.map((t) => [t.address, [t.title, t.cwd, t.labels["herdr.space"] ?? null, t.labels["herdr.tab"] ?? null, t.status ?? null, t.foreground?.cwd ?? null]]));
159
+ }
160
+
50
161
  function clip(x, n) { return typeof x === "string" ? x.slice(0, n) : ""; }
162
+
163
+ let wsLabels = new Map();
164
+ let wsLabelsUntil = 0;
165
+ /** workspace_id → label; empty when the TUI lacks `workspace list` (spaces then go unnamed). */
166
+ async function workspaceLabels() {
167
+ if (Date.now() < wsLabelsUntil) return wsLabels;
168
+ try {
169
+ const parsed = JSON.parse(await run(["workspace", "list"]));
170
+ wsLabels = new Map((Array.isArray(parsed?.result?.workspaces) ? parsed.result.workspaces : [])
171
+ .filter((w) => typeof w?.workspace_id === "string" && typeof w?.label === "string")
172
+ .map((w) => [w.workspace_id, clip(w.label, 120)]));
173
+ } catch { wsLabels = new Map(); }
174
+ wsLabelsUntil = Date.now() + 5_000;
175
+ return wsLabels;
176
+ }
177
+
178
+ /**
179
+ * The `herdr-app` layout document the desktop app renders: each TUI workspace becomes a
180
+ * space (named by its label, placed by its first pane's cwd), each tab a tab, each pane a
181
+ * terminal block. Read-only: structural edits stay in the TUI (doc.set is not offered).
182
+ */
183
+ // Seating maps for doc writes: the doc's digest ids back to Herdr's own ids.
184
+ const seatWorkspace = new Map(); // spaceId → workspace_id
185
+ const seatTab = new Map(); // tabId → { ws, tab }
186
+ const seatPane = new Map(); // terminal address → pane_id
187
+
188
+ let tabLabels = new Map();
189
+ let tabLabelsUntil = 0;
190
+ /** tab_id → label; empty when the TUI lacks `tab list`. */
191
+ async function tabLabelMap() {
192
+ if (Date.now() < tabLabelsUntil) return tabLabels;
193
+ try {
194
+ const parsed = JSON.parse(await run(["tab", "list"]));
195
+ tabLabels = new Map((Array.isArray(parsed?.result?.tabs) ? parsed.result.tabs : [])
196
+ .filter((t) => typeof t?.tab_id === "string" && typeof t?.label === "string")
197
+ .map((t) => [t.tab_id, clip(t.label, 120)]));
198
+ } catch { tabLabels = new Map(); }
199
+ tabLabelsUntil = Date.now() + 5_000;
200
+ return tabLabels;
201
+ }
202
+
203
+ async function layoutDoc() {
204
+ const labels = await workspaceLabels();
205
+ const tabNames = await tabLabelMap();
206
+ const rects = await paneRects();
207
+ const byTab = new Map();
208
+ for (const p of await panes()) {
209
+ if (!p.workspace || !p.tab) continue; // a pane outside every workspace stays off the app's screens
210
+ if (!byTab.has(p.tab)) byTab.set(p.tab, { workspace: p.workspace, panes: [] });
211
+ byTab.get(p.tab).panes.push(p);
212
+ }
213
+ const spaces = new Map();
214
+ for (const [tab, { workspace, panes: tabPanes }] of byTab) {
215
+ const spaceId = "sp" + digest("space:" + workspace).slice(0, 30);
216
+ if (!spaces.has(workspace)) spaces.set(workspace, { id: spaceId, name: labels.get(workspace) || "", folder: tabPanes[0]?.terminal.cwd || "", tabs: new Map() });
217
+ const space = spaces.get(workspace);
218
+ seatWorkspace.set(spaceId, workspace);
219
+ if (!space.folder && tabPanes[0]?.terminal.cwd) space.folder = tabPanes[0].terminal.cwd;
220
+ const tabId = "tb" + digest("tab:" + tab).slice(0, 30);
221
+ seatTab.set(tabId, { ws: workspace, tab });
222
+ let root;
223
+ if (tabPanes.every((p) => rects.has(p.id))) {
224
+ // The TUI's real split structure, rebuilt from the panes' on-screen rectangles.
225
+ 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);
226
+ root = layoutTree(items, tabId);
227
+ } else {
228
+ root = { id: tabId, type: "row", children: tabPanes.map((p) => blockOf({ pane: p })) };
229
+ }
230
+ for (const p of tabPanes) seatPane.set(p.terminal.address, p.id);
231
+ space.tabs.set(tab, { id: tabId, name: tabNames.get(tab) || "", root });
232
+ }
233
+ return { spaces: [...spaces.values()].map((s) => ({ id: s.id, name: s.name, folder: s.folder, tabs: [...s.tabs.values()] })) };
234
+ }
235
+
236
+ const versionOf = (value) => Number.parseInt(digest(JSON.stringify(value)).slice(0, 12), 16);
237
+
238
+ /** Wrap text to a viewer's width, breaking long tokens — a transcript that reads like the pane. */
239
+ function wrapFor(width, text) {
240
+ const cols = Math.max(20, Math.min(200, width - 2));
241
+ const out = [];
242
+ for (const para of text.split("\n")) {
243
+ if (!para.trim()) { out.push(""); continue; }
244
+ let line = "";
245
+ for (let word of para.trim().split(/\s+/)) {
246
+ while (word.length > cols) { // paths and URLs: split rather than overflow
247
+ if (line) { out.push(line); line = ""; }
248
+ out.push(word.slice(0, cols));
249
+ word = word.slice(cols);
250
+ }
251
+ if (!word) continue;
252
+ if (line && line.length + 1 + word.length > cols) { out.push(line); line = word; }
253
+ else line = line ? line + " " + word : word;
254
+ }
255
+ if (line) out.push(line);
256
+ }
257
+ return out.join("\r\n");
258
+ }
259
+
260
+ const sessionCache = new Map(); // pane_id → { session, until } — pane get is a per-read cost otherwise
261
+ async function agentSession(hit) {
262
+ const cached = sessionCache.get(hit.id);
263
+ if (cached && Date.now() < cached.until) return cached.session;
264
+ let session = null;
265
+ try {
266
+ const parsed = JSON.parse(await run(["pane", "get", hit.id]));
267
+ const value = parsed?.result?.pane?.agent_session?.value;
268
+ if (typeof value === "string" && value.endsWith(".jsonl") && value.startsWith(homedir() + "/")) session = value;
269
+ } catch { /* a pane without an agent session simply has no transcript */ }
270
+ sessionCache.set(hit.id, { session, until: Date.now() + 30_000 });
271
+ return session;
272
+ }
273
+
274
+ /** The pane's recent chat as structured blocks — the history that lives inside the agent
275
+ * (π) and never was in the terminal stream. */
276
+ async function transcriptBlocks(hit) {
277
+ const session = await agentSession(hit);
278
+ if (!session) return null;
279
+ try {
280
+ const fh = await openFile(session, "r");
281
+ let chunk;
282
+ try {
283
+ const { size } = await fh.stat();
284
+ const len = Math.min(size, 256 * 1024);
285
+ chunk = Buffer.alloc(len);
286
+ await fh.read(chunk, 0, len, size - len);
287
+ } finally {
288
+ await fh.close();
289
+ }
290
+ const lines = chunk.toString("utf8").split("\n").slice(1); // the head line is usually cut mid-record
291
+ const blocks = [];
292
+ for (const raw of lines.slice(-300)) {
293
+ let entry;
294
+ try { entry = JSON.parse(raw); } catch { continue; }
295
+ if (entry?.type !== "message") continue;
296
+ const message = entry.message ?? {};
297
+ const role = message.role;
298
+ if (role !== "user" && role !== "assistant") continue; // tool chatter stays out of the transcript
299
+ const content = message.content;
300
+ const text = (typeof content === "string" ? content : Array.isArray(content) ? content.filter((x) => x?.type === "text").map((x) => x?.text ?? "").join(" ") : "").trim();
301
+ if (!text) continue;
302
+ blocks.push({ role, text: text.slice(0, 4000) });
303
+ }
304
+ // Newest whole messages first; the oldest drops off whole, never cut mid-thought.
305
+ const kept = blocks.slice(-40);
306
+ let size = kept.reduce((n, b) => n + b.text.length, 0);
307
+ while (kept.length > 1 && size > 40_000) size -= kept.shift().text.length;
308
+ return kept.length ? kept : null;
309
+ } catch {
310
+ return null; // best-effort
311
+ }
312
+ }
313
+
314
+ /** Transcript blocks as the plain lines a text reader (the phone's history view) shows. */
315
+ async function transcriptText(hit) {
316
+ const blocks = await transcriptBlocks(hit);
317
+ if (!blocks) return null;
318
+ return blocks.map((b) => (b.role === "user" ? "❯ " : "● ") + b.text).join("\n");
319
+ }
320
+
321
+ /** The terminal addresses a doc tree shows. */
322
+ function collectTerminals(node, out = []) {
323
+ if (!node || typeof node !== "object") return out;
324
+ if (node.type === "block" && node.content?.terminal) out.push(node.content.terminal);
325
+ for (const child of Array.isArray(node.children) ? node.children : []) collectTerminals(child, out);
326
+ return out;
327
+ }
328
+
329
+ const firstLeaf = (node) => {
330
+ let cur = node;
331
+ for (let depth = 0; cur && depth < 32; depth++) {
332
+ if (cur.type === "block") return cur.content?.terminal ?? null;
333
+ cur = Array.isArray(cur.children) && cur.children.length ? cur.children[0] : null;
334
+ }
335
+ return null;
336
+ };
337
+
338
+ /** Divider drags: weight changes between siblings become pane resize steps. */
339
+ function treeDiffResize(cur, nxt, ops) {
340
+ if (!cur || !nxt || cur.type !== nxt.type) return;
341
+ if ((cur.type !== "row" && cur.type !== "column") || !Array.isArray(cur.children) || cur.children.length !== nxt.children?.length) return;
342
+ const axis = cur.type === "row" ? ["right", "left"] : ["down", "up"];
343
+ for (let i = 0; i < cur.children.length; i++) {
344
+ const c = cur.children[i], x = nxt.children[i];
345
+ const cw = c?.size?.weight, xw = x?.size?.weight;
346
+ if (Number.isFinite(cw) && Number.isFinite(xw) && Math.abs(xw - cw) > 0.01 && xw > cw) {
347
+ // This child grows; the sibling it takes from says which edge moves.
348
+ 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));
349
+ const leaf = firstLeaf(c) ?? firstLeaf(cur.children[i]);
350
+ 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))]);
351
+ }
352
+ treeDiffResize(c, x, ops);
353
+ }
354
+ }
355
+
356
+ const labelArg = (name) => typeof name === "string" && name.trim() && !name.trim().startsWith("-") ? name.trim().slice(0, 120) : null;
357
+ const renameArg = (name) => typeof name === "string" && !name.trim().startsWith("-") ? name.trim().slice(0, 120) : null; // a rename may clear the label
358
+
359
+ /** A doc.set is a diff against the live layout: adds, removals, renames and divider drags. */
360
+ async function applyDocEdit(cur, nxt) {
361
+ if (!nxt || !Array.isArray(nxt.spaces)) throw invalid();
362
+ const ops = [];
363
+ const nextSpaceIds = new Set();
364
+ for (const space of nxt.spaces.slice(0, 40)) {
365
+ if (!space || typeof space.id !== "string" || !Array.isArray(space.tabs)) continue;
366
+ nextSpaceIds.add(space.id);
367
+ const before = cur.spaces.find((s) => s.id === space.id);
368
+ const name = labelArg(space.name);
369
+ if (!before) {
370
+ if (name) ops.push(["workspace", "create", "--label", name]);
371
+ continue; // its tabs arrive with the panes Herdr seats there
372
+ }
373
+ const wsId = seatWorkspace.get(space.id);
374
+ const newName = renameArg(space.name);
375
+ if (newName !== null && newName !== before.name && wsId) ops.push(["workspace", "rename", wsId, newName]);
376
+ const nextTabIds = new Set();
377
+ for (const tab of space.tabs.slice(0, 40)) {
378
+ if (!tab || typeof tab.id !== "string" || !tab.root) continue;
379
+ nextTabIds.add(tab.id);
380
+ const seat = seatTab.get(tab.id);
381
+ const tabName = renameArg(tab.name);
382
+ const curTab = before.tabs.find((t) => t.id === tab.id);
383
+ if (!curTab && seat) ops.push(["tab", "create", "--workspace", seat.ws, ...(labelArg(tab.name) ? ["--label", labelArg(tab.name)] : [])]);
384
+ else if (curTab && tabName !== null && tabName !== curTab.name && seat) ops.push(["tab", "rename", seat.tab, tabName]);
385
+ if (curTab) {
386
+ const keep = new Set(collectTerminals(tab.root));
387
+ for (const addr of collectTerminals(curTab.root)) if (!keep.has(addr) && seatPane.has(addr)) ops.push(["pane", "close", seatPane.get(addr)]);
388
+ }
389
+ }
390
+ for (const tabId of before.tabs.map((t) => t.id)) {
391
+ const seat = seatTab.get(tabId);
392
+ if (!nextTabIds.has(tabId) && seat) ops.push(["tab", "close", seat.tab]);
393
+ }
394
+ }
395
+ for (const space of cur.spaces) {
396
+ const wsId = seatWorkspace.get(space.id);
397
+ if (!nextSpaceIds.has(space.id) && wsId) ops.push(["workspace", "close", wsId]);
398
+ }
399
+ for (const space of nxt.spaces) {
400
+ const before = cur.spaces.find((s) => s.id === space.id);
401
+ if (!before) continue;
402
+ for (const tab of space.tabs ?? []) {
403
+ const curTab = before.tabs.find((t) => t.id === tab.id);
404
+ if (curTab?.root && tab.root) treeDiffResize(curTab.root, tab.root, ops);
405
+ }
406
+ }
407
+ for (const op of ops.slice(0, 40)) {
408
+ try { await run(op); } catch { /* a step that races the TUI must not block the rest */ }
409
+ }
410
+ }
411
+
51
412
  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
413
  class RpcError extends Error {
53
414
  constructor(code, message, kind) { super(message); this.code = code; this.kind = kind; }
@@ -61,19 +422,25 @@ async function findPane(terminal) {
61
422
  return hit;
62
423
  }
63
424
 
64
- async function call(method, p, framed, attach) {
425
+ async function call(method, p, framed, attach, startEvents) {
65
426
  switch (method) {
66
427
  case "hello":
67
428
  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
429
  case "server.status": return status();
69
- case "terminal.list":
70
- case "events.subscribe": {
430
+ case "terminal.list": {
71
431
  const filters = p.labels ?? {};
72
432
  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))) &&
433
+ const terminals = (await terminalRecords()).filter((t) =>
75
434
  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 };
435
+ return { terminals, hidden_finished: 0, machines: [] };
436
+ }
437
+ case "events.subscribe": {
438
+ // A real event stream: the app re-reads the layout doc and terminal list from these,
439
+ // without them it never notices a pane opened or closed on the TUI.
440
+ if (!framed) throw new RpcError(-32000, "Framed connection required", "needs_framed");
441
+ const records = await terminalRecords();
442
+ const channel = startEvents(records);
443
+ return { terminals: records, seq: 0, channel };
77
444
  }
78
445
  case "terminal.send":
79
446
  case "terminal.keys":
@@ -92,24 +459,124 @@ async function call(method, p, framed, attach) {
92
459
  await run(["pane", "send-keys", id, ...keys]);
93
460
  return method === "terminal.interrupt" ? { key: keys[0], outcome: "unknown" } : { turn, status: null };
94
461
  }
462
+ case "terminal.run": {
463
+ if (!interactive) throw new RpcError(-32601, "This pairing is read-only", "forbidden");
464
+ 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();
465
+ // The TUI owns placement: the new pane splits the seat the request labels (or the first pane), in the asked direction.
466
+ const before = await panes();
467
+ const space = p.labels && typeof p.labels["herdr.space"] === "string" ? p.labels["herdr.space"] : null;
468
+ const target = before.find((x) => x.terminal.labels["herdr.space"] === space && space) ?? before[0];
469
+ if (!target) throw new RpcError(-32000, "No pane to split", "unavailable");
470
+ const cwd = typeof p.cwd === "string" && p.cwd && !p.cwd.includes("\0") && p.cwd.length <= 512 && !p.cwd.startsWith("-") ? ["--cwd", p.cwd] : [];
471
+ await run(["pane", "split", "--pane", target.id, "--direction", p.place === "down" ? "down" : "right", ...cwd]);
472
+ // Wait briefly for the new pane to appear beside the one we split, then report it seated.
473
+ let record;
474
+ for (let i = 0; i < 10 && !record; i++) {
475
+ await new Promise((resolve) => setTimeout(resolve, 200));
476
+ cacheUntil = 0; // the pane list is cached a second; force a fresh look
477
+ const fresh = await panes();
478
+ const created = fresh.find((x) => x.tab === target.tab && !before.some((o) => o.id === x.id));
479
+ if (created) {
480
+ record = (await terminalRecords()).find((t) => t.address === created.terminal.address) ?? null;
481
+ try { await run(["pane", "run", created.id, p.argv.join(" ")]); } catch { /* the pane stands; the command is best-effort */ }
482
+ }
483
+ }
484
+ if (!record) throw new RpcError(-32000, "The new pane did not appear", "unavailable");
485
+ return { terminal: record, started: null, wait: null };
486
+ }
487
+ case "terminal.kill": {
488
+ if (!interactive) throw new RpcError(-32601, "This pairing is read-only", "forbidden");
489
+ const hit = await findPane(p.terminal);
490
+ await run(["pane", "close", hit.id]);
491
+ return {};
492
+ }
95
493
  case "terminal.get":
96
494
  case "terminal.attach":
97
495
  case "terminal.read": {
98
496
  const hit = await findPane(p.terminal);
99
- if (method === "terminal.get") return hit.terminal;
497
+ const rect = (await paneRects()).get(hit.id);
498
+ const dims = { cols: Math.max(2, Math.min(1000, rect?.width ?? 80)), rows: Math.max(2, Math.min(1000, rect?.height ?? 24)) };
499
+ if (method === "terminal.get") return { ...hit.terminal, ...dims };
100
500
  if (method === "terminal.attach") {
101
501
  if (!framed) throw new RpcError(-32000, "Framed connection required", "needs_framed");
102
502
  if ([p.cols, p.rows].some((n) => n !== undefined && n !== 0 && !validDimension(n))) throw invalid();
103
- return attach(hit, p);
503
+ return attach(hit, p, rect);
104
504
  }
105
505
  const lines = p.lines ?? 0;
106
506
  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" };
507
+ // An agent pane keeps its chat inside itself: serve the transcript as "stitched"
508
+ // history (the core's term for a full-screen app read by scrolling it).
509
+ const transcript = await transcriptText(hit);
510
+ if (transcript) {
511
+ const all = transcript.split("\n");
512
+ const take = lines > 0 ? all.slice(-Math.min(2000, lines)) : all.slice(-24);
513
+ const text = take.join("\n");
514
+ return { text: text.slice(0, 60 * 1024), complete: transcript.length <= 60 * 1024, how: "stitched", why: null };
515
+ }
516
+ // A shell pane: `recent` carries the history viewers scroll (the phone reads it);
517
+ // a pane with none — fresh — falls back to the on-screen text so it is not blank.
518
+ let text = await run(["pane", "read", hit.id, "--source", "recent", "--lines", String(Math.max(24, Math.min(120, lines + 24))), "--format", "text", "--raw"]);
519
+ let how = "history";
520
+ if (!text.trim()) {
521
+ text = await run(["pane", "read", hit.id, "--source", "visible", "--lines", String(dims.rows), "--format", "text", "--raw"]);
522
+ how = "screen";
523
+ }
524
+ return { text: text.slice(0, 32 * 1024), complete: text.length <= 32 * 1024, how };
109
525
  }
110
526
  case "templates.list": return { templates: [] };
111
527
  case "machine.list": return { machines: [] };
112
- case "doc.get": return { value: null, version: 0 };
528
+ case "terminal.label": {
529
+ if (!interactive) throw new RpcError(-32601, "This pairing is read-only", "forbidden");
530
+ const hit = await findPane(p.terminal);
531
+ const labels = p.labels ?? {};
532
+ if (!labels || typeof labels !== "object" || Array.isArray(labels)) throw invalid();
533
+ const clean = {};
534
+ for (const [k, v] of Object.entries(labels).slice(0, 16)) {
535
+ if (!/^[a-z0-9][a-z0-9._-]{0,63}$/i.test(k) || typeof v !== "string" || v.length > 200) throw invalid();
536
+ // Seating labels are the adapter's; everything else is the app's to keep.
537
+ if (k !== "herdr.space" && k !== "herdr.tab" && k !== "where") clean[k] = v;
538
+ }
539
+ if (Object.keys(clean).length) appLabels.set(hit.id, clean); else appLabels.delete(hit.id);
540
+ saveAppLabels();
541
+ cacheUntil = 0; // the next listing shows the new labels
542
+ return {};
543
+ }
544
+ case "terminal.keep": {
545
+ if (!interactive) throw new RpcError(-32601, "This pairing is read-only", "forbidden");
546
+ await findPane(p.terminal); // Herdr panes already outlive any one viewer
547
+ return {};
548
+ }
549
+ case "doc.set": {
550
+ // Layout edits arrive as a whole document; the TUI applies the difference.
551
+ if (!interactive) throw new RpcError(-32601, "This pairing is read-only", "forbidden");
552
+ if (typeof p.name !== "string" || p.name !== "herdr-app" || p.on) throw invalid();
553
+ if (!p.value || typeof p.value !== "object" || !Array.isArray(p.value.spaces)) throw invalid();
554
+ if (!Number.isSafeInteger(p.version) || p.version < 0) throw invalid();
555
+ const current = await layoutDoc();
556
+ if (p.version !== versionOf(current)) throw new RpcError(-32000, "The TUI layout moved on; read it again", "conflict");
557
+ await applyDocEdit(current, p.value);
558
+ // The edits land on the TUI asynchronously; wait briefly until the doc reflects them.
559
+ const before = versionOf(current);
560
+ let next = current;
561
+ for (let tries = 0; tries < 6; tries++) {
562
+ await new Promise((resolve) => setTimeout(resolve, 200));
563
+ cacheUntil = 0;
564
+ rectCacheAt = 0;
565
+ wsLabelsUntil = 0;
566
+ tabLabelsUntil = 0;
567
+ rectCache = new Map();
568
+ next = await layoutDoc();
569
+ if (versionOf(next) !== before) break;
570
+ }
571
+ return { version: versionOf(next) };
572
+ }
573
+ case "doc.get": {
574
+ if (typeof p.name !== "string" || !p.name || p.name.length > 128) throw invalid();
575
+ if (p.name !== "herdr-app") return { value: null, version: 0 };
576
+ const value = await layoutDoc();
577
+ // Content-derived, so the version is stable while the layout is unchanged.
578
+ return { value, version: versionOf(value) };
579
+ }
113
580
  default: throw new RpcError(-32601, "Method not available on this TUI adapter", "forbidden");
114
581
  }
115
582
  }
@@ -146,15 +613,51 @@ async function serve() {
146
613
  const body = Buffer.from(JSON.stringify(reply));
147
614
  return framed ? frame(0, frameKind.data, body) : output(Buffer.concat([body, Buffer.from("\n")]));
148
615
  }
149
- async function attach(hit, p) {
616
+ async function attach(hit, p, rect) {
150
617
  if (streams.size >= maxStreams || nextChannel > 0xffff_ffff) throw new RpcError(-32000, "Too many open terminal views", "unavailable");
151
618
  const writable = interactive && p.observe !== true;
152
619
  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;
620
+ // The viewer owns the size (herdr-core): attach at what it asked to render at, so the
621
+ // first frame is already its size and no repaint stacks an old screen into its scrollback.
622
+ 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)) };
623
+ let native = writable ? await openTerminal(herdr, hit.target, real.cols, real.rows) : null;
624
+ if (native) {
625
+ // History above the live screen: the agent's own transcript (every viewer), and the
626
+ // terminal scrollback when the viewer asked for it (the desktop app does; the phone
627
+ // does not, and its mirror stays as it was). Herdr streams only the live screen.
628
+ const parts = [];
629
+ const blocks = await transcriptBlocks(hit);
630
+ if (blocks) {
631
+ // Theme-neutral styling: bold/dim attributes only, no palette — π's own `system`
632
+ // theme takes colors from the terminal at runtime, and so does this seed.
633
+ const dim = "\x1b[2m", bold = "\x1b[1m", reset = "\x1b[0m";
634
+ const out = [dim + "──── lịch sử chat (mới nhất ở dưới) ────" + reset];
635
+ for (const b of blocks) {
636
+ const mark = b.role === "user" ? bold + "❯ " + reset : "● ";
637
+ const wrapped = wrapFor(real.cols, b.text).split("\r\n");
638
+ out.push(wrapped[0] ? mark + wrapped[0] : mark);
639
+ for (const line of wrapped.slice(1)) out.push(" " + line);
640
+ out.push("");
641
+ }
642
+ out.push(dim + "──── trở lại hiện tại ────" + reset);
643
+ parts.push(Buffer.from(out.join("\r\n") + "\r\n"));
644
+ }
645
+ if (Number.isSafeInteger(p.history) && p.history > 0) {
646
+ try {
647
+ const back = await run(["pane", "read", hit.id, "--source", "recent", "--lines", String(Math.min(2000, p.history)), "--format", "ansi", "--raw"]);
648
+ const lines = back.split(/\r?\n/);
649
+ const history = lines.slice(0, Math.max(0, lines.length - real.rows)).join("\r\n")
650
+ // Colors stay; terminal replies, links and other noise would only confuse mirrors.
651
+ .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)?/g, "").replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, (m) => (m.endsWith("m") ? m : ""));
652
+ if (history.trim()) parts.push(Buffer.from(history + "\r\n"));
653
+ } catch { /* seeding is best-effort */ }
654
+ }
655
+ if (parts.length) native = { ...native, first: { ...native.first, bytes: Buffer.concat([...parts, native.first.bytes]) } };
656
+ }
154
657
  const channel = nextChannel++;
155
658
  const resize = Boolean(native && p.resize_notifications === true);
156
659
  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 });
660
+ 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
661
  return { channel, terminal, resize_notifications: resize, automatic_input: false };
159
662
  }
160
663
  function release(channel) {
@@ -197,7 +700,7 @@ async function serve() {
197
700
  finally { await closeStream(channel); }
198
701
  }
199
702
  function schedule(delay) {
200
- if (closed || polling || timer || ![...streams.values()].some((s) => !s.native)) return;
703
+ if (closed || polling || timer || ![...streams.values()].some((s) => !s.native && !s.events)) return;
201
704
  timer = setTimeout(() => {
202
705
  timer = undefined;
203
706
  void poll().catch(() => process.stdin.destroy());
@@ -209,7 +712,7 @@ async function serve() {
209
712
  try {
210
713
  for (const [channel, stream] of [...streams]) {
211
714
  // 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;
715
+ if (closed || streams.get(channel) !== stream || stream.native || stream.events || !stream.ready || stream.credit < windowBytes / 2) continue;
213
716
  let snapshot;
214
717
  try { snapshot = await paint(stream.id, stream.rows); }
215
718
  catch {
@@ -227,6 +730,64 @@ async function serve() {
227
730
  }
228
731
  }
229
732
 
733
+ const startEvents = (records) => {
734
+ const channel = nextChannel++;
735
+ streams.set(channel, { events: true, seq: 0, credit: windowBytes, docFp: docFingerprint(records), seen: seenFingerprint(records), ready: true });
736
+ scheduleEvents(0);
737
+ return channel;
738
+ };
739
+ const eventMs = Math.max(250, Number.parseInt(process.env.HERDGATE_TUI_EVENT_MS ?? "1500", 10) || 1500);
740
+ let eventTimer;
741
+ let eventing = false;
742
+ function scheduleEvents(delay) {
743
+ if (closed || eventTimer || ![...streams.values()].some((s) => s.events)) return;
744
+ eventTimer = setTimeout(() => {
745
+ eventTimer = undefined;
746
+ void pumpEvents().catch(() => process.stdin.destroy());
747
+ }, delay);
748
+ eventTimer.unref();
749
+ }
750
+ /** The layout doc and terminal records change on the TUI; retell the subscribers. */
751
+ async function pumpEvents() {
752
+ if (eventing) return;
753
+ eventing = true;
754
+ try {
755
+ const watchers = [...streams].filter(([, s]) => s.events);
756
+ if (!watchers.length) return;
757
+ let records;
758
+ try { records = await terminalRecords(); } catch { return; }
759
+ const docFp = docFingerprint(records);
760
+ const now = seenFingerprint(records);
761
+ for (const [channel, s] of watchers) {
762
+ if (closed || streams.get(channel) !== s) continue;
763
+ const out = [];
764
+ if (s.docFp !== docFp) out.push({ method: "event", params: { seq: ++s.seq, type: "doc" } });
765
+ for (const addr of s.seen.keys()) if (!now.has(addr)) out.push({ method: "event", params: { seq: ++s.seq, type: "removed", terminal: addr, data: {} } });
766
+ for (const t of records) {
767
+ const prev = s.seen.get(t.address);
768
+ if (prev === undefined) out.push({ method: "event", params: { seq: ++s.seq, type: "created", terminal: t.address, data: t } });
769
+ else if (prev.join("\0") !== now.get(t.address).join("\0")) {
770
+ const [title0, cwd0, space0, tabb0, status0, fg0] = prev;
771
+ const [title1, cwd1, space1, tabb1, status1, fg1] = now.get(t.address);
772
+ if (status0 !== status1) out.push({ method: "event", params: { seq: ++s.seq, type: "status", terminal: t.address, data: { status: status1, records: {}, reported: status1 !== null } } });
773
+ if (fg0 !== fg1) out.push({ method: "event", params: { seq: ++s.seq, type: "foreground", terminal: t.address, data: t.foreground } });
774
+ out.push({ method: "event", params: { seq: ++s.seq, type: "labels", terminal: t.address, data: { record: t } } });
775
+ }
776
+ }
777
+ s.docFp = docFp;
778
+ s.seen = now;
779
+ if (out.length && s.credit > 4096) {
780
+ const body = Buffer.from(out.map((e) => JSON.stringify(e)).join("\n") + "\n");
781
+ s.credit -= body.length;
782
+ await frame(channel, frameKind.data, body);
783
+ }
784
+ }
785
+ } finally {
786
+ eventing = false;
787
+ scheduleEvents(eventMs);
788
+ }
789
+ }
790
+
230
791
  try {
231
792
  for await (const chunk of process.stdin) {
232
793
  buffer = Buffer.concat([buffer, chunk]);
@@ -251,10 +812,12 @@ async function serve() {
251
812
  if (stream && kind === frameKind.close && size === 0) await closeStream(channel);
252
813
  if (stream?.native) {
253
814
  try {
254
- if (kind === frameKind.data && size > 0) {
255
- if (size > 32 * 1024) throw invalid();
815
+ if (kind === frameKind.data || kind === 6 /* automatic input: program replies, e.g. cell-size reports */) {
816
+ if (kind === frameKind.data && size > 32 * 1024) throw invalid();
256
817
  await stream.native.send({ type: "terminal.input", bytes: body.toString("base64") });
257
818
  }
819
+ // The viewer owns the size (herdr-core semantics): forwarded, and Herdr
820
+ // restores the pane's own size when this stream closes.
258
821
  if (kind === frameKind.resize && size === 4) {
259
822
  const cols = body.readUInt16LE(0), rows = body.readUInt16LE(2);
260
823
  if (cols > 0 && rows > 0) await stream.native.send({ type: "terminal.resize", cols: Math.min(500, cols), rows: Math.min(300, rows) });
@@ -282,7 +845,7 @@ async function serve() {
282
845
  let result;
283
846
  try {
284
847
  if (msg.params != null && (typeof msg.params !== "object" || Array.isArray(msg.params))) throw invalid();
285
- result = await call(msg.method, msg.params ?? {}, nextFramed, attach);
848
+ result = await call(msg.method, msg.params ?? {}, nextFramed, attach, startEvents);
286
849
  } catch (err) {
287
850
  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
851
  await write({ ...reply, error });
@@ -301,6 +864,7 @@ async function serve() {
301
864
  } finally {
302
865
  closed = true;
303
866
  clearTimeout(timer);
867
+ clearTimeout(eventTimer);
304
868
  for (const channel of streams.keys()) release(channel);
305
869
  }
306
870
  }