@awebai/oats 0.57.0 → 0.57.1

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.
Files changed (50) hide show
  1. package/docs/configuration.md +17 -27
  2. package/docs/desktop.md +14 -0
  3. package/docs/execution-targets.md +6 -1
  4. package/docs/implementation.md +7 -1
  5. package/docs/integrations.md +3 -1
  6. package/docs/official-catalog.md +1 -1
  7. package/docs/packages.md +5 -5
  8. package/docs/release-notes/v0.57.1.md +275 -0
  9. package/docs/servers.md +18 -0
  10. package/docs/tui.md +214 -87
  11. package/docs/workspaces.md +1 -1
  12. package/lib/session-viewer.mjs +29 -4
  13. package/package-catalog.json +1 -1
  14. package/package.json +1 -1
  15. package/packages/client/cli-adapter.mjs +9 -7
  16. package/packages/client/composed-gate.mjs +34 -0
  17. package/packages/client/inspect-boundary.mjs +157 -0
  18. package/packages/client/inspect-cache.mjs +86 -0
  19. package/packages/client/keyed-catalog.mjs +132 -0
  20. package/packages/client/launch-view.mjs +46 -0
  21. package/packages/client/session-attach.mjs +7 -5
  22. package/packages/client/soul-catalog.mjs +77 -0
  23. package/packages/client/soul-colors.mjs +31 -0
  24. package/packages/client/soul-facts.mjs +85 -0
  25. package/packages/client/soul-rows.mjs +48 -0
  26. package/packages/client/spawn-apply-cli.mjs +11 -6
  27. package/packages/client/spawn-apply.mjs +212 -0
  28. package/packages/client/spawn-messages.mjs +131 -85
  29. package/packages/client/spawn-preview-contract.mjs +3 -0
  30. package/packages/client/spawn-preview-facts.mjs +119 -0
  31. package/packages/client/spawn-preview.mjs +152 -0
  32. package/packages/client/spawn-transaction.mjs +136 -0
  33. package/packages/tui/README.md +32 -11
  34. package/packages/tui/lib/actions.mjs +10 -1
  35. package/packages/tui/lib/config.mjs +9 -14
  36. package/packages/tui/lib/main.mjs +165 -57
  37. package/packages/tui/lib/model.mjs +28 -24
  38. package/packages/tui/lib/panel.mjs +955 -0
  39. package/packages/tui/lib/read.mjs +5 -14
  40. package/packages/tui/lib/store.mjs +77 -30
  41. package/packages/tui/lib/term/capture.mjs +260 -0
  42. package/packages/tui/lib/term/screen.mjs +44 -8
  43. package/packages/tui/lib/term/style.mjs +78 -6
  44. package/packages/tui/lib/term/text.mjs +24 -4
  45. package/packages/tui/lib/term/through.mjs +213 -0
  46. package/packages/tui/lib/term/tty.mjs +7 -60
  47. package/packages/tui/lib/views/frame.mjs +126 -40
  48. package/packages/tui/lib/views/help.mjs +12 -10
  49. package/skills/oats-getting-started/SKILL.md +3 -2
  50. package/packages/tui/lib/open.mjs +0 -45
@@ -5,7 +5,7 @@
5
5
  // restart) that the shared callers start through `changeExec`: those are never ended by the TUI,
6
6
  // and their output goes to two files of the run's own private directory, the only files this
7
7
  // module writes. (Opening an agent's terminal starts the kernel's viewer, which is not a read and
8
- // is not started here: lib/open.mjs.)
8
+ // is not started here: it runs in a pane of the panel's private tmux server, lib/panel.mjs.)
9
9
  // No function of this module decodes a kernel answer. Each one passes values between the shared
10
10
  // functions (client.mjs), which decide what a roster, a row and a failed read are, once, for both
11
11
  // clients: the TUI never writes "stopped" for a row and never builds the collector's input by hand.
@@ -198,7 +198,7 @@ const said = (error) => String(error?.message ?? error);
198
198
 
199
199
  /** The reader of a run: its cycles over every served deployment, the roster of other machines,
200
200
  * their children, and the way out.
201
- * -> { start(), request({ live }), touch(), voidInFlight(), hold(), release(), exec, stop(), children() }
201
+ * -> { start(), request({ live }), touch(), voidInFlight(), exec, stop(), children() }
202
202
  *
203
203
  * `cli` is probeKernel's record (`cli.bin` the absolute path of bin/oats.mjs). The reader keeps no
204
204
  * answer of its own: what a run holds is the caller's store, asked for when it is needed.
@@ -230,8 +230,8 @@ const said = (error) => String(error?.message ?? error);
230
230
  * list of options, `detached` is not one of them, and a child it starts stays in the TUI's group
231
231
  * whatever it is asked. `run` below is the part of execFile's contract the shared readers use.
232
232
  *
233
- * ENDING A CHILD: only a read is ever ended. The viewer of an opened agent is lib/open.mjs's, and
234
- * no child of the reader. A KERNEL CALL THAT CHANGES SOMETHING (kind "change", `changeExec`) IS
233
+ * ENDING A CHILD: only a read is ever ended. The viewer of an opened agent runs in the panel's
234
+ * private tmux server (lib/panel.mjs), and is no child of the reader. A KERNEL CALL THAT CHANGES SOMETHING (kind "change", `changeExec`) IS
235
235
  * NEVER SIGNALLED BY THE TUI: a stop killed while it waits leaves a marker that refuses every
236
236
  * later stop, and a killed start leaves its lock (#889, #890). So every child is remembered with
237
237
  * its kind, and only kind "read" is ever signalled.
@@ -255,8 +255,6 @@ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onR
255
255
  * is the epoch the cycle now running began in (the loop runs one at a time). `served` is what
256
256
  * getServed() answered at the start of that cycle. */
