@awebai/oats 0.57.0 → 0.58.0

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 (60) hide show
  1. package/bin/oats.mjs +24 -11
  2. package/docs/configuration.md +19 -28
  3. package/docs/desktop-cli-api.md +38 -15
  4. package/docs/desktop.md +14 -0
  5. package/docs/execution-targets.md +10 -1
  6. package/docs/implementation.md +7 -1
  7. package/docs/integrations.md +3 -1
  8. package/docs/official-catalog.md +1 -1
  9. package/docs/packages.md +5 -5
  10. package/docs/release-notes/v0.57.1.md +275 -0
  11. package/docs/release-notes/v0.58.0.md +107 -0
  12. package/docs/servers.md +18 -0
  13. package/docs/souls-and-instances.md +9 -0
  14. package/docs/tui.md +224 -87
  15. package/docs/workspaces.md +1 -1
  16. package/lib/core.mjs +11 -4
  17. package/lib/session-viewer.mjs +29 -4
  18. package/package-catalog.json +1 -1
  19. package/package.json +1 -1
  20. package/packages/client/cli-adapter.mjs +9 -7
  21. package/packages/client/cli-locator.mjs +2 -2
  22. package/packages/client/composed-gate.mjs +34 -0
  23. package/packages/client/inspect-boundary.mjs +157 -0
  24. package/packages/client/inspect-cache.mjs +86 -0
  25. package/packages/client/keyed-catalog.mjs +132 -0
  26. package/packages/client/launch-view.mjs +46 -0
  27. package/packages/client/panel-views.mjs +1 -1
  28. package/packages/client/session-attach.mjs +7 -5
  29. package/packages/client/soul-catalog.mjs +77 -0
  30. package/packages/client/soul-colors.mjs +31 -0
  31. package/packages/client/soul-facts.mjs +85 -0
  32. package/packages/client/soul-rows.mjs +48 -0
  33. package/packages/client/spawn-apply-cli.mjs +19 -8
  34. package/packages/client/spawn-apply.mjs +216 -0
  35. package/packages/client/spawn-messages.mjs +131 -85
  36. package/packages/client/spawn-preview-cli.mjs +2 -1
  37. package/packages/client/spawn-preview-contract.mjs +3 -0
  38. package/packages/client/spawn-preview-facts.mjs +119 -0
  39. package/packages/client/spawn-preview.mjs +164 -0
  40. package/packages/client/spawn-transaction.mjs +136 -0
  41. package/packages/record/lib/directory-identity.mjs +14 -0
  42. package/packages/record/lib/native-history.mjs +6 -5
  43. package/packages/tui/README.md +32 -11
  44. package/packages/tui/lib/actions.mjs +10 -1
  45. package/packages/tui/lib/config.mjs +9 -14
  46. package/packages/tui/lib/main.mjs +165 -57
  47. package/packages/tui/lib/model.mjs +28 -24
  48. package/packages/tui/lib/panel.mjs +1019 -0
  49. package/packages/tui/lib/read.mjs +5 -14
  50. package/packages/tui/lib/store.mjs +77 -30
  51. package/packages/tui/lib/term/capture.mjs +260 -0
  52. package/packages/tui/lib/term/screen.mjs +44 -8
  53. package/packages/tui/lib/term/style.mjs +78 -6
  54. package/packages/tui/lib/term/text.mjs +24 -4
  55. package/packages/tui/lib/term/through.mjs +213 -0
  56. package/packages/tui/lib/term/tty.mjs +7 -60
  57. package/packages/tui/lib/views/frame.mjs +126 -40
  58. package/packages/tui/lib/views/help.mjs +12 -10
  59. package/skills/oats-getting-started/SKILL.md +3 -2
  60. package/packages/tui/lib/open.mjs +0 -45