257
257
  let counter = 0, epoch = 0, flight = 0, served = [];
258
- /** The terminal is lent (hold()): no cycle and no roster read starts until release(). */
259
- let held = false;
260
258
  /** The roster of other machines. `rosterFlight` is the read in flight (a token of its own, so an
261
259
  * answer knows whether it is still awaited), or null. `rosterEnded` is now() when the last read
262
260
  * that was not given up ended, or null while none has. `gatedSaid`: a kernel that reads no
@@ -526,7 +524,7 @@ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onR
526
524
  * started beside two would be refused as busy and never read). The cycle is over when its
527
525
  * deployments are; with none served it reads nothing local. */
528
526
  async function cycle({ live }) {
529
- if (stopped || held) return;
527
+ if (stopped) return;
530
528
  flight = epoch;
531
529
  const mine = epoch, number = ++counter, at = clock();
532
530
  const over = () => stopped || mine !== epoch;
@@ -591,13 +589,6 @@ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onR
591
589
  rosterFlight = null;
592
590
  endReads({ cycles: true });
593
591
  },
594
- /** The terminal is lent to the kernel's viewer: from now until release() no cycle begins and
595
- * no roster read starts (a cycle the loop's timer or a request would begin does nothing and
596
- * emits nothing). What is in flight is not touched here: the caller made it void first, as at
597
- * a stop. Idempotent. */
598
- hold() { held = true; },
599
- /** The terminal is back: cycles begin again. The caller asks for a live one. */
600
- release() { held = false; },
601
592
  /** See askedExec. */
602
593
  exec: askedExec,
603
594
  /** See changeExec. */
@@ -12,7 +12,7 @@
12
12
  import { ACTIONS, bindings } from "./actions.mjs";
13
13
  import { collapseKey, displayLine, instanceActs, instanceId, pendingEntry } from "./client.mjs";
14
14
  import { DETACH_KEY } from "./config.mjs";
15
- import { BUTTON_ORDER, actDecision, disclosure, openDecision, preflightLine, returnedLine, roster, switcher } from "./model.mjs";
15
+ import { BUTTON_ORDER, NOT_BUILT, actDecision, disclosure, openDecision, preflightLine, returnedLine, roster, switcher } from "./model.mjs";
16
16
  import { windowOf } from "./views/scroll.mjs";
17
17
 
18
18
  /** The longest filter, in UTF-16 units. */
@@ -35,18 +35,23 @@ const NO_FILTER = Object.freeze({ editing: false, query: "" });
35
35
  * `selected`, `top`, `detailTop` are the open view's; `places` keeps them for
36
36
  * the views left behind, and `collapsed` holds every view's keys (each carries its `open`).
37
37
  * `back`: the view under the help. `offered`: the deployments of `~/Agents` not served.