@@ -0,0 +1,1019 @@
1
+ // An agent's terminal in a panel beside the list. The kernel's viewer (`oats session attach`, a
2
+ // node process that runs a tmux client attached to the agent's own tmux server) runs in a pane of
3
+ // a PRIVATE tmux server that this TUI run owns; the TUI keeps ONE control-mode client of that
4
+ // server for the run, captures the pane when tmux says it changed, and sends the keys to it.
5
+ // This is the only module of the TUI that runs tmux. It knows nothing of rows, keys or views: the
6
+ // caller hands it the viewer's argv, a size and the bytes to type, and it hands back screens (built
7
+ // by the caller's own cell builder) and the end of each viewer.
8
+ //
9
+ // THE SERVER. Its socket is `<run dir>/tmux`, in the run's private directory (0700, made by the
10
+ // caller's `dir()`, shared with the reader). Every call is `tmux -u -f /dev/null -S <socket> …`
11
+ // with TMUX and TMUX_PANE removed from the environment it gets, so it reads neither the user's
12
+ // configuration nor their default server, and never mistakes itself for a client nested in the
13
+ // pane the TUI runs in. `-f` matters only to the call that starts the server, and is on every call
14
+ // so that no call can ever start one that reads a configuration. The first open writes
15
+ // `<run dir>/owner.json` ({ tool, pid, started }), which is what lets a later run's sweep (below)
16
+ // tell a directory left by a crashed run from anything else.
17
+ //
18
+ // ONE SESSION, A KEEPER AND ONE WINDOW PER VIEWER. A control client hears `%output` only for the
19
+ // panes of the session it is attached to, and a session ends with its last window: so the session
20
+ // is made with a keeper window (never typed to; see THE KEEPER), and each viewer is a window of it, sized by
21
+ // `default-size` before it is made (the viewer starts at its size) and by `resize-window` after,
22
+ // which sets that window's own `window-size` to manual. The control client never sizes a window
23
+ // (it never says its size: tmux ignores the size of a control client that has not sent
24
+ // `refresh-client -C`). The GLOBAL `window-size` is left alone: set to manual, tmux 3.3a to 3.5a
25
+ // crash in the next `new-window` (resize.c clients_calculate_size reads the window's manual size
26
+ // before the window exists), as CI's tmux 3.4 did.
27
+ //
28
+ // THE START, ONE PROCESS. The control client starts the server itself: `tmux -C new-session …`,
29
+ // with `set-option -s exit-unattached on` and the other options in the SAME command list. The
30
+ // order matters. `exit-unattached` set before any client is attached ends the server at once (the
31
+ // spike's trap), so it must come after the attach; but a server started on its own (`new-session
32
+ // -d`) and attached afterwards lives, keeper and all, with nothing to end it, if the TUI is killed
33
+ // between the two (round 1 of the review). Here the client that starts the server is attached by
34
+ // that very `new-session`, the list then turns `exit-unattached` on, and that client is a process of
35
+ // its own (its own process group): a TUI killed at any moment of the start closes the client's
36
+ // stdin, the client ends, and the server ends with its last client. Verified with tmux 3.7c: the
37
+ // starter's stdin closed 0, 5 and 30 ms after the spawn left no server. The first blocks the
38
+ // client prints are the answers to that list, one per command.
39
+ //
40
+ // THE KEEPER WATCHES THE TUI. The stdin EOF is not enough on its own. Found with tmux 3.7c: a
41
+ // control client whose reader has gone while the server still has output queued for it is never
42
+ // ended. tmux keeps the client until its output has drained, which it no longer can, and so never
43
+ // acts on the EOF; the client stays attached, `exit-unattached` never fires, and the server lives
44
+ // on, viewers and all. A TUI killed during the start (the server is writing the start's blocks)
45
+ // always hits it, and one killed while an agent prints often does. So the keeper window watches
46
+ // the TUI itself: the run's FIFO `<run dir>/alive`, whose write end the TUI holds for the run
47
+ // (O_CLOEXEC, in no child's stdio). The keeper (KEEPER_SCRIPT) opens the FIFO, reads it until no
48
+ // writer is left, and then kills the server (SIGKILL: a server ends only when its clients are gone,
49
+ // and the stuck one never is). THE ORDER: the TUI makes the FIFO and
50
+ // holds its write end BEFORE it starts the server, so a keeper that finds no writer always means
51
+ // "the TUI is gone", never "not yet". A TUI that is stopped (Ctrl+Z) still holds it: nothing is
52
+ // killed. A normal end sends `kill-server` itself first, which ends the keeper with its pane
53
+ // before the TUI lets go of the FIFO; a keeper that still woke would find its server gone, and do
54
+ // nothing.
55
+ //
56
+ // THE CAPTURE, OUT OF BAND. No pane's text ever enters the control client's stream. A capture is
57
+ // four commands, each its own line and so its own block: `capture-pane -e -N -b <buffer>` into the
58
+ // one paste buffer CAPTURE_BUFFER, `save-buffer` of it to `<run dir>/capture`, `delete-buffer`,
59
+ // and the cursor's `display`. They are four lines, not one list, because a command of a list that
60
+ // fails ends the list there: a pane gone between the send and the run would leave the buffer, and
61
+ // the blocks out of step with the commands waiting. The file is read only after its save's block
62
+ // has ended (tmux has written and closed it by then), by `fs.whole`, bounded (CAPTURE_MAX); a file
63
+ // missing, too large or not a regular file is a failed capture: no frame, and the next change
64
+ // tries again. The path is a word of a control line (controlWord), not an argv: in single quotes,
65
+ // with `#` doubled, since save-buffer expands formats in it (a `#(…)` would run a command). So
66
+ // every block that succeeds says nothing but tmux's own words, and only the cursor's says
67
+ // anything: a block that holds anything else ends the control client (`ask`'s `says`). That is
68
+ // now a fault of tmux, or a stream out of step, never an agent's doing. The file is the run's,
69
+ // 0700 directory and all; end() and the sweep remove it. Verified with tmux 3.4 and 3.7c: the file
70
+ // is what `capture-pane -p` prints, each line ending in "\n", and a path holding a space, `'`,
71
+ // `"`, `$HOME`, `#(…)`, `#{…}`, `~`, `;` or `\` lands where it says and runs nothing.
72
+ //
73
+ // WHAT STARTS A PROCESS, each with argv and no shell: the FIFO's `mkfifo` and `tmux -V` (once a
74
+ // run), the start of the server (the control client, spawned), the making of a window, the
75
+ // `kill-server` calls (before a new server, after a failed start, and end()'s), and the sweep's
76
+ // `list-sessions` (at most one for each run directory it looks at that holds a socket). A frame
77
+ // never does: every capture, key, resize and close goes through the control client, as a command
78
+ // of constant text and tmux's own ids.
79
+ //
80
+ // THE ARGV OF A COMMAND IS NOT TEXT TO TMUX, BUT FOR ONE RULE. Verified with tmux 3.7c: new-window
81
+ // passes its command's arguments to the program as they are (no format is expanded in them or in
82
+ // an `-e` value, nothing is re-parsed: `#{pane_id}`, `'`, `$HOME`, `$(…)`, spaces, a newline, `{`,
83
+ // a leading `-` all arrive intact), EXCEPT that tmux reads an argument that ENDS in `;` as the end
84
+ // of a command, so `x;` followed by `kill-server` would be a second command. `tmuxArgument` writes
85
+ // such an argument as `x\;`, which tmux reads back as `x;` (cmd-parse.y, the same since 3.0).
86
+ // Every argument that is not a constant of this file goes through it.
87
+ //
88
+ // THE END OF A VIEWER. The viewer is its pane's own process (VIEW_SCRIPT execs it), so the pane's
89
+ // hang-up reaches it at once as SIGHUP, and it cleans up after itself. A pane is never closed by
90
+ // its process's end: `remain-on-exit` is on, so tmux keeps a dead pane with its exit status, and
91
+ // the control client is subscribed (`refresh-client -B`, DEAD_SUBSCRIPTION) to every pane's
92
+ // `#{pane_dead} #{pane_dead_status} #{pane_dead_signal}`. tmux checks a subscription once a second,
93
+ // so a viewer's end is heard within a second: `1 <status> ` when it exited, `1 <signal>` when a
94
+ // signal ended it. The panel then kills the dead pane, which closes its window. A pane can be
95
+ // heard dead BEFORE tmux has its status: tmux marks it dead when its terminal hangs up (the
96
+ // process's files closed as it exits) and takes the status only when it reaps the process, a
97
+ // moment later (server_destroy_pane, then server_child_exited; 3.2 to 3.4 at least, and CI on 3.4
98
+ // heard the dead pane between the two). That line, `1 `, is not the end: the line with the status
99
+ // follows at the next check, and the panel waits for it, a bounded time: a viewer heard so is over
100
+ // without a status once STATUS_WAIT_MS have passed with no other line, its pane killed, so a
101
+ // status that never comes never leaves a terminal open that nothing will close (CI, tmux 3.4).
102
+ // tmux 3.2 has no `pane_dead_signal` (3.3 added it), so there a signal's end reads `1 ` for good,
103
+ // and the wait is the shorter DEAD_WAIT_MS. A pane-died hook cannot do it: tmux sends no
104
+ // notification for a command a hook runs. A pane the panel kills (close(), an open given up) is
105
+ // gone at once, with no status. Verified with tmux 3.4 and 3.7c; read in 3.2's source (control.c,
106
+ // format.c, server-fn.c), the same.
107
+ //
108
+ // THE END OF A RUN. A normal end calls end(): `kill-server`, then the socket, the capture's file,
109
+ // owner.json, the FIFO and the view files are removed (the run directory is the loop's to remove, after this). On a
110
+ // crash or a `kill -9` of the TUI nothing here runs, and nothing needs to: the FIFO loses its
111
+ // writer, the keeper kills the server (THE KEEPER), and the control client, whose server is gone,
112
+ // exits; the viewers' panes hang up, so each viewer gets SIGHUP and runs its own clean-up. What is
113
+ // left is the run directory with its socket, owner.json, FIFO and capture's file, which the next
114
+ // run's sweep removes.
115
+ import { execFile as nodeExecFile, execFileSync as nodeExecFileSync, spawn as nodeSpawn } from "node:child_process";
116
+ import { closeSync, constants as FS, fstatSync, lstatSync, openSync, readSync, readdirSync, rmdirSync, unlinkSync, writeSync } from "node:fs";
117
+ import { tmpdir as osTmpdir } from "node:os";
118
+ import { join } from "node:path";
119
+
120
+ /** How many terminals a run may hold open at once in the next version. This version opens one at
121
+ * a time: `open` refuses while one is open (E_PANEL_BUSY). */
122
+ export const MAX_TERMINALS = 4;
123
+ /** The most of a viewer's stderr that is kept, in bytes: the last ones. */
124
+ export const STDERR_KEPT = 4096;
125
+ /** The frame tick, in milliseconds: a capture follows the output that asked for it by one tick, so
126
+ * a burst of output is drawn once. The tick is not what bounds the rate: a fresh capture (open,
127
+ * resize, refresh, showing again) skips it, and what bounds them all is that at most one capture
128
+ * is in flight. */
129
+ export const FRAME_MS = 16;
130
+ /** The pane's command around the viewer, a CONSTANT: its stderr to the file named by E, then the
131
+ * viewer itself in the shell's place (`exec "$0" "$@"`: its argv, which follows this script as
132
+ * arguments and is never part of it). The viewer is the pane's own process, the leader of its
133
+ * terminal's session, so a pane that hangs up (killed, or its server gone) sends SIGHUP to the
134
+ * viewer at once, and the viewer cleans up after itself (the kernel's attach removes its session
135
+ * on the agents' server). With a shell between them, Linux sends that SIGHUP to the shell alone
136
+ * and to the viewer only once the shell has died: on a busy machine the viewer's tmux client had
137
+ * often ended by then (the agents' server drops a client whose terminal hung up), the attach had
138
+ * put its signal handlers away to clean up, and the late SIGHUP killed it part way, its session
139
+ * left (CI, tmux 3.4). Its exit status is the one tmux keeps for a dead pane (THE END OF A
140
+ * VIEWER). */
141
+ export const VIEW_SCRIPT = 'exec "$0" "$@" 2>"$E"';
142
+ /** The control client's subscription to every pane's end (THE END OF A VIEWER): its name, and
143
+ * the line tmux prints when a pane's value changes, `1 <status> ` for a dead pane whose process
144
+ * exited, `1 <signal>` for one a signal ended (a name, or its number), `1 ` for one whose status
145
+ * tmux does not have yet (or, on tmux 3.2, a signal's), `0 ` for a live one. */
146
+ const DEAD_SUBSCRIPTION = "oats-tui-dead";
147
+ const DEAD_LINE = /^%subscription-changed oats-tui-dead \$\d+ (@\d+) \d+ %\d+ : ([01]) (\d{0,3}) ([A-Z0-9]{0,12})$/;
148
+ /** On tmux 3.2 (no `pane_dead_signal`), how long a viewer heard dead with no status and no signal
149
+ * (`1 `) waits for the line that has one, in milliseconds: two checks of the subscription past
150
+ * the one that heard it. */
151
+ export const DEAD_WAIT_MS = 2500;
152
+ /** On tmux 3.3 and later, the same wait: ten checks of the subscription. tmux has the status a
153
+ * moment after the hang-up; a viewer that closed its terminal and lives on keeps it longer, and
154
+ * one whose status never comes is over without one when this has passed. */
155
+ export const STATUS_WAIT_MS = 10000;
156
+ /** The first tmux whose `pane_dead_signal` says which signal ended a pane. */
157
+ const DEAD_SIGNAL_TMUX = Object.freeze([3, 3]);
158
+ /** What a dead line with no status and no signal says of a viewer: its status is still to come. */
159
+ const PENDING = Symbol("pending");
160
+ /** The one session of the private server, and its keeper window's command. */
161
+ export const SESSION = "oats-tui";
162
+ /** The keeper's command (see THE KEEPER), a constant run as `sh -c KEEPER_SCRIPT oats-tui-keeper
163
+ * <fifo>`: the FIFO's path is argv, never text of the script. `3<>` opens the FIFO read-write,
164
+ * which never waits for a writer; `4<` then opens it for reading, at once since fd 3 is a writer;
165
+ * closing 3 leaves the TUI's as the only writer. `cat` returns when no writer is left (at once if
166
+ * the TUI is already gone). Then the keeper SIGKILLs its parent, the server: `kill-server` or
167
+ * SIGTERM would not do, since a server ends only once its clients are gone, and the client tmux
168
+ * cannot drain is never gone. The kernel then closes every pane's terminal, so each viewer gets
169
+ * SIGHUP and cleans up, and the control client, its server gone, exits. The parent is killed only
170
+ * while it is still the keeper's parent: a keeper whose server has ended is reparented, and its
171
+ * `$PPID` may name another process by then. The parent now is read from `/proc/$$/stat` where
172
+ * there is one (field 4, after the `) ` that ends the command name, which may itself hold one),
173
+ * else from `ps -o ppid= -p $$` (macOS). FAIL SAFE: when neither names it (no /proc, and no ps or
174
+ * one that refuses `-p`, as BusyBox's does), nothing is killed, and the server is left to the
175
+ * stdin EOF alone (docs/tui.md says what that can leave). `read` and `kill` are the shell's own:
176
+ * a PATH without them does not matter. All of it quietly. */
177
+ export const KEEPER_SCRIPT = 'exec 3<>"$1" 4<"$1" 3>&-; cat <&4 >/dev/null; exec >/dev/null 2>&1; p=; if [ -r /proc/$$/stat ]; then read -r s </proc/$$/stat; set -- ${s##*) }; p=$2; else set -- $(ps -o ppid= -p $$); p=$1; fi; [ -n "$p" ] && [ "$p" -eq "$PPID" ] && kill -KILL "$PPID"';
178
+ /** The command list the control client starts the server with (see THE START above): the session
179
+ * with its keeper, attached; `exit-unattached` at once after it; then every option. `unbind-key
180
+ * -a` empties the prefix table only: the root table (mouse bindings by default) and the
181
+ * copy-mode tables are emptied by name. No key typed into a pane is read through a table anyway
182
+ * (send-keys without -K writes to the pane), and no pane ever enters a mode: this leaves the
183
+ * server nothing to do with a key but type it. -> [[command…]…] */
184
+ export const startCommands = ({ alive }) => [
185
+ ["new-session", "-s", SESSION, "-x", "80", "-y", "24", "/bin/sh", "-c", KEEPER_SCRIPT, "oats-tui-keeper", tmuxArgument(alive)],
186
+ ["set-option", "-s", "exit-unattached", "on"],
187
+ ["set-option", "-s", "escape-time", "0"],
188
+ ["set-option", "-g", "status", "off"],
189
+ ["set-option", "-g", "prefix", "None"],
190
+ ["set-option", "-g", "prefix2", "None"],
191
+ ["set-option", "-gw", "remain-on-exit", "on"],
192
+ // Nothing drawn over a dead pane (tmux 3.3 and later; -q: 3.2 has no such option).
193
+ ["set-option", "-gwq", "remain-on-exit-format", ""],
194
+ ["refresh-client", "-B", `${DEAD_SUBSCRIPTION}:%*:#{pane_dead} #{pane_dead_status} #{pane_dead_signal}`],
195
+ ["unbind-key", "-a"],
196
+ ["unbind-key", "-a", "-T", "root"],
197
+ ["unbind-key", "-a", "-T", "copy-mode"],
198
+ ["unbind-key", "-a", "-T", "copy-mode-vi"],
199
+ ];
200
+ /** The most of what a control client that did not start printed on stderr that is kept. */
201
+ const DETAIL_KEPT = 400;
202
+ /** The names this module makes in the run directory, and the pattern of a view file. */
203
+ const SOCKET_NAME = "tmux", OWNER_NAME = "owner.json", OWNER_TOOL = "oats-tui", ALIVE_NAME = "alive";
204
+ /** The capture's file in the run directory, and the one paste buffer it passes through (see THE
205
+ * CAPTURE). */
206
+ const CAPTURE_NAME = "capture", CAPTURE_BUFFER = "oats-tui-capture";
207
+ /** The most bytes a capture's file may hold: a larger one is a failed capture. A pane of 500 by
208
+ * 200 cells with a change of style at every cell fits. */
209
+ const CAPTURE_MAX = 8 * 1024 * 1024;
210
+ /** What a command of the control client answers when it succeeds (see THE CAPTURE): nothing, or
211
+ * for the cursor's `display`, its one line. */
212
+ const SAYS_NOTHING = (lines) => lines.length === 0;
213
+ const CURSOR_LINE = /^(\d+) (\d+) ([01])$/;
214
+ const SAYS_CURSOR = (lines) => lines.length === 1 && CURSOR_LINE.test(lines[0]);
215
+ const VIEW_FILE = /^[1-9][0-9]*\.view\.(err|status)$/;
216
+ /** The oldest tmux this module knows to have every command it uses (`refresh-client -f`). */
217
+ const MIN_TMUX = Object.freeze([3, 2]);
218
+ /** The limits of a call that starts or opens something; of the `kill-server` on the way out (which
219
+ * runs in the exit path, synchronously); of the sweep's one look at a socket. */
220
+ const CALL_TIMEOUT_MS = 5000, END_TIMEOUT_MS = 1000, SWEEP_TIMEOUT_MS = 1000;
221
+ const CALL_MAX_BUFFER = 64 * 1024;
222
+ /** The most bytes of keys one `send-keys` carries. */
223
+ const INPUT_CHUNK = 256;
224
+ /** The sweep looks at no more run directories than this in one run. */
225
+ const SWEEP_MAX = 32;
226
+ /** The sweep looks at no more names `oats-tui-*` than this in one run (each costs an lstat). */
227
+ const SWEEP_SCAN_MAX = 1024;
228
+ /** Bracketed paste's two marks, as bytes (CSI 200 ~ and CSI 201 ~). Only term/screen.mjs and
229
+ * term/tty.mjs write an escape byte in a string; here the marks are numbers sent as hex. */
230
+ const PASTE_START = Buffer.from([0x1b, 0x5b, 0x32, 0x30, 0x30, 0x7e]);
231
+ const PASTE_END = Buffer.from([0x1b, 0x5b, 0x32, 0x30, 0x31, 0x7e]);
232
+
233
+ /** A step that must not stop the ones after it: a child, a stream or a file that is already gone. */
234
+ const quietly = (act) => { try { return act(); } catch { return undefined; } };
235
+ /** A refusal the caller can tell from another by its `code`. */
236
+ const refusal = (code, message, facts = {}) => Object.assign(new Error(message), { code, ...facts });
237
+ /** An argument tmux will hand on as it is (see the head of this file): a trailing `;` escaped. */
238
+ export const tmuxArgument = (text) => (text.endsWith(";") ? `${text.slice(0, -1)}\\;` : text);
239
+ /** A path as one word of a command line the control client sends (see THE CAPTURE): in single
240
+ * quotes, so tmux's parser takes every character as it is, with `'` written as `'"'"'`, and with
241
+ * `#` doubled, since save-buffer expands formats in its path (`##` is a `#`). A path holding a
242
+ * control character (a newline would end the line) cannot be one: -> null. */
243
+ export function controlWord(text) {
244
+ if (typeof text !== "string" || /[\x00-\x1f\x7f]/.test(text)) return null;
245
+ return `'${text.replaceAll("#", "##").replaceAll("'", `'"'"'`)}'`;
246
+ }
247
+ /** The environment of every tmux call: the one given, without TMUX and TMUX_PANE. */
248
+ function tmuxEnvironment(env) {
249
+ const { TMUX: _client, TMUX_PANE: _pane, ...rest } = env ?? {};
250
+ return rest;
251
+ }
252
+ /** A size tmux is told: a whole number of cells, at least 1; anything else is `fallback`. */
253
+ const cells = (n, fallback) => (Number.isInteger(n) && n > 0 ? Math.min(n, 10_000) : fallback);
254
+ /** Bytes as tmux's `send-keys -H` takes them: two hex digits each, separated by spaces. */
255
+ const hex = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(" ");
256
+ /** Whether a `tmux -V` answer names a version older than `[major, minor]`. A name without a
257
+ * version (a build from the repository says `master` or `next-…`) is taken as new enough. */
258
+ function older(answer, [least, leastMinor]) {
259
+ const found = /(\d+)\.(\d+)/.exec(String(answer));
260
+ if (!found) return false;
261
+ const [major, minor] = [Number(found[1]), Number(found[2])];
262
+ return major < least || (major === least && minor < leastMinor);
263
+ }
264
+
265
+ /** What this module does to the file system, each replaceable by a test.
266
+ * `make(path)` makes an empty file for one writer (0600, refused if it is there); `write(path,
267
+ * text)` makes one and writes `text`; `head(path, max)` and `tail(path, max)` read at most `max`
268
+ * bytes from its start or its end, as text (a tail that begins inside a UTF-8 character drops the
269
+ * bytes of that character); `whole(path, max)` reads a regular file of at most `max` bytes, as
270
+ * text, and answers null for a larger one or one that is not a regular file (a link is not
271
+ * followed, and a FIFO is not waited on); `lstat`, `list` (names in a directory), `unlink`, `rmdir`. */
272
+ export const PANEL_FS = Object.freeze({
273
+ make: (path) => closeSync(openSync(path, "wx", 0o600)),
274
+ write: (path, text) => {
275
+ const fd = openSync(path, "wx", 0o600);
276
+ try { writeSync(fd, text); } finally { quietly(() => closeSync(fd)); }
277
+ },
278
+ /** The write end of the FIFO at `path` (see THE KEEPER): opened through a reader of its own, so
279
+ * it never waits, and only once fstat says it is a FIFO. -> fd. Node opens every fd O_CLOEXEC. */
280
+ hold: (path) => {
281
+ const reader = openSync(path, FS.O_RDONLY | FS.O_NONBLOCK);
282
+ try {
283
+ if (!fstatSync(reader).isFIFO()) throw refusal("E_PANEL_START", "the panel's liveness mark is not a FIFO");
284
+ return openSync(path, FS.O_WRONLY);
285
+ } finally { quietly(() => closeSync(reader)); }
286
+ },
287
+ release: (fd) => closeSync(fd),
288
+ head: (path, max) => readPart(path, max, false),
289
+ tail: (path, max) => readPart(path, max, true),
290
+ whole: (path, max) => {
291
+ // O_NONBLOCK: a FIFO put there must not hold the TUI in its open; it is then no file, below.
292
+ const fd = openSync(path, FS.O_RDONLY | FS.O_NOFOLLOW | FS.O_NONBLOCK);
293
+ try {
294
+ const stat = fstatSync(fd);
295
+ if (!stat.isFile() || stat.size > max) return null;
296
+ const buffer = Buffer.alloc(stat.size);
297
+ let got = 0, n;
298
+ while (got < buffer.length && (n = readSync(fd, buffer, got, buffer.length - got, got)) > 0) got += n;
299
+ return buffer.subarray(0, got).toString("utf8");
300
+ } finally { quietly(() => closeSync(fd)); }
301
+ },
302
+ lstat: (path) => lstatSync(path),
303
+ list: (path) => readdirSync(path),
304
+ unlink: (path) => unlinkSync(path),
305
+ rmdir: (path) => rmdirSync(path),
306
+ });
307
+ function readPart(file, max, fromEnd) {
308
+ const fd = openSync(file, "r");
309
+ try {
310
+ const size = fstatSync(fd).size, start = fromEnd ? Math.max(0, size - max) : 0, room = Math.min(size - start, max);
311
+ const buffer = Buffer.alloc(room);
312
+ let got = 0;
313
+ while (got < room) { const n = readSync(fd, buffer, got, room - got, start + got); if (n === 0) break; got += n; }
314
+ let from = 0;
315
+ if (start > 0) while (from < Math.min(3, got) && (buffer[from] & 0xc0) === 0x80) from++;
316
+ return buffer.subarray(from, got).toString("utf8");
317
+ } finally { quietly(() => closeSync(fd)); }
318
+ }
319
+
320
+ /** The panel of a run: the private server, its control client and the viewer open in it.
321
+ * -> { open, close, resize, input, paste, setVisible, refresh, pause, resume, end, get current }
322
+ *
323
+ * Options:
324
+ * dir() the run's private directory: called at the first open, and expected to answer
325
+ * the same path every time (the caller makes it once and remembers it). This
326
+ * module never makes it and never removes it.
327
+ * capture(text, { cols, rows }) REQUIRED: the caller's cell builder, handed what
328
+ * `capture-pane -e -N` captured (its lines joined by "\n") and the pane's size;
329
+ * what it answers is handed on as `screen`.
330
+ * onScreen({ id, screen, cursor: { x, y, visible } }) a capture of the open viewer.
331
+ * onClosed({ id, status, stderr, asked }) a viewer ended: `status` its exit status as tmux
332
+ * kept it for its dead pane (null when there is none: a signal ended the viewer,
333
+ * its pane was killed, or its server went away), `stderr` the last STDERR_KEPT
334
+ * bytes it wrote to its file, as text, `asked`
335
+ * true when close() ended it. Called once per viewer, never for one still open
336
+ * at end(), and never before its open() has resolved.
337
+ * env the environment tmux is given (TMUX and TMUX_PANE removed); default process.env.
338
+ * tmux the program; default "tmux" on PATH.
339
+ * spawn, execFile, execFileSync, fs (see PANEL_FS), timers ({ setTimeout, clearTimeout }: the
340
+ * frame tick and a dead viewer's wait for its status, STATUS_WAIT_MS or
341
+ * DEAD_WAIT_MS, the only timers of this module), clock (an ISO time, for
342
+ * owner.json), pid (the TUI's, for owner.json): for tests.
343
+ * trace(text) told, when given, each notification of a viewer's end the control client printed
344
+ * (the dead-pane subscription's lines, a window's end, the client's own end) and
345
+ * what the panel made of it: tmux's ids and numbers and this module's words only,
346
+ * never a pane's text. For diagnosing an end in a test; default none.
347
+ * A callback that throws does not break the panel: what it threw is thrown again in a microtask,
348
+ * where the run hears it as any uncaught error.
349
+ *
350
+ * open({ argv, cols, rows }) -> Promise<{ id }>: start the viewer `argv` ([node, bin, ...args],
351
+ * the kernel's `oats session attach …`) in a new window of cols x rows. `id` is tmux's window id.
352
+ * The first open starts the server; so does the first after the server went away. Rejected with
353
+ * a coded Error: E_PANEL_BUSY (a viewer is open, or an open is under way: the caller closes it
354
+ * first, and may open the next as soon as close() has returned),
355
+ * E_PANEL_TMUX (no tmux, or one older than 3.2), E_PANEL_START (the server or its control
356
+ * client did not start; `detail` holds what tmux said, untrusted text), E_PANEL_OPEN (the
357
+ * window was not made; `detail` likewise, or a bad argv), E_PANEL_ENDED (after end()).
358
+ * close(): end the open viewer (`kill-pane`: its terminal hangs up, the viewer gets SIGHUP and
359
+ * cleans up after itself). THE SLOT IS FREE WHEN IT RETURNS: the next open may follow at once,
360
+ * and the closed viewer is reported by onClosed with `asked: true` when its window has ended.
361
+ * Asked while an open is under way, that open still answers its `{ id }`, and its window is
362
+ * killed as soon as it exists (reported likewise). With no viewer and no open, nothing.
363
+ * resize(cols, rows): the window's new size, then a fresh capture.
364
+ * input(bytes): bytes (a Buffer, or a string as UTF-8) typed into the viewer, in order. With no
365
+ * viewer window yet (an open under way) or none at all, they are dropped.
366
+ * paste(text): `text` as a bracketed paste (any end mark inside it removed); the agent's own
367
+ * server decides whether its program sees the marks (the viewer is a tmux client).
368
+ * setVisible(on): hidden, no capture runs and output only marks the screen stale; shown again,
369
+ * one fresh capture. refresh(): one fresh capture now (after `fg`, Ctrl+L).
370
+ * pause() / resume(): around a suspend of the TUI: tmux stops sending the pane's output (a
371
+ * stopped TUI does not read its pipe), then sends it again, and a fresh capture follows.
372
+ * end(): leave, synchronously: kill the server, end the control client, remove the socket,
373
+ * owner.json and the view files. Idempotent.
374
+ * current: the id of the open viewer, or null.
375
+ * No method but open() throws or rejects: a server that went away makes each of them do nothing. */
376
+ export function createPanel({ dir, capture, onScreen = () => {}, onClosed = () => {}, env = process.env, tmux = "tmux",
377
+ spawn = nodeSpawn, execFile = nodeExecFile, execFileSync = nodeExecFileSync, fs: givenFs = {}, timers = { setTimeout, clearTimeout },
378
+ clock = () => new Date().toISOString(), pid = process.pid, trace = null } = {}) {
379
+ if (typeof dir !== "function") throw new TypeError("createPanel needs dir(): the run's private directory");
380
+ if (typeof capture !== "function") throw new TypeError("createPanel needs capture(text, { cols, rows }): the cell builder");
381
+ const fs = { ...PANEL_FS, ...givenFs };
382
+
383
+ /** The run directory and the socket in it, once known; whether owner.json was written, tmux's
384
+ * version checked, and a server ever started in this run. */
385
+ let runDir = null, socket = null, ownerWritten = false, checked = false, everStarted = false;
386
+ /** Whether this tmux says which signal ended a pane (DEAD_SIGNAL_TMUX), known once checked. */
387
+ let signals = true;
388
+ /** The capture's file, and that path as a word of a control line (see THE CAPTURE). */
389
+ let capturePath = null, captureWord = null;
390
+ /** The write end of `<run dir>/alive`, held for the run once made (see THE KEEPER), or null. */
391
+ let aliveFd = null;
392
+ /** The server now: { child, replies (the FIFO of commands waiting for their block), block (the
393
+ * block being read), startLeft (the blocks of the start list still to come), attached, gone,
394
+ * onAttach, stderr }, or null. A start under way is `starting` (its promise). */
395
+ let server = null, starting = null;
396
+ /** THE SLOT: the viewer open now ({ id, pane, cols, rows, files, asked, over, status }), or the open
397
+ * under way that will be it (`opening`: { closeAsked, files }), or neither. close() frees it at
398
+ * once: the viewer it closed waits in `closing` (window id -> viewer) for its window's end, and
399
+ * an open it gave up goes on to kill its window as soon as it exists. Every open under way, the
400
+ * given-up ones included, is in `openings`.
401
+ * `closedSeen`: the window ids whose end was heard while an open was under way. A viewer that
402
+ * exits at once can end before new-window has answered with its id; ids are never reused by a
403
+ * server, and the set is emptied when no open is under way, and at every new server.
404
+ * `diedSeen`: the same for a pane heard dead (window id -> its status, null, or PENDING). */
405
+ let viewer = null, opening = null;
406
+ const closing = new Map(), openings = new Set(), closedSeen = new Set(), diedSeen = new Map();
407
+ /** The frames: the screen is stale (`dirty`), a tick is armed (`tick`), a capture is in flight. */
408
+ let dirty = false, tick = null, capturing = false, visible = true, paused = false;
409
+ let ended = false, files = 0;
410
+
411
+ /** A callback of the caller's, called so that what it throws cannot break the panel. */
412
+ function tell(act) {
413
+ try { act(); } catch (error) { queueMicrotask(() => { throw error; }); }
414
+ }
415
+ /** One line of the trace, when the caller asked for one. */
416
+ const traced = (text) => { if (trace) tell(() => trace(text)); };
417
+ /** The flags every call starts with. */
418
+ const base = () => ["-u", "-f", "/dev/null", "-S", socket];
419
+
420
+ /** One tmux call that starts or opens something: argv, no shell, a time limit.
421
+ * -> Promise<{ stdout }>, rejected with execFile's error (its `stderr` added). */
422
+ function call(args) {
423
+ return new Promise((resolve, reject) => {
424
+ try {
425
+ execFile(tmux, [...base(), ...args], { env: tmuxEnvironment(env), timeout: CALL_TIMEOUT_MS, maxBuffer: CALL_MAX_BUFFER, encoding: "utf8", shell: false, windowsHide: true },
426
+ (error, stdout, stderr) => (error ? reject(Object.assign(error, { stderr: String(stderr ?? "") })) : resolve({ stdout: String(stdout ?? "") })));
427
+ } catch (error) { reject(error); }
428
+ });
429
+ }
430
+ /** What tmux said, kept for the caller to show (through its own display filter): untrusted text. */
431
+ const detail = (error) => String(error?.stderr || error?.message || "").slice(0, 400);
432
+
433
+ // THE CONTROL CLIENT ---------------------------------------------------------------------------
434
+
435
+ /** Ask the server one command through the control client: -> Promise<{ ok, lines }>, never
436
+ * rejected. `ok` is false for an `%error` block, and for every command still waiting when the
437
+ * server goes away. `command` is constant text with tmux's ids and numbers in it, and the
438
+ * capture's path as controlWord writes it: never a newline, never the caller's text. `says`:
439
+ * what its block may hold when it succeeds (SAYS_NOTHING unless named); a block that holds
440
+ * anything else ends the control client (see THE CAPTURE). */
441
+ function ask(command, says = SAYS_NOTHING) {
442
+ const s = server;
443
+ if (s === null || s.gone) return Promise.resolve({ ok: false, lines: [] });
444
+ return new Promise((resolve) => {
445
+ s.replies.push({ resolve, says });
446
+ try { s.child.stdin.write(`${command}\n`); } catch { lost(s); }
447
+ });
448
+ }
449
+
450
+ /** One line the control client printed. Inside a block every line is the block's, until the
451
+ * `%end` or `%error` line that repeats its `%begin`'s time, number and flags EXACTLY (tmux
452
+ * prints the same time and number on both lines of a block). No pane's text is ever in a block
453
+ * (THE CAPTURE); the exact end is kept all the same. Outside a block a line is a notification
454
+ * (tmux never prints one inside a block; `%output` carries a pane's text escaped, one line). The FIRST blocks, one per command of
455
+ * the start list, answer the start itself; every later one answers the oldest command waiting. */
456
+ function heard(s, line) {
457
+ if (s.block) {
458
+ if (line === `%end ${s.block.head}` || line === `%error ${s.block.head}`) {
459
+ const { lines, start } = s.block, ok = line.startsWith("%end ");
460
+ s.block = null;
461
+ // A command of the list that fails ends the list there: tmux runs none after it, so the
462
+ // start is answered at once.
463
+ if (start && !ok) s.startError = lines.join("\n").slice(0, DETAIL_KEPT);
464
+ // Fail closed here too: no command of the start list says anything when it succeeds.
465
+ if (start && ok && !SAYS_NOTHING(lines)) {
466
+ s.startError = "tmux answered the start with words its commands never say";
467
+ s.startLeft = 0;
468
+ return attached(s, false);
469
+ }
470
+ if (start) return ok && s.startLeft > 0 ? undefined : attached(s, ok);
471
+ const waiting = s.replies.shift();
472
+ // Fail closed: no pane's text is ever in a block (THE CAPTURE), so a block that answers a
473
+ // command with words that command does not say is tmux's fault, or a stream out of step.
474
+ // The control client is ended, and nothing more it prints is read.
475
+ if (waiting && ok && !waiting.says(lines)) { waiting.resolve({ ok: false, lines: [] }); return void lost(s); }
476
+ return void waiting?.resolve({ ok, lines });
477
+ }
478
+ return void s.block.lines.push(line);
479
+ }
480
+ if (line.startsWith("%begin ")) {
481
+ s.block = { head: line.slice("%begin ".length), lines: [], start: s.startLeft > 0 };
482
+ if (s.startLeft > 0) s.startLeft -= 1;
483
+ return;
484
+ }
485
+ const [kind, first] = line.split(" ", 2);
486
+ if (kind === "%output" || kind === "%extended-output") { if (viewer && first === viewer.pane) stale(); }
487
+ else if (kind === "%layout-change") { if (viewer && first === viewer.id) stale(); }
488
+ else if (kind === "%window-close" || kind === "%unlinked-window-close") { traced(line); windowClosed(first); }
489
+ else if (kind === "%exit") { traced(line); lost(s); }
490
+ else if (kind === "%subscription-changed") {
491
+ const dead = DEAD_LINE.exec(line);
492
+ if (first === DEAD_SUBSCRIPTION) traced(dead ? line : `${DEAD_SUBSCRIPTION}: a line not of its shape`);
493
+ if (dead && dead[2] === "1") paneDied(dead[1], dead[3] !== "" ? Number(dead[3]) : dead[4] !== "" ? null : PENDING);
494
+ }
495
+ }
496
+
497
+ /** The start's blocks are over, or one failed: the start waits for this (see `ensureServer`). */
498
+ function attached(s, ok) {
499
+ const waiting = s.onAttach;
500
+ s.onAttach = null;
501
+ if (ok) s.attached = true;
502
+ waiting?.(ok);
503
+ }
504
+
505
+ /** The control client is gone (`%exit`, its pipe closed, it did not start): the server with it,
506
+ * as far as this run is concerned. Every command waiting is answered as failed, the open viewer
507
+ * is closed with no status, and the next open starts a new server. */
508
+ function lost(s) {
509
+ if (s.gone) return;
510
+ s.gone = true;
511
+ if (server === s) server = null;
512
+ for (const { resolve } of s.replies.splice(0)) resolve({ ok: false, lines: [] });
513
+ if (s.onAttach) attached(s, false);
514
+ // stderr is left to end with the process: a start that failed reads what tmux said on it.
515
+ for (const stream of [s.child.stdin, s.child.stdout]) quietly(() => stream?.destroy());
516
+ quietly(() => s.child.kill("SIGTERM"));
517
+ quietly(() => s.child.unref());
518
+ stopFrames();
519
+ if (viewer) finish(viewer, { lost: true });
520
+ for (const v of [...closing.values()]) finish(v, { lost: true });
521
+ }
522
+
523
+ /** Start the server through the control client, with startCommands as its list, and wait for
524
+ * the list's blocks (see THE START). -> { s, started: Promise<boolean> }: false when it did not
525
+ * start; what tmux said is in `s.startError` (the failed block's lines) or `s.stderr` (the
526
+ * client's own, when it ended without a block). */
527
+ function connect() {
528
+ const commands = startCommands({ alive: join(runDir, ALIVE_NAME) });
529
+ const list = commands.flatMap((command, i) => (i === 0 ? command : [";", ...command]));
530
+ const child = spawn(tmux, [...base(), "-C", ...list], { env: tmuxEnvironment(env), stdio: ["pipe", "pipe", "pipe"], detached: true, windowsHide: true });
531
+ // `detached`: a process group of its own. The TUI's Ctrl+Z sends SIGTSTP to the TUI's group,
532
+ // and a stopped control client would stop the panel with it.
533
+ const s = { child, replies: [], block: null, startLeft: commands.length, attached: false, gone: false, onAttach: null, startError: "", stderr: "", closed: null };
534
+ s.closed = new Promise((resolve) => child.once("close", resolve));
535
+ let pending = Buffer.alloc(0);
536
+ child.stdin?.on("error", () => lost(s));
537
+ child.stdout?.on("error", () => lost(s));
538
+ child.stderr?.on("error", () => {});
539
+ child.stderr?.on("data", (chunk) => { if (s.stderr.length < DETAIL_KEPT) s.stderr = (s.stderr + chunk.toString("utf8")).slice(0, DETAIL_KEPT); });
540
+ // Bytes, split on "\n"; each line decoded as UTF-8 by itself, so a character is never cut.
541
+ child.stdout?.on("data", (chunk) => {
542
+ pending = pending.length ? Buffer.concat([pending, chunk]) : chunk;
543
+ let at;
544
+ while (!s.gone && (at = pending.indexOf(0x0a)) >= 0) {
545
+ const line = pending.subarray(0, at).toString("utf8");
546
+ pending = pending.subarray(at + 1);
547
+ heard(s, line);
548
+ }
549
+ });
550
+ child.once("close", () => lost(s));
551
+ child.on("error", () => lost(s));
552
+ server = s;
553
+ const started = new Promise((resolve) => {
554
+ s.onAttach = (ok) => resolve(ok);
555
+ if (s.gone) attached(s, false);
556
+ });
557
+ return { s, started };
558
+ }
559
+
560
+ /** The server, started if there is none: -> Promise<server>, rejected with a coded Error.
561
+ * In order: the run directory and owner.json (once a run), tmux's version (once a run), a
562
+ * server left from an earlier start of this run killed (its control client ended without it),
563
+ * the FIFO the keeper watches made and its write end held (once a run, and always before any
564
+ * server: see THE KEEPER), and the server started by the control client with every option in
565
+ * its ONE command list (see THE START: why `exit-unattached` comes right after the session). */
566
+ function ensureServer() {
567
+ if (server && !server.gone && server.attached) return Promise.resolve(server);
568
+ if (starting) return starting;
569
+ starting = (async () => {
570
+ try {
571
+ if (runDir === null) {
572
+ try { runDir = dir(); } catch (error) { throw refusal("E_PANEL_START", "the panel has no private directory", { detail: detail(error) }); }
573
+ socket = join(runDir, SOCKET_NAME);
574
+ capturePath = join(runDir, CAPTURE_NAME);
575
+ captureWord = controlWord(capturePath);
576
+ }
577
+ if (captureWord === null) throw refusal("E_PANEL_START", "the panel's private directory cannot be named to tmux: its path holds a control character");
578
+ if (!ownerWritten) {
579
+ try { fs.write(join(runDir, OWNER_NAME), `${JSON.stringify({ tool: OWNER_TOOL, pid, started: clock() })}\n`); } catch (error) { throw refusal("E_PANEL_START", "the panel could not mark its directory", { detail: detail(error) }); }
580
+ ownerWritten = true;
581
+ }
582
+ if (!checked) {
583
+ let answer;
584
+ try { answer = await call(["-V"]); } catch (error) {
585
+ throw error?.code === "ENOENT" ? refusal("E_PANEL_TMUX", "tmux is not installed") : refusal("E_PANEL_TMUX", "tmux did not say its version", { detail: detail(error) });
586
+ }
587
+ if (older(answer.stdout, MIN_TMUX)) throw refusal("E_PANEL_TMUX", "the panel needs tmux 3.2 or later", { detail: answer.stdout.trim().slice(0, 80) });
588
+ signals = !older(answer.stdout, DEAD_SIGNAL_TMUX);
589
+ checked = true;
590
+ }
591
+ if (ended) throw refusal("E_PANEL_ENDED", "the panel has ended");
592
+ if (everStarted) await call(["kill-server"]).catch(() => {});
593
+ if (aliveFd === null) {
594
+ const alive = join(runDir, ALIVE_NAME);
595
+ try {
596
+ await new Promise((resolve, reject) => execFile("mkfifo", ["-m", "600", alive], { timeout: CALL_TIMEOUT_MS, shell: false, windowsHide: true }, (error) => (error ? reject(error) : resolve())));
597
+ aliveFd = fs.hold(alive);
598
+ } catch (error) {
599
+ quietly(() => fs.unlink(alive));
600
+ throw refusal("E_PANEL_START", "the panel could not make the mark its server watches", { detail: detail(error) });
601
+ }
602
+ if (ended) { quietly(() => fs.release(aliveFd)); aliveFd = null; quietly(() => fs.unlink(alive)); throw refusal("E_PANEL_ENDED", "the panel has ended"); }
603
+ }
604
+ everStarted = true;
605
+ closedSeen.clear();
606
+ diedSeen.clear();
607
+ // A start that fails part way (a command of the list answered with an error, the client
608
+ // gone) may leave a server whose options are not all set: its client is ended and the
609
+ // server killed, not left to linger.
610
+ let s = null, ok = false;
611
+ try {
612
+ const start = connect();
613
+ s = start.s;
614
+ ok = await start.started;
615
+ } catch { ok = false; }
616
+ if (!ok) {
617
+ if (s) {
618
+ lost(s);
619
+ // What tmux said comes on stderr, which may still be on its way when stdout said
620
+ // `%exit`: the process's end is waited for (it was sent SIGTERM), bounded. The bound's
621
+ // timer is kept referenced, and cleared once the end wins: the child is unref'd by
622
+ // lost(), and an unref'd timer would leave nothing holding the event loop, so a
623
+ // close that never comes would end the process with this await still pending.
624
+ let bound = null;
625
+ await Promise.race([s.closed, new Promise((resolve) => { bound = setTimeout(resolve, END_TIMEOUT_MS); })]);
626
+ clearTimeout(bound);
627
+ }
628
+ const said = (s?.startError.trim() || s?.stderr.trim()) ?? "";
629
+ if (ended) throw refusal("E_PANEL_ENDED", "the panel has ended");
630
+ await call(["kill-server"]).catch(() => {});
631
+ throw refusal("E_PANEL_START", "the panel's tmux server did not start", said ? { detail: said } : {});
632
+ }
633
+ if (ended) throw refusal("E_PANEL_ENDED", "the panel has ended");
634
+ return s;
635
+ } finally { starting = null; }
636
+ })();
637
+ return starting;
638
+ }
639
+
640
+ // FRAMES ---------------------------------------------------------------------------------------
641
+
642
+ /** Whether a capture may run now. */
643
+ const showing = () => viewer !== null && !viewer.over && visible && !paused && !ended;
644
+ /** Arm the tick, unless one is armed or a capture is in flight (it arms one when it is over). */
645
+ function arm() {
646
+ if (!showing() || tick !== null || capturing) return;
647
+ tick = timers.setTimeout(() => { tick = null; startCapture(); }, FRAME_MS);
648
+ }
649
+ function stopFrames() {
650
+ if (tick !== null) { quietly(() => timers.clearTimeout(tick)); tick = null; }
651
+ }
652
+ /** A notification said the screen changed: stale, and a capture one tick later. NO TIMER RUNS
653
+ * BUT THIS ONE: nothing is ever captured unless tmux said something changed, or the caller asked. */
654
+ function stale() { dirty = true; arm(); }
655
+ /** A capture now (or right after the one in flight), whatever the tick. */
656
+ function fresh() {
657
+ dirty = true;
658
+ if (!showing() || capturing) return;
659
+ stopFrames();
660
+ startCapture();
661
+ }
662
+ /** A capture whose promise nobody awaits: it never rejects. */
663
+ const startCapture = () => { captureNow().catch(() => { capturing = false; }); };
664
+ /** One capture: the pane's cells into the capture's file, and its cursor, asked through the
665
+ * control client in one go (see THE CAPTURE). At most one in flight; what was marked stale
666
+ * meanwhile arms the next tick after it. A capture that fails (the pane gone, the file missing,
667
+ * too large or not a file) draws nothing, and the next change tries again. */
668
+ async function captureNow() {
669
+ const v = viewer;
670
+ if (!showing() || capturing) return;
671
+ capturing = true;
672
+ dirty = false;
673
+ const [taken, saved, , cursor] = await Promise.all([
674
+ ask(`capture-pane -e -N -b ${CAPTURE_BUFFER} -t ${v.pane}`),
675
+ ask(`save-buffer -b ${CAPTURE_BUFFER} ${captureWord}`),
676
+ ask(`delete-buffer -b ${CAPTURE_BUFFER}`),
677
+ ask(`display -p -t ${v.pane} '#{cursor_x} #{cursor_y} #{cursor_flag}'`, SAYS_CURSOR),
678
+ ]);
679
+ capturing = false;
680
+ if (ended || viewer !== v || v.over) return;
681
+ // Hidden or paused while it was in flight: not drawn; the capture that showing again asks for is.
682
+ if (!showing()) { dirty = true; return; }
683
+ const held = taken.ok && saved.ok && cursor.ok ? quietly(() => fs.whole(capturePath, CAPTURE_MAX)) : null;
684
+ if (typeof held === "string") {
685
+ const at = CURSOR_LINE.exec(cursor.lines[0]);
686
+ const where = { x: Number(at[1]), y: Number(at[2]), visible: at[3] === "1" };
687
+ // The file holds each line with its "\n"; the cell builder takes them joined by "\n".
688
+ const text = held.endsWith("\n") ? held.slice(0, -1) : held;
689
+ tell(() => onScreen({ id: v.id, screen: capture(text, { cols: v.cols, rows: v.rows }), cursor: where }));
690
+ }
691
+ if (dirty) arm();
692
+ }
693
+
694
+ // VIEWERS --------------------------------------------------------------------------------------
695
+
696
+ /** A viewer's pane is dead (THE END OF A VIEWER): the viewer is over with the status tmux kept,
697
+ * and its pane is killed, which closes its window. PENDING (dead, and tmux has no status yet) is
698
+ * not the end: the viewer waits for the line with its status (`waitStatus`). A pane not yet
699
+ * known (an open under way) is remembered with what was heard; any other is not a viewer's (the
700
+ * keeper's, one already over). */
701
+ function paneDied(id, status) {
702
+ const v = viewer?.id === id ? viewer : closing.get(id);
703
+ if (v && status === PENDING) return waitStatus(v);
704
+ if (v) { v.status = status; ask(`kill-pane -t ${v.pane}`); return finish(v, {}); }
705
+ if (openings.size > 0 && !(status === PENDING && diedSeen.has(id))) diedSeen.set(id, status);
706
+ }
707
+ /** A viewer heard dead with no status: it stays open until the line with its status or its
708
+ * signal, a close, or its server's end, and at most STATUS_WAIT_MS (DEAD_WAIT_MS on tmux 3.2,
709
+ * which says a signal's end no other way): then it is over without a status, and its pane is
710
+ * killed. Armed once. */
711
+ function waitStatus(v) {
712
+ if (v.over || v.waiting !== null) return;
713
+ const ms = signals ? STATUS_WAIT_MS : DEAD_WAIT_MS;
714
+ traced(`${v.id} dead, waiting ${ms} ms for its status`);
715
+ v.waiting = timers.setTimeout(() => {
716
+ v.waiting = null;
717
+ if (ended || v.over) return;
718
+ traced(`${v.id} no status after ${ms} ms`);
719
+ v.status = null;
720
+ if (server && !server.gone) ask(`kill-pane -t ${v.pane}`);
721
+ finish(v, {});
722
+ }, ms);
723
+ }
724
+ /** A window ended: the open viewer's, one closing, or (an open under way) one to remember. */
725
+ function windowClosed(id) {
726
+ if (viewer && viewer.id === id) return finish(viewer, {});
727
+ if (closing.has(id)) return finish(closing.get(id), {});
728
+ if (openings.size > 0) closedSeen.add(id);
729
+ }
730
+ /** A viewer is over: read what it left, remove its file, and say so. Its status is what tmux kept
731
+ * of its dead pane (`v.status`, set when that was heard: whichever way it is finished then, the
732
+ * status stands), null when it has none (a signal ended it, its pane was killed first, or
733
+ * `lost`: its server went away). */
734
+ function finish(v, { lost: gone = false }) {
735
+ const status = v.status;
736
+ if (v.over) return;
737
+ v.over = true;
738
+ unwait(v);
739
+ closing.delete(v.id);
740
+ if (viewer === v) free();
741
+ const stderr = quietly(() => fs.tail(v.files.err, STDERR_KEPT)) ?? "";
742
+ traced(`${v.id} over, status ${gone ? null : status}${gone ? ", its server gone" : ""}${v.asked ? ", closed" : ""}`);
743
+ forget(v.files);
744
+ if (!ended) tell(() => onClosed({ id: v.id, status: gone ? null : status, stderr, asked: v.asked }));
745
+ }
746
+ /** A viewer's wait for its status (waitStatus), put away. */
747
+ function unwait(v) { if (v.waiting !== null) { quietly(() => timers.clearTimeout(v.waiting)); v.waiting = null; } }
748
+ /** The slot is free: no viewer, no frame to come. */
749
+ function free() { viewer = null; stopFrames(); dirty = false; }
750
+ const forget = (made) => { for (const path of [made?.err, made?.status]) if (path) quietly(() => fs.unlink(path)); };
751
+ /** End a viewer the caller closed (or gave up while it opened): its pane killed through the
752
+ * control client, and its end awaited in `closing`. With no server, it is over now. */
753
+ function kill(v) {
754
+ v.asked = true;
755
+ closing.set(v.id, v);
756
+ if (!server || server.gone) return finish(v, { lost: true });
757
+ ask(`kill-pane -t ${v.pane}`);
758
+ }
759
+
760
+ /** See createPanel. */
761
+ function open({ argv, cols, rows } = {}) {
762
+ if (ended) return Promise.reject(refusal("E_PANEL_ENDED", "the panel has ended"));
763
+ if (viewer || opening) return Promise.reject(refusal("E_PANEL_BUSY", "a terminal is open in the panel"));
764
+ if (!Array.isArray(argv) || argv.length === 0 || !argv.every((arg) => typeof arg === "string" && !arg.includes("\0"))) return Promise.reject(refusal("E_PANEL_OPEN", "the viewer's argv is not a list of strings"));
765
+ const size = { cols: cells(cols, 80), rows: cells(rows, 24) };
766
+ const mine = opening = { closeAsked: false, files: null };
767
+ openings.add(mine);
768
+ /** This open is no longer under way. */
769
+ const settle = () => {
770
+ openings.delete(mine);
771
+ if (opening === mine) opening = null;
772
+ if (openings.size === 0) { closedSeen.clear(); diedSeen.clear(); }
773
+ };
774
+ return (async () => {
775
+ try {
776
+ const s = await ensureServer();
777
+ if (ended) throw refusal("E_PANEL_ENDED", "the panel has ended");
778
+ // The stderr file exists, 0600, BEFORE the window: the pane's shell only truncates it.
779
+ const n = ++files, made = { err: join(runDir, `${n}.view.err`) };
780
+ try { fs.make(made.err); mine.files = made; } catch (error) { throw refusal("E_PANEL_OPEN", "the panel could not make the viewer's file", { detail: detail(error) }); }
781
+ let answer;
782
+ try {
783
+ answer = await call(["set-option", "-t", SESSION, "default-size", `${size.cols}x${size.rows}`,
784
+ ";", "new-window", "-d", "-P", "-F", "#{window_id} #{pane_id}", "-t", `${SESSION}:`,
785
+ "-e", tmuxArgument(`E=${made.err}`),
786
+ "/bin/sh", "-c", VIEW_SCRIPT, ...argv.map(tmuxArgument)]);
787
+ } catch (error) { throw refusal("E_PANEL_OPEN", "the panel could not open a window", { detail: detail(error) }); }
788
+ const ids = /^(@\d+) (%\d+)\s*$/.exec(answer.stdout);
789
+ if (!ids) {
790
+ // A window was made, but not named as asked: one it names at all is killed now, not left
791
+ // until end(). One it does not name stays until end()'s kill-server.
792
+ const window = /(?:^|\s)(@\d+)(?=\s|$)/.exec(answer.stdout);
793
+ if (window) ask(`kill-window -t ${window[1]}`);
794
+ throw refusal("E_PANEL_OPEN", "tmux did not name the window it opened");
795
+ }
796
+ if (ended) throw refusal("E_PANEL_ENDED", "the panel has ended");
797
+ const v = { id: ids[1], pane: ids[2], ...size, files: made, asked: false, over: false, status: null, waiting: null };
798
+ mine.files = null; // the viewer's now: finish() removes them
799
+ // Heard dead with no status yet: opened as any other, and waiting for the line with it.
800
+ const pending = diedSeen.get(v.id) === PENDING;
801
+ const died = diedSeen.has(v.id) && !pending, status = died ? diedSeen.get(v.id) : null;
802
+ const already = closedSeen.has(v.id) || died, gone = server !== s;
803
+ traced(`${v.id} ${v.pane} opened${closedSeen.has(v.id) ? ", its window already closed" : died ? `, already dead with status ${status}` : pending ? ", already dead with no status yet" : ""}${gone ? ", its server gone" : ""}`);
804
+ settle();
805
+ if (already || gone) {
806
+ // Over before its id was known (it exited at once, or the server went away meanwhile):
807
+ // said after open() has answered, so the caller knows the id onClosed names. A pane that
808
+ // died is killed, as paneDied does.
809
+ v.asked = mine.closeAsked;
810
+ if (!mine.closeAsked) viewer = v;
811
+ else closing.set(v.id, v);
812
+ // The status is the viewer's from here: the window's end that answers this kill-pane can
813
+ // come before the finish below, and finishes it with this status (CI, under load).
814
+ v.status = status;
815
+ if (died && !gone) ask(`kill-pane -t ${v.pane}`);
816
+ setImmediate(() => finish(v, { lost: gone && !already }));
817
+ } else if (mine.closeAsked) kill(v); // given up while it opened: killed at once
818
+ else {
819
+ viewer = v;
820
+ ask(`resize-window -t ${v.id} -x ${v.cols} -y ${v.rows}`);
821
+ fresh();
822
+ if (pending) waitStatus(v);
823
+ }
824
+ return { id: v.id };
825
+ } catch (error) {
826
+ settle();
827
+ forget(mine.files);
828
+ throw error;
829
+ }
830
+ })();
831
+ }
832
+
833
+ /** See createPanel. The slot is free when this returns. */
834
+ function close() {
835
+ if (ended) return;
836
+ if (viewer) {
837
+ const v = viewer;
838
+ free();
839
+ return kill(v);
840
+ }
841
+ if (opening) { opening.closeAsked = true; opening = null; }
842
+ }
843
+
844
+ function resize(cols, rows) {
845
+ const v = viewer;
846
+ if (ended || !v || v.over) return;
847
+ v.cols = cells(cols, v.cols);
848
+ v.rows = cells(rows, v.rows);
849
+ ask(`resize-window -t ${v.id} -x ${v.cols} -y ${v.rows}`);
850
+ fresh();
851
+ }
852
+
853
+ /** Bytes to the open pane, in commands of at most INPUT_CHUNK bytes, in order (one pipe, and
854
+ * tmux runs a client's commands in the order they came); their answers are consumed. */
855
+ function send(bytes) {
856
+ const v = viewer;
857
+ if (ended || !v || v.over || !server || bytes.length === 0) return;
858
+ for (let at = 0; at < bytes.length; at += INPUT_CHUNK) ask(`send-keys -t ${v.pane} -H ${hex(bytes.subarray(at, at + INPUT_CHUNK))}`);
859
+ }
860
+ function input(bytes) {
861
+ try { send(Buffer.isBuffer(bytes) ? bytes : typeof bytes === "string" ? Buffer.from(bytes, "utf8") : Buffer.from(bytes ?? [])); } catch { /* nothing to type */ }
862
+ }
863
+ /** A bracketed paste. An end mark inside the text would end the paste early and let the rest act
864
+ * as keys: it is removed, and so is one that a removal makes by joining what was around it. One
865
+ * pass: the bytes are copied, and whenever what was copied ends in an end mark, it is taken back. */
866
+ function paste(text) {
867
+ try {
868
+ const body = Buffer.from(String(text ?? ""), "utf8"), kept = Buffer.alloc(body.length), mark = PASTE_END.length;
869
+ let n = 0;
870
+ for (const byte of body) {
871
+ kept[n++] = byte;
872
+ if (n >= mark && byte === PASTE_END[mark - 1] && kept.subarray(n - mark, n).equals(PASTE_END)) n -= mark;
873
+ }
874
+ send(Buffer.concat([PASTE_START, kept.subarray(0, n), PASTE_END]));
875
+ } catch { /* nothing to paste */ }
876
+ }
877
+
878
+ function setVisible(on) {
879
+ if (ended) return;
880
+ visible = on === true;
881
+ if (!visible) stopFrames();
882
+ else fresh();
883
+ }
884
+ function refresh() { if (!ended) fresh(); }
885
+
886
+ /** `refresh-client -f no-output` (tmux 3.2): tmux keeps no pane output for this client while the
887
+ * TUI is stopped, so the pipe does not fill and tmux does not drop a client that falls behind.
888
+ * The other notifications (a window's end) still come, and are few. `!no-output` turns it off. */
889
+ function pause() {
890
+ if (ended || paused) return;
891
+ paused = true;
892
+ stopFrames();
893
+ ask("refresh-client -f no-output");
894
+ }
895
+ function resume() {
896
+ if (ended || !paused) return;
897
+ paused = false;
898
+ ask("refresh-client -f '!no-output'");
899
+ fresh();
900
+ }
901
+
902
+ /** Kill this run's server, synchronously and bounded: it runs in the exit path. An end() that
903
+ * comes while the start is under way ends the starting client too (below), and a server it
904
+ * started ends with it (see THE START): nothing of a start is left to linger. */
905
+ function endServer() {
906
+ if (socket === null || !everStarted) return;
907
+ quietly(() => execFileSync(tmux, [...base(), "kill-server"], { env: tmuxEnvironment(env), timeout: END_TIMEOUT_MS, stdio: "ignore", windowsHide: true }));
908
+ }
909
+ function end() {
910
+ if (ended) return;
911
+ ended = true;
912
+ stopFrames();
913
+ endServer();
914
+ const s = server;
915
+ server = null;
916
+ if (s) {
917
+ s.gone = true;
918
+ for (const { resolve } of s.replies.splice(0)) resolve({ ok: false, lines: [] });
919
+ if (s.onAttach) attached(s, false);
920
+ quietly(() => s.child.stdin?.end());
921
+ for (const stream of [s.child.stdin, s.child.stdout, s.child.stderr]) quietly(() => stream?.destroy());
922
+ quietly(() => s.child.kill("SIGTERM"));
923
+ quietly(() => s.child.unref());
924
+ }
925
+ // Nothing more is said: the run is leaving. Every viewer's files go, and so do those of an open
926
+ // under way (which then rejects with E_PANEL_ENDED and makes nothing more).
927
+ for (const v of [viewer, ...closing.values()]) if (v) { v.over = true; unwait(v); forget(v.files); }
928
+ viewer = null;
929
+ closing.clear();
930
+ for (const under of openings) forget(under.files);
931
+ if (runDir !== null) {
932
+ quietly(() => fs.unlink(socket));
933
+ quietly(() => fs.unlink(capturePath));
934
+ if (ownerWritten) quietly(() => fs.unlink(join(runDir, OWNER_NAME)));
935
+ // After kill-server: the keeper this wakes meets no server (see THE KEEPER).
936
+ if (aliveFd !== null) { quietly(() => fs.release(aliveFd)); aliveFd = null; quietly(() => fs.unlink(join(runDir, ALIVE_NAME))); }
937
+ }
938
+ }
939
+
940
+ return { open, close, resize, input, paste, setVisible, refresh, pause, resume, end, get current() { return viewer && !viewer.over ? viewer.id : null; } };
941
+ }
942
+
943
+ /** What the sweep reads and removes, each replaceable by a test (see PANEL_FS). */
944
+ const SWEEP_FS = PANEL_FS;
945
+
946
+ /** The sweep, once at the start of a run, before anything else: remove what a run that crashed
947
+ * left of its panel in the OS temp dir. -> { removed: [dir…] } (the directories emptied of the
948
+ * panel's files; each is then rmdir'd, which fails quietly when anything else is left in it, such
949
+ * as a reader's change output). Synchronous, bounded, never throws.
950
+ * It looks ONLY at entries of `tmpdir` named `oats-tui-*` that are directories (lstat: a link is
951
+ * not one), owned by `uid`, of mode exactly 0700, holding an owner.json (a regular file, owned by
952
+ * `uid`, small) whose `tool` is "oats-tui" and whose `pid` is a whole number. Such a directory is
953
+ * a dead run's when BOTH:
954
+ * its pid is not alive (signal 0 answers ESRCH; EPERM, or any other answer, counts as alive:
955
+ * the pid may have been taken by another process, and then the directory is left), and
956
+ * its socket refuses (`tmux -S <it> list-sessions` exits nonzero; no socket file counts as
957
+ * refusing; a socket that answers, a call that times out or cannot run, an entry `tmux` that
958
+ * is not a socket, all leave the directory alone).
959
+ * Then it removes the socket, owner.json, the FIFO `alive` (when it is one), the capture's file
960
+ * `capture` (when it is a regular file) and the panel's view files (`<n>.view.err`,
961
+ * `<n>.view.status`, by that exact pattern only), and rmdirs the directory.
962
+ * It NEVER sends `kill-server` or a signal (signal 0 only asks), and never looks at a socket
963
+ * outside such a directory, the user's default server, or the kernel's. At most `max` candidates
964
+ * (SWEEP_MAX) are looked at in one run, each tmux call with a short time limit: a candidate is a
965
+ * directory whose owner.json names this tool, so a look-alike without one, or a directory a
966
+ * sweep already emptied of its owner.json but could not remove (it holds another file), never
967
+ * uses up the limit. At most SWEEP_SCAN_MAX names are looked at. `removed` names each directory
968
+ * the sweep emptied, one it could not then remove too.
969
+ * `kill` is process.kill's signature, `execFileSync` child_process's, `fs` as PANEL_FS: for tests. */
970
+ export function sweep({ tmpdir = osTmpdir(), uid = process.getuid?.(), pid = process.pid, env = process.env, tmux = "tmux",
971
+ fs: givenFs = {}, execFileSync = nodeExecFileSync, kill = (target, signal) => process.kill(target, signal), max = SWEEP_MAX } = {}) {
972
+ const removed = [];
973
+ try {
974
+ if (!Number.isInteger(uid)) return { removed };
975
+ const fs = { ...SWEEP_FS, ...givenFs };
976
+ const names = fs.list(tmpdir).filter((name) => typeof name === "string" && name.startsWith("oats-tui-")).sort().slice(0, SWEEP_SCAN_MAX);
977
+ let candidates = 0;
978
+ for (const name of names) {
979
+ if (candidates >= max) break;
980
+ const at = join(tmpdir, name);
981
+ if (quietly(() => deadRun(at)) === true) {
982
+ quietly(() => fs.unlink(join(at, SOCKET_NAME)));
983
+ for (const entry of quietly(() => fs.list(at)) ?? []) {
984
+ if (VIEW_FILE.test(entry) && quietly(() => fs.lstat(join(at, entry)).isFile())) quietly(() => fs.unlink(join(at, entry)));
985
+ }
986
+ if (quietly(() => fs.lstat(join(at, ALIVE_NAME)).isFIFO())) quietly(() => fs.unlink(join(at, ALIVE_NAME)));
987
+ if (quietly(() => fs.lstat(join(at, CAPTURE_NAME)).isFile())) quietly(() => fs.unlink(join(at, CAPTURE_NAME)));
988
+ quietly(() => fs.unlink(join(at, OWNER_NAME)));
989
+ quietly(() => fs.rmdir(at));
990
+ removed.push(at);
991
+ }
992
+ }
993
+ /** Whether `at` is a directory a dead run of this tool left (see above). Throws for anything
994
+ * that cannot be read: the caller leaves that directory. */
995
+ function deadRun(at) {
996
+ const stat = fs.lstat(at);
997
+ if (!stat.isDirectory() || stat.uid !== uid || (stat.mode & 0o777) !== 0o700) return false;
998
+ const ownerPath = join(at, OWNER_NAME), owner = fs.lstat(ownerPath);
999
+ if (!owner.isFile() || owner.uid !== uid || owner.size > 4096) return false;
1000
+ const record = JSON.parse(fs.head(ownerPath, 4096));
1001
+ if (record?.tool !== OWNER_TOOL || !Number.isInteger(record.pid) || record.pid <= 0) return false;
1002
+ candidates += 1;
1003
+ if (record.pid === pid || alive(record.pid)) return false;
1004
+ const sock = quietly(() => fs.lstat(join(at, SOCKET_NAME)));
1005
+ if (sock === undefined) return true; // no socket: nothing can answer
1006
+ if (!sock.isSocket()) return false;
1007
+ try {
1008
+ execFileSync(tmux, ["-u", "-f", "/dev/null", "-S", join(at, SOCKET_NAME), "list-sessions"], { env: tmuxEnvironment(env), timeout: SWEEP_TIMEOUT_MS, stdio: "ignore", windowsHide: true });
1009
+ return false; // it answers: a server lives there
1010
+ } catch (error) {
1011
+ return Number.isInteger(error?.status) && error.status !== 0; // it refused; a time limit or a tmux that cannot run says nothing
1012
+ }
1013
+ }
1014
+ function alive(target) {
1015
+ try { kill(target, 0); return true; } catch (error) { return error?.code !== "ESRCH"; }
1016
+ }
1017
+ } catch { /* a temp dir that cannot be listed: nothing to sweep */ }
1018
+ return { removed };
1019
+ }