38
- * `opening`: the agent whose terminal is being opened, or null: `{ id, phase, name, machine,
39
- * routed }`, `phase` "preflight" while another machine is asked whether its session is there and
40
- * "lent" while the kernel's viewer has the terminal; `name`, `machine` and `routed` are the row's
41
- * as it was when Enter was pressed, for the line after. `outcome`: that line (the model's
42
- * `{ said, under }`), shown above the panes until the next key bound to an action, or null.
43
- * `detachKey`: tui.json's `open.detachKey`, the key that leaves an agent's terminal.
38
+ * `opening`: the agent of another machine whose terminal is being opened, or null:
39
+ * `{ id, phase: "preflight", name, machine, routed }` while that machine is asked whether its
40
+ * session is there; `name`, `machine` and `routed` are the row's as it was when Enter was
41
+ * pressed, for the line after. `terminal`: the open terminal, or null (one at a time):
42
+ * `{ id, name, machine, routed, focus, zoom, status }`, `id` the row's instanceId and the next
43
+ * three the row's as it was when it was opened; `focus` "terminal" while what is typed goes to
44
+ * the agent and "list" while the TUI reads keys; `zoom` true while it has the whole body (only
45
+ * with the terminal's focus); `status` "starting" until the panel has its window, then "open".
46
+ * `outcome`: the line after an open (the model's `{ said, under }`), shown above the panes until
47
+ * the next key bound to an action, or null.
48
+ * `detachKey`: tui.json's `open.detachKey`, the back key: it takes the focus from the terminal.
44
49
  * `act`: the confirmation open in the act view (see `actOpened`), or null; `acted` counts the
45
50
  * confirmations opened in this run, so an answer for one that was closed is told apart.
46
51
  * `starting`: id -> `{ verb, since }` of this run's starts and restarts whose child is still
47
52
  * alive, whether or not the TUI still waits for its answer (the loop says when one is spawned and
48
53
  * when it closes): no act opens on such a row.
49
- * The roster is made from none of `opening`, `outcome`, `act`, `acted` and `starting`
54
+ * The roster is made from none of `opening`, `terminal`, `outcome`, `act`, `acted` and `starting`
50
55
  * (lib/model.mjs MADE_FROM). */
51
56
  export function initialState({ deployment = null, cli, home, entry = null, actions = ACTIONS, ascii = false, detachKey = DETACH_KEY }) {
52
57
  return Object.freeze({
@@ -58,7 +63,7 @@ export function initialState({ deployment = null, cli, home, entry = null, actio
58
63
  selected: null, collapsed: new Set(), filter: NO_FILTER, focus: "list", top: 0, loose: false, detailTop: 0, places: new Map(), unread: new Map(),
59
64
  switcher: Object.freeze({ editing: false, query: "", selected: null, top: 0, loose: false, line: null, refused: null }),
60
65
  offered: Object.freeze({ offered: Object.freeze([]), limited: false }),
61
- helpTop: 0, actions, ascii, detachKey, opening: null, outcome: null, act: null, acted: 0, starting: new Map(),
66
+ helpTop: 0, actions, ascii, detachKey, opening: null, terminal: null, outcome: null, act: null, acted: 0, starting: new Map(),
62
67
  });
63
68
  }
64
69
 
@@ -297,49 +302,86 @@ function switched(state, action, page) {
297
302
  * (one outcome of the roster read), `{ collecting }`, `{ offered: { offered, limited } }` (the
298
303
  * deployments of `~/Agents` not served), `{ admitted: <deployment>, at }` and `{ refused: <path> }`
299
304
  * (what a picked folder turned out to be).
300
- * Opening an agent gives three more: `{ prepared: { id, error? } }` (the preflight of another
305
+ * Opening an agent gives five more: `{ prepared: { id, error? } }` (the preflight of another
301
306
  * machine's agent ended: `error` is what the shared prepareRemoteTerm threw), `{ given: true }`
302
- * (the loop gave the preflight up itself: a suspend) and `{ returned: { id, status, stderr } }`
303
- * (the viewer closed: its exit status as Node reports it, and the stderr it kept).
307
+ * (the loop gave the preflight up itself: a suspend), `{ shown: { id } }` (the panel has the
308
+ * viewer's window), `{ returned: { id, status, stderr, asked, refused } }` (the viewer ended: what
309
+ * its pane wrote of its exit status and stderr, whether it was closed because the TUI asked, and
310
+ * the panel's refusal when it started none: model.mjs returnedLine) and
311
+ * `{ back: true }` (the back key was typed in the terminal).
304
312
  * An effect is something only the loop can do: "quit", "suspend", "redraw", or an object with
305
313
  * any of `refresh: { live }` (read now), `offer: true` (list `~/Agents` again),
306
- * `admit: <path>` (ask whether a picked folder is a deployment), `open: <decision>` (open the
307
- * agent's terminal: the model's openDecision, with its target), `lend: <id>` (the preflight is
308
- * over: start the viewer it prepared) and `abandon: true` (give the preflight up); or null.
314
+ * `admit: <path>` (ask whether a picked folder is a deployment), `close: <id>` (close the open
315
+ * terminal; when an `open` comes with it, before that open), `open: <decision>` (open the agent's
316
+ * terminal: the model's openDecision, with its target), `panel: <id>` (the preflight is over:
317
+ * start the viewer it prepared in the panel) and `abandon: true` (give the preflight up); or null.
309
318
  * The line after an open stands until the next key that is bound to an action: a key bound to
310
- * nothing (a stray detach key is no key at all) leaves it. */
319
+ * nothing (a stray back key is no key at all) leaves it. */
311
320
  export function reduce(state, event, keymap = bindings(state.actions)) {
312
321
  if (state.outcome !== null && typeof event.key === "string" && keymap.has(event.key)) state = next(state, { outcome: null });
313
- return reduced(state, event, keymap);
322
+ const step = reduced(state, event, keymap);
323
+ // The terminal has the focus only while the list of instances is shown: anything that shows
324
+ // another view (a workspace gone, which shows the switcher) gives the focus back to the list.
325
+ const t = step.state.terminal;
326
+ if (t?.focus !== "terminal") return step;
327
+ if (step.state.view !== "instances") return { ...step, state: next(step.state, { terminal: Object.freeze({ ...t, focus: "list", zoom: false }) }) };
328
+ // While it has the focus, what lies under it is the list: the back key returns there, never to
329
+ // the detail. A filter field open when the focus came (a preflight that ended while it was
330
+ // typed in) is settled, its text kept as Enter keeps it: no key goes to it any more.
331
+ const under = step.state.focus !== "list" || step.state.filter.editing;
332
+ return under ? { ...step, state: next(step.state, { focus: "list", filter: Object.freeze({ ...step.state.filter, editing: false }) }) } : step;
314
333
  }
315
334
 
335
+ /** The terminal of an open decision (the model's openDecision), starting, with the focus. */
336
+ const startingTerminal = ({ id, name, machine, routed }) => Object.freeze({ id, name, machine, routed, focus: "terminal", zoom: false, status: "starting" });
337
+ /** The open terminal with what changes of it. */
338
+ const terminalWith = (state, changes) => next(state, { terminal: Object.freeze({ ...state.terminal, ...changes }) });
339
+
316
340
  /** The preflight of another machine's agent ended. Given up meanwhile (Esc, a suspend, a second
317
341
  * open): dropped. Failed: the line that says so, unless it is the person's own giving up. Else
318
- * the viewer is started, unless the row it is for has gone from the roster since. */
342
+ * the viewer is started in the panel, unless the row it is for has gone from the roster since. */
319
343
  function prepared(state, { id, error }) {
320
344
  const opening = state.opening;
321
345
  if (opening === null || opening.id !== id || opening.phase !== "preflight") return { state, effect: null };
322
346
  if (error !== undefined) return { state: next(state, { opening: null, outcome: preflightLine(opening, error) }), effect: null };
323
347
  if (!roster(state).instances.some((row) => instanceId(row) === id)) return { state: next(state, { opening: null }), effect: null };
324
- return { state: next(state, { opening: Object.freeze({ ...opening, phase: "lent" }) }), effect: { lend: id } };
348
+ return { state: next(state, { opening: null, terminal: startingTerminal(opening) }), effect: { panel: id } };
325
349
  }
326
350
 
327
- /** The viewer closed: the line that says what happened, and the instances read again at once
328
- * (an exit status says nothing of the agent but that it was left by the key). */
329
- function returned(state, { id, status, stderr }) {
330
- const opening = state.opening;
331
- if (opening === null || opening.id !== id) return { state, effect: null };
332
- return { state: next(state, { opening: null, outcome: returnedLine(opening, status, stderr) }), effect: { refresh: { live: true } } };
351
+ /** The viewer of the open terminal ended: the right side is the detail's again, the focus the
352
+ * list's, the line says what happened (nothing, when the person closed it), and the instances are
353
+ * read again at once. It is never opened again on its own: Enter opens it. An end of a terminal
354
+ * that is no longer the open one (closed by the person, then reported) changes nothing. */
355
+ function returned(state, { id, status, stderr, asked = false, refused = null }) {
356
+ const t = state.terminal;
357
+ if (t === null || t.id !== id) return { state, effect: null };
358
+ return { state: next(state, { terminal: null, outcome: returnedLine(t, status, stderr, { asked, refused }) }), effect: { refresh: { live: true } } };
333
359
  }
334
360
 
335
- /** Enter in the list of instances: the selected agent's terminal, or the line that says why not.
336
- * Nothing while an open is under way. */
361
+ /** Enter in the list of instances: on the row whose terminal is open, the focus goes to it; on
362
+ * another, the selected agent's terminal is opened (the open one is closed first: one at a time),
363
+ * or the line says why not. Nothing while another machine is asked first. */
337
364
  function openAgent(state, r, at) {
338
365
  if (state.opening !== null || at < 0) return { state, effect: null };
339
- const row = r.items[at].row, decision = openDecision(state, row, instanceActs(row));
366
+ const row = r.items[at].row, t = state.terminal;
367
+ if (t !== null && t.id === instanceId(row)) return { state: terminalWith(state, { focus: "terminal", zoom: false }), effect: null };
368
+ const decision = openDecision(state, row, instanceActs(row));
340
369
  if (!decision.open) return { state: next(state, { outcome: decision.said }), effect: null };
341
- const opening = Object.freeze({ id: decision.id, phase: decision.routed ? "preflight" : "lent", name: decision.name, machine: decision.machine, routed: decision.routed });
342
- return { state: next(state, { opening, outcome: null }), effect: { open: decision } };
370
+ const close = t === null ? {} : { close: t.id };
371
+ if (decision.routed) {
372
+ const opening = Object.freeze({ id: decision.id, phase: "preflight", name: decision.name, machine: decision.machine, routed: true });
373
+ return { state: next(state, { opening, terminal: null, outcome: null }), effect: { ...close, open: decision } };
374
+ }
375
+ return { state: next(state, { terminal: startingTerminal(decision), outcome: null }), effect: { ...close, open: decision } };
376
+ }
377
+
378
+ /** The keys of the open terminal from the list: zoom gives it the focus and the whole body, and
379
+ * close ends its viewer (the agent keeps running) and gives the right side back to the detail. */
380
+ function terminalKey(state, action) {
381
+ const t = state.terminal;
382
+ if (t === null) return { state, effect: null };
383
+ if (action === "zoom") return { state: terminalWith(state, { focus: "terminal", zoom: true }), effect: null };
384
+ return { state: next(state, { terminal: null }), effect: { close: t.id } };
343
385
  }
344
386
 
345
387
  /** The keys of the act view that are not the action table's: the focus moves with these and with
@@ -443,6 +485,8 @@ function reduced(state, event, keymap) {
443
485
  if (event.prepared !== undefined) return prepared(state, event.prepared);
444
486
  if (event.given !== undefined) return state.opening?.phase === "preflight" ? { state: next(state, { opening: null }), effect: null } : stay;
445
487
  if (event.returned !== undefined) return returned(state, event.returned);
488
+ if (event.shown !== undefined) return state.terminal?.id === event.shown.id ? { state: terminalWith(state, { status: "open" }), effect: null } : stay;
489
+ if (event.back !== undefined) return state.terminal?.focus === "terminal" ? { state: terminalWith(state, { focus: "list", zoom: false }), effect: null } : stay;
446
490
  if (event.entry !== undefined) return took(state, event);
447
491
  if (event.roster !== undefined) return heard(state, event.roster);
448
492
  if (event.collecting !== undefined) return { state: event.collecting === state.collecting ? state : next(state, { collecting: event.collecting === true }), effect: null };
@@ -491,6 +535,9 @@ function reduced(state, event, keymap) {
491
535
  switch (action) {
492
536
  case "filter": return { state: next(state, { focus: "list", filter: Object.freeze({ ...state.filter, editing: true }) }), effect: null };
493
537
  case "open": return openAgent(state, r, at);
538
+ case "zoom": case "close-terminal": return terminalKey(state, action);
539
+ // The views not built yet: the line says what to run instead.
540
+ case "souls": case "capabilities": return { state: next(state, { outcome: NOT_BUILT[action] }), effect: null };
494
541
  case "stop": case "retire": case "start": case "restart": return actOn(state, r, at, action);
495
542
  case "detail": return at < 0 ? stay : { state: next(state, { focus: state.focus === "detail" ? "list" : "detail" }), effect: null };
496
543
  case "up": case "down": case "top": case "bottom": case "page-up": case "page-down": {
@@ -0,0 +1,260 @@
1
+ // An agent's terminal, as cells: what `tmux capture-pane -e -N` captured (the text `-p` prints), turned into the
2
+ // screen's spans (term/screen.mjs). Pure: no IO.
3
+ //
4
+ // The capture is text the TUI did not write, from a program that may write anything, so nothing
5
+ // of it reaches the screen as it came. The characters are kept, measured by width.mjs, and set
6
+ // at the column each one takes; of the escape sequences only SGR is read, as a state machine
7
+ // over an allowlist, and the style of a cell is built from that state by style.mjs's
8
+ // agentStyle(). Every other sequence, every control character and every bidi control is
9
+ // dropped, and what is left becomes safe text through text.mjs's cellText(), which refuses
10
+ // anything this module should have dropped.
11
+ //
12
+ // How tmux writes a capture with `-e` (measured on tmux 3.7c): each row is the pane's cells from
13
+ // column 0 and ends at "\n"; a wide character is written once, the next character two cells on;
14
+ // a run of cells a tab left is one "\t"; an attribute is written where it changes from the cell
15
+ // before, ACROSS rows (a row that goes on in the style the last one ended in starts with no SGR
16
+ // at all), so the SGR state is carried from row to row and starts plain at the first row; and a
17
+ // hyperlink is an OSC 8, which is dropped with the rest.
18
+ import { cells } from "./width.mjs";
19
+ import { cellText } from "./text.mjs";
20
+ import { agentStyle, blankShows } from "./style.mjs";
21
+
22
+ /** Tab stops are every 8 columns: tmux writes a tab's cells as one "\t" and does not say how
23
+ * many there were, and a program that set its own stops is the rare case. Each row is set on its
24
+ * own, so a stop guessed wrong moves only the rest of that row. A tab moves to the stop and paints
25
+ * nothing: the cells it passes are blank. */
26
+ const TAB = 8;
27
+ /** A run of characters that are written as they are: no control (C0, DEL, C1) and no bidi
28
+ * control. Sticky, so each run is matched where the scan stands. */
29
+ const TEXT_RUN = /[^\x00-\x1f\x7f-\x9f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]+/y;
30
+
31
+ // ── The SGR state ────────────────────────────────────────────────────────────────────────────────
32
+
33
+ /** The state with nothing set. A state is a plain object this module alone changes; agentStyle()
34
+ * interns the style made from it. */
35
+ const fresh = () => ({ bold: false, dim: false, italic: false, underline: false, blink: false, reverse: false, invisible: false, strikethrough: false, fg: null, bg: null });
36
+ /** Single parameters that set or clear attributes, and what each does to the state. */
37
+ const SIMPLE = new Map([
38
+ [1, { bold: true }], [2, { dim: true }], [3, { italic: true }], [4, { underline: true }],
39
+ [5, { blink: true }], [6, { blink: true }], [7, { reverse: true }], [8, { invisible: true }], [9, { strikethrough: true }],
40
+ [21, { bold: false }], [22, { bold: false, dim: false }], [23, { italic: false }], [24, { underline: false }],
41
+ [25, { blink: false }], [27, { reverse: false }], [28, { invisible: false }], [29, { strikethrough: false }],
42
+ [39, { fg: null }], [49, { bg: null }],
43
+ ]);
44
+ /** A parameter as a number: decimal digits only, at most three of them (no value this module
45
+ * keeps is larger), else null. An empty parameter is 0, as ECMA-48 has it. */
46
+ function number(text) {
47
+ if (text === "") return 0;
48
+ return /^\d{1,3}$/.test(text) ? Number(text) : null;
49
+ }
50
+ const byte = (text) => { const n = text === undefined ? null : number(text); return n !== null && n < 256 ? n : null; };
51
+ /** The colour an extended form names: `5;n` or `2;r;g;b`, as the list of what follows 38 or 48.
52
+ * Null when malformed or out of range. */
53
+ function extended(kind, values) {
54
+ if (kind === 5 && values.length === 1) { const n = byte(values[0]); return n === null ? null : { index: n }; }
55
+ if (kind === 2 && values.length === 3) { const rgb = values.map(byte); return rgb.includes(null) ? null : { rgb }; }
56
+ return null;
57
+ }
58
+
59
+ /** Applies the parameters of one SGR (`ESC [ <params> m`, the params as written) to the state.
60
+ * An allowlist: a parameter not named here is dropped and the rest still apply. An extended
61
+ * colour (38, 48, and 58 which is dropped) consumes what its selector claims, 5 one value and 2
62
+ * three, even when a value is missing or out of range, so a malformed colour is dropped and
63
+ * never read as attributes; a selector that is neither leaves the rest of the list unreadable,
64
+ * and the rest is dropped. The colon forms (4:n, 38:5:n, 38:2::r:g:b, 38:2:r:g:b) are one parameter each. */
65
+ function applySgr(state, params) {
66
+ const list = params.split(";");
67
+ for (let i = 0; i < list.length; i++) {
68
+ const p = list[i];
69
+ if (p.includes(":")) { colon(state, p.split(":")); continue; }
70
+ const n = number(p);
71
+ if (n === null) continue;
72
+ if (n === 0) Object.assign(state, fresh());
73
+ else if (SIMPLE.has(n)) Object.assign(state, SIMPLE.get(n));
74
+ else if (n >= 30 && n <= 37) state.fg = { ansi: n - 30 };
75
+ else if (n >= 90 && n <= 97) state.fg = { ansi: n - 90 + 8 };
76
+ else if (n >= 40 && n <= 47) state.bg = { ansi: n - 40 };
77
+ else if (n >= 100 && n <= 107) state.bg = { ansi: n - 100 + 8 };
78
+ else if (n === 38 || n === 48 || n === 58) {
79
+ const kind = number(list[i + 1] ?? "x");
80
+ const claims = kind === 5 ? 1 : kind === 2 ? 3 : null;
81
+ if (claims === null) return;
82
+ // 58, the underline's colour, is read as the other two are only to be dropped whole: its
83
+ // values are not attributes (tmux writes it as 58;5;n, and its 5 is not a blink).
84
+ const colour = n === 58 ? null : extended(kind, list.slice(i + 2, i + 2 + claims));
85
+ if (colour) state[n === 38 ? "fg" : "bg"] = colour;
86
+ i += 1 + claims;
87
+ }
88
+ }
89
+ }
90
+ /** One colon parameter: 4:n (0 off, 1 to 5 an underline of some kind, which is kept as on), or an
91
+ * extended colour 38:5:n, 38:2:r:g:b or 38:2:<colour space>:r:g:b (and 48). Anything else, the
92
+ * underline colour 58 among them, is dropped. */
93
+ function colon(state, sub) {
94
+ if (sub[0] === "4" && sub.length === 2) {
95
+ const n = number(sub[1]);
96
+ if (n !== null && n <= 5) state.underline = n !== 0;
97
+ return;
98
+ }
99
+ if (sub[0] !== "38" && sub[0] !== "48") return;
100
+ const kind = number(sub[1] ?? "x");
101
+ let values = sub.slice(2);
102
+ if (kind === 2 && values.length === 4 && /^\d*$/.test(values[0])) values = values.slice(1);
103
+ const colour = extended(kind, values);
104
+ if (colour) state[sub[0] === "38" ? "fg" : "bg"] = colour;
105
+ }
106
+
107
+ // ── Sequences ────────────────────────────────────────────────────────────────────────────────────
108
+
109
+ /** Where a control string (OSC, DCS, SOS, PM, APC) that starts at `from` ends: past its BEL (OSC
110
+ * only), its ST (`ESC \` or U+009C), or before an ESC that starts something else. -1 when the row
111
+ * ends first: the string is cut, and the rest of the row with it. */
112
+ function stringEnd(row, from, bel) {
113
+ for (let i = from; i < row.length; i++) {
114
+ const c = row.charCodeAt(i);
115
+ if ((bel && c === 0x07) || c === 0x9c) return i + 1;
116
+ if (c === 0x1b) return row[i + 1] === "\\" ? i + 2 : i;
117
+ }
118
+ return -1;
119
+ }
120
+ /** Where a CSI whose parameters start at `from` ends, and its parameters and final byte:
121
+ * `{ end, params, final }`, with `final` null when a byte outside a CSI stops it (the sequence
122
+ * ends before that byte, which is read again). `end` -1 when the row ends first. */
123
+ function csiEnd(row, from) {
124
+ let i = from;
125
+ while (i < row.length && row.charCodeAt(i) >= 0x30 && row.charCodeAt(i) <= 0x3f) i++;
126
+ const params = row.slice(from, i);
127
+ let intermediate = false;
128
+ while (i < row.length && row.charCodeAt(i) >= 0x20 && row.charCodeAt(i) <= 0x2f) { i++; intermediate = true; }
129
+ if (i >= row.length) return { end: -1 };
130
+ const c = row.charCodeAt(i);
131
+ if (c >= 0x40 && c <= 0x7e) return { end: i + 1, params, final: intermediate ? null : row[i] };
132
+ return { end: i, params, final: null };
133
+ }
134
+ /** Whether the parameters are an SGR's: a CSI with final `m` and no private marker (`<`, `=`, `>`,
135
+ * `?`: `CSI > 4;1 m` sets a keyboard mode, not a style). */
136
+ const isSgr = (final, params) => final === "m" && /^[0-9:;]*$/.test(params);
137
+
138
+ // ── Rows ─────────────────────────────────────────────────────────────────────────────────────────
139
+
140
+ /** One row of the capture as spans, from the SGR `state` it starts in, which it leaves as the row
141
+ * ended so the next row goes on from it. Past `cols` no character is kept, but the SGRs are
142
+ * still read: the next row may start in the style this one ended in. */
143
+ function captureRow(row, cols, state) {
144
+ const placed = [];
145
+ let col = 0, full = cols <= 0;
146
+ let look = agentStyle(state), pending = "";
147
+ /** Sets what was read in the current style, grapheme by grapheme, from the running column. */
148
+ function flush() {
149
+ if (pending === "") return;
150
+ const text = pending;
151
+ pending = "";
152
+ if (full) return;
153
+ for (const g of cells(text)) {
154
+ // A wide grapheme that would cross the edge is dropped, and so is everything after it: the
155
+ // terminal set the next one two cells on, past the edge too.
156
+ if (col + g.width > cols) { full = true; return; }
157
+ placed.push({ col, text: g.text, width: g.width, style: look });
158
+ col += g.width;
159
+ }
160
+ if (col >= cols) full = true;
161
+ }
162
+ /** After an SGR: the same style goes on in the same run, so graphemes split by an SGR that
163
+ * changed nothing are measured together, as the screen will measure them. */
164
+ function restyle() {
165
+ if (full) return;
166
+ const next = agentStyle(state);
167
+ if (next !== look) { flush(); look = next; }
168
+ }
169
+
170
+ for (let i = 0; i < row.length;) {
171
+ TEXT_RUN.lastIndex = i;
172
+ const run = TEXT_RUN.exec(row);
173
+ if (run) {
174
+ if (!full) pending += run[0];
175
+ i += run[0].length;
176
+ continue;
177
+ }
178
+ const c = row.charCodeAt(i);
179
+ if (c === 0x09) {
180
+ flush();
181
+ if (!full) { col = Math.min(col + TAB - (col % TAB), cols); full = col >= cols; }
182
+ i++;
183
+ continue;
184
+ }
185
+ if (c === 0x1b || c === 0x9b || c === 0x9d || c === 0x90 || c === 0x98 || c === 0x9e || c === 0x9f) {
186
+ const eight = c !== 0x1b;
187
+ const kind = eight ? String.fromCharCode(c - 0x40) : row[i + 1];
188
+ const body = eight ? i + 1 : i + 2;
189
+ // An ESC that ends the row: the sequence it began is cut, and dropped.
190
+ if (kind === undefined) break;
191
+ if (kind === "[") {
192
+ const { end, params, final } = csiEnd(row, body);
193
+ if (end < 0) break;
194
+ // Only the 7-bit SGR is read: the 8-bit CSI (U+009B) is dropped whole, its style too.
195
+ if (!eight && isSgr(final, params)) { applySgr(state, params); restyle(); }
196
+ i = end;
197
+ } else if (kind === "]" || kind === "P" || kind === "X" || kind === "^" || kind === "_") {
198
+ const end = stringEnd(row, body, kind === "]");
199
+ if (end < 0) break;
200
+ i = end;
201
+ } else {
202
+ // ESC with intermediates and a final (ESC ( B), or ESC and one final byte; an ESC before
203
+ // anything else is dropped alone and what follows it is read again.
204
+ let j = i + 1;
205
+ while (j < row.length && row.charCodeAt(j) >= 0x20 && row.charCodeAt(j) <= 0x2f) j++;
206
+ if (j >= row.length) break;
207
+ const f = row.charCodeAt(j);
208
+ i = f >= 0x30 && f <= 0x7e ? j + 1 : j > i + 1 ? j : i + 1;
209
+ }
210
+ continue;
211
+ }
212
+ // Every other control character, and a bidi control: dropped.
213
+ i++;
214
+ }
215
+ flush();
216
+ return spans(placed);
217
+ }
218
+
219
+ /** The placed graphemes as spans: consecutive graphemes of one style, with no gap a tab left
220
+ * between them, are one span. Spaces in a style that shows nothing on a blank are left to the
221
+ * screen's own blank cells, so such a span never starts or ends with one, and a run of nothing
222
+ * else makes no span. */
223
+ function spans(placed) {
224
+ const out = [];
225
+ let open = null;
226
+ for (const g of placed) {
227
+ if (open && open.style === g.style && open.end === g.col) { open.graphemes.push(g); open.end += g.width; continue; }
228
+ open = { style: g.style, graphemes: [g], end: g.col + g.width };
229
+ out.push(open);
230
+ }
231
+ const result = [];
232
+ for (const { style, graphemes } of out) {
233
+ let first = 0, last = graphemes.length;
234
+ if (!blankShows(style)) {
235
+ while (first < last && graphemes[first].text === " ") first++;
236
+ while (last > first && graphemes[last - 1].text === " ") last--;
237
+ }
238
+ if (first === last) continue;
239
+ const kept = graphemes.slice(first, last);
240
+ const width = kept.reduce((sum, g) => sum + g.width, 0);
241
+ result.push(Object.freeze({ col: kept[0].col, text: cellText(kept.map((g) => g.text).join("")), style, width }));
242
+ }
243
+ return Object.freeze(result);
244
+ }
245
+
246
+ /** The rows of a capture-pane answer (`tmux capture-pane -e -N`, as `-p` prints it) as the screen's spans, for a
247
+ * panel of `cols` by `rows` cells: exactly `rows` rows, the first ones of the capture, each an
248
+ * array of `{ col, text, style, width }` with `col` from 0 inside the panel, `text` safe text
249
+ * (cellText), `style` an agent style (or PLAIN) and `width` the cells it takes. A row holds at
250
+ * most `cols` cells: what is past the edge is dropped, never wrapped. A capture with fewer rows
251
+ * gives empty rows after them; the newline that ends the last row is not a row of its own. */
252
+ export function captureRows(text, { cols, rows }) {
253
+ if (typeof text !== "string") throw new TypeError("a capture is the text tmux answered");
254
+ if (!Number.isInteger(cols) || cols < 0 || !Number.isInteger(rows) || rows < 0) throw new RangeError("a panel's size is a number of cells");
255
+ const lines = text.split("\n");
256
+ if (text.endsWith("\n")) lines.pop();
257
+ const state = fresh(), out = [];
258
+ for (let r = 0; r < rows; r++) out.push(r < lines.length ? captureRow(lines[r], cols, state) : Object.freeze([]));
259
+ return Object.freeze(out);
260
+ }
@@ -1,28 +1,38 @@
1
1
  // The screen: a buffer of cells and the bytes that turn the previous frame into the next one.
2
2
  // With term/tty.mjs it is the only module that produces an ESC byte, and what it writes is a closed
3
- // list: a position, an erase, an SGR of style.mjs's parameters. Text reaches it as safe text only
4
- // (term/text.mjs); a string is refused.
3
+ // list: a position (CSI row;col H); an erase (CSI K, CSI 2J); an SGR it builds itself, a reset and
4
+ // the parameters style.mjs answers for a style value, of either kind (CSI 0;...m); the
5
+ // synchronized-output pair around each frame (CSI ?2026h, CSI ?2026l); and the cursor shown or
6
+ // hidden (CSI ?25h, CSI ?25l). Text reaches it as safe text only (term/text.mjs); a string is
7
+ // refused.
5
8
  //
6
9
  // The rules a width disagreement cannot break (docs/tui.md): every row write starts with an
7
10
  // absolute position and is erased to its end, so a character the terminal draws wider or narrower
8
11
  // than width.mjs counts moves nothing outside its own row; nothing is written past the last column.
12
+ //
13
+ // Each frame that writes anything is one synchronized update (DEC mode 2026): the terminal shows
14
+ // it whole or not yet, never half drawn. The mode is set at the start of the frame and reset at its
15
+ // end, so no frame leaves it set; a terminal that does not know the mode ignores both. The cursor
16
+ // is placed after every row, since each row write moves it.
9
17
  import { cells } from "./width.mjs";
10
18
  import { textOf } from "./text.mjs";
11
- import { PLAIN, isStyle, sgr } from "./style.mjs";
19
+ import { PLAIN, blankShows, isStyle, sgr } from "./style.mjs";
12
20
 
13
21
  const CSI = "\x1b[";
14
22
  const RESET = `${CSI}0m`;
15
23
  const CLEAR = `${CSI}2J`;
16
24
  const ERASE_TO_END = `${CSI}K`;
17
25
  const position = (row, col) => `${CSI}${row + 1};${col + 1}H`;
26
+ const SYNC_BEGIN = `${CSI}?2026h`;
27
+ const SYNC_END = `${CSI}?2026l`;
28
+ const CURSOR_SHOW = `${CSI}?25h`;
29
+ const CURSOR_HIDE = `${CSI}?25l`;
18
30
 
19
31
  const cell = (text, width, style) => Object.freeze({ text, width, style });
20
32
  const BLANK = cell(" ", 1, PLAIN);
21
33
  /** The second cell of a two-cell grapheme: it holds nothing to write. */
22
34
  const TAIL = cell("", 0, PLAIN);
23
35
  const PRINTABLE_ASCII = /^[\x20-\x7e]$/;
24
- /** A cell that shows nothing: a space in a style that draws nothing on a space. */
25
- const shows = (c) => c.text !== " " || c.style.underline || c.style.reverse;
26
36
 
27
37
  /** What the locale and `--ascii` decide: `utf8`, whether the terminal is told to read UTF-8
28
38
  * (LC_ALL, else LC_CTYPE, else LANG names it), and `ascii`, whether the TUI's own marks and rules
@@ -33,7 +43,10 @@ export function glyphs(env, { ascii = false } = {}) {
33
43
  return { utf8, ascii: ascii || !utf8 };
34
44
  }
35
45
 
36
- /** A screen. `render(rows, size, { full })` answers the bytes for one frame and remembers it.
46
+ /** A screen. `render(rows, size, { full, cursor })` answers the bytes for one frame and remembers
47
+ * it: "" when nothing changed, else one synchronized update. `cursor` is null (hidden, as the
48
+ * TUI keeps it) or `{ row, col }`, a cell of the frame from 0, where the cursor is left shown; one
49
+ * outside the size is hidden. `full` draws the frame whole and states the cursor again.
37
50
  * `rows[r]` is the spans of row r, drawn in order, a later one over an earlier one:
38
51
  * `{ col, text, style?, width? }`, `text` safe text, `width` the cells the span may take (default:
39
52
  * to the right edge); or a fill, `{ col, width, style? }`, `width` blank cells in that style.
@@ -42,6 +55,10 @@ export function glyphs(env, { ascii = false } = {}) {
42
55
  export function createScreen({ utf8 = true, ascii = !utf8, color = true } = {}) {
43
56
  const mark = cells(ascii ? "..." : "\u2026");
44
57
  let previous = null;
58
+ /** The cursor the last frame left: null hidden, else `{ row, col }` shown there. */
59
+ let cursorShown = null;
60
+ /** A cell that shows: anything but a space, or a space in a style that paints it. */
61
+ const shows = (c) => c.text !== " " || blankShows(c.style, { color });
45
62
 
46
63
  /** Overwriting one half of a two-cell grapheme blanks the other half. */
47
64
  function clear(line, x) {
@@ -114,7 +131,16 @@ export function createScreen({ utf8 = true, ascii = !utf8, color = true } = {})
114
131
  return end < line.length ? out + ERASE_TO_END : out;
115
132
  }
116
133
 
117
- function render(rows, size, { full = false } = {}) {
134
+ /** Where the frame leaves the cursor: null hidden, else a cell inside the size. */
135
+ function cursorOf(cursor, size) {
136
+ if (cursor === null || cursor === undefined) return null;
137
+ if (typeof cursor !== "object" || !Number.isInteger(cursor.row) || !Number.isInteger(cursor.col)) throw new TypeError("a cursor is null or { row, col }, a cell index from 0");
138
+ const { row, col } = cursor;
139
+ return row >= 0 && col >= 0 && row < size.rows && col < size.cols ? { row, col } : null;
140
+ }
141
+
142
+ function render(rows, size, { full = false, cursor = null } = {}) {
143
+ const wanted = cursorOf(cursor, size);
118
144
  const lines = layout(rows, size);
119
145
  const redraw = full || !previous || previous.cols !== size.cols || previous.rows !== size.rows;
120
146
  let out = redraw ? RESET + CLEAR : "";
@@ -127,8 +153,18 @@ export function createScreen({ utf8 = true, ascii = !utf8, color = true } = {})
127
153
  // as sure as the width table, so nothing in it is addressed by column.
128
154
  out += writeRow(r, line, asciiOnly(line) && asciiOnly(old) ? changed : 0);
129
155
  }
156
+ // The cursor after every row: a row write leaves it at the row's end, so a shown cursor is
157
+ // placed again whenever a row was written, and a redraw shows it again (the guard's ENTER, at
158
+ // a start, a resume or a Ctrl+L, hides it). A hidden one is hidden only when this screen had
159
+ // shown it: hiding it is the guard's, and a frame adds no mode the guard did not switch.
160
+ if (wanted) {
161
+ const moved = out !== "" || !cursorShown || cursorShown.row !== wanted.row || cursorShown.col !== wanted.col;
162
+ if (moved) out += position(wanted.row, wanted.col);
163
+ if (redraw || !cursorShown) out += CURSOR_SHOW;
164
+ } else if (cursorShown) out += CURSOR_HIDE;
130
165
  previous = { cols: size.cols, rows: size.rows, lines };
131
- return out;
166
+ cursorShown = wanted;
167
+ return out === "" ? "" : SYNC_BEGIN + out + SYNC_END;
132
168
  }
133
169
  return { render, cells: layout };
134
170
  }