@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
@@ -1,6 +1,13 @@
1
- // Style values, by name. A style is the terminal's own sixteen colours and four attributes
2
- // (docs/tui.md): no background, no 256-colour or RGB value, so the user's theme stays the theme.
3
- // This module holds SGR parameters as numbers; the screen is what writes the sequence.
1
+ // Style values, of two kinds. This module holds SGR parameters as numbers; the screen is what writes
2
+ // the sequence, and a value only this module made is one it writes.
3
+ //
4
+ // The TUI's own: the terminal's sixteen colours and four attributes (docs/tui.md), `style()`. No
5
+ // background, no 256-colour or RGB value, so the user's theme stays the theme.
6
+ // The agent's own: what an agent's terminal set, read from its capture by term/capture.mjs and
7
+ // drawn only in the terminal panel, `agentStyle()`. Those colours are the agent's, not the TUI's,
8
+ // so this kind has a background and 256-colour and RGB values. It is still a closed set built
9
+ // from a state of named fields: nothing of the agent's sequence text is kept, only the numbers
10
+ // this module writes back for it.
4
11
 
5
12
  const FOREGROUND = Object.freeze({
6
13
  black: 30, red: 31, green: 32, yellow: 33, blue: 34, magenta: 35, cyan: 36, white: 37,
@@ -23,7 +30,7 @@ export function style(spec = {}) {
23
30
  const id = [...attributes, spec.fg ?? ""].join(",");
24
31
  if (!made.has(id)) {
25
32
  const value = Object.freeze({ fg: spec.fg ?? null, ...Object.fromEntries(ATTRIBUTES.map((name) => [name, attributes.includes(name)])) });
26
- parameters.set(value, Object.freeze({ attributes: attributes.map((name) => ATTRIBUTE[name]), colour: spec.fg === undefined ? [] : [FOREGROUND[spec.fg]] }));
33
+ parameters.set(value, Object.freeze({ attributes: attributes.map((name) => ATTRIBUTE[name]), colour: spec.fg === undefined ? [] : [FOREGROUND[spec.fg]], background: false }));
27
34
  made.set(id, value);
28
35
  }
29
36
  return made.get(id);
@@ -31,13 +38,78 @@ export function style(spec = {}) {
31
38
  export const PLAIN = style();
32
39
  export const isStyle = (value) => parameters.has(value);
33
40
 
34
- /** The SGR parameters of a style, attributes first. Without `color` the colour is dropped and the
35
- * attributes stay. */
41
+ // ── The agent's own ──────────────────────────────────────────────────────────────────────────────
42
+
43
+ /** The attributes an agent's style keeps, in the order their parameters are written. Each is on
44
+ * or off: an underline's kind (curly, dotted) is not kept, so 4:3 is written back as 4. */
45
+ const AGENT_ATTRIBUTE = Object.freeze({ bold: 1, dim: 2, italic: 3, underline: 4, blink: 5, reverse: 7, invisible: 8, strikethrough: 9 });
46
+ export const AGENT_ATTRIBUTES = Object.freeze(Object.keys(AGENT_ATTRIBUTE));
47
+ const AGENT_KEYS = Object.freeze([...AGENT_ATTRIBUTES, "fg", "bg"]);
48
+ /** The agent's styles are interned apart and only so many are kept, the least recently made or
49
+ * asked for going first: an agent that writes a gradient in RGB names a new style per cell, and
50
+ * what the TUI keeps must not grow with what an agent writes. One that was let go and is asked
51
+ * for again is a new value, which costs the screen one rewrite of the rows it is in. */
52
+ export const AGENT_STYLES_KEPT = 4096;
53
+ const agentMade = new Map();
54
+
55
+ const isByte = (n) => Number.isInteger(n) && n >= 0 && n < 256;
56
+ /** A colour of an agent's style, checked and frozen: `null` (the terminal's default), `{ ansi: n }`
57
+ * one of the sixteen (0 to 15), `{ index: n }` one of 256, or `{ rgb: [r, g, b] }`. Anything else
58
+ * is refused: the parameters written for it are built from these numbers alone. */
59
+ function agentColour(colour) {
60
+ if (colour === undefined || colour === null) return null;
61
+ const keys = typeof colour === "object" ? Object.keys(colour) : [];
62
+ if (keys.length === 1 && keys[0] === "ansi" && Number.isInteger(colour.ansi) && colour.ansi >= 0 && colour.ansi <= 15) return Object.freeze({ ansi: colour.ansi });
63
+ if (keys.length === 1 && keys[0] === "index" && isByte(colour.index)) return Object.freeze({ index: colour.index });
64
+ if (keys.length === 1 && keys[0] === "rgb" && Array.isArray(colour.rgb) && colour.rgb.length === 3 && colour.rgb.every(isByte)) return Object.freeze({ rgb: Object.freeze([...colour.rgb]) });
65
+ throw new TypeError("an agent style's colour is null, { ansi: 0-15 }, { index: 0-255 } or { rgb: [r, g, b] } of 0-255");
66
+ }
67
+ const colourId = (colour) => (colour === null ? "" : "ansi" in colour ? `a${colour.ansi}` : "index" in colour ? `i${colour.index}` : `r${colour.rgb.join(".")}`);
68
+ /** The parameters of a colour: `base` is 30 for the foreground and 40 for the background, so the
69
+ * sixteen are base..base+7 and base+60..base+67, and the extended forms base+8 then 5;n or 2;r;g;b. */
70
+ function colourParameters(colour, base) {
71
+ if (colour === null) return [];
72
+ if ("ansi" in colour) return [colour.ansi < 8 ? base + colour.ansi : base + 60 + colour.ansi - 8];
73
+ if ("index" in colour) return [base + 8, 5, colour.index];
74
+ return [base + 8, 2, ...colour.rgb];
75
+ }
76
+
77
+ /** The style an agent's terminal set: `agentStyle({ bold: true, fg: { index: 208 }, bg: { rgb: [1, 2, 3] } })`,
78
+ * each attribute of AGENT_ATTRIBUTES true or absent, `fg` and `bg` a colour or null. Interned as
79
+ * style() is, so an equal state is the same value (of the AGENT_STYLES_KEPT last asked for). The state with nothing set is PLAIN, which the
80
+ * two kinds share: an agent's blank cell and the TUI's are one cell to the screen. */
81
+ export function agentStyle(state = {}) {
82
+ if (state === null || typeof state !== "object") throw new TypeError("an agent style is made from a state object");
83
+ for (const key of Object.keys(state)) if (!AGENT_KEYS.includes(key)) throw new TypeError(`unknown agent style key ${key}`);
84
+ const attributes = AGENT_ATTRIBUTES.filter((name) => state[name] === true);
85
+ const fg = agentColour(state.fg), bg = agentColour(state.bg);
86
+ if (attributes.length === 0 && fg === null && bg === null) return PLAIN;
87
+ const id = `${attributes.join(",")}|${colourId(fg)}|${colourId(bg)}`;
88
+ let value = agentMade.get(id);
89
+ if (value) { agentMade.delete(id); agentMade.set(id, value); return value; }
90
+ value = Object.freeze({ agent: true, ...Object.fromEntries(AGENT_ATTRIBUTES.map((name) => [name, attributes.includes(name)])), fg, bg });
91
+ parameters.set(value, Object.freeze({ attributes: attributes.map((name) => AGENT_ATTRIBUTE[name]), colour: [...colourParameters(fg, 30), ...colourParameters(bg, 40)], background: bg !== null }));
92
+ agentMade.set(id, value);
93
+ if (agentMade.size > AGENT_STYLES_KEPT) agentMade.delete(agentMade.keys().next().value);
94
+ return value;
95
+ }
96
+
97
+ /** The SGR parameters of a style, attributes first and then the colours, foreground before
98
+ * background. Without `color` every colour is dropped and the attributes stay. */
36
99
  export function sgr(value, { color = true } = {}) {
37
100
  const own = parameters.get(value);
38
101
  if (!own) throw new TypeError("not a style value: make one with style()");
39
102
  return color ? [...own.attributes, ...own.colour] : [...own.attributes];
40
103
  }
41
104
 
105
+ /** Whether a blank cell in this style shows: a space draws nothing of its own, so it shows only by
106
+ * what the style paints across the whole cell, an underline, reverse video, a strikethrough or a
107
+ * background. Without `color` a background is not written, so a space with only one shows nothing. */
108
+ export function blankShows(value, { color = true } = {}) {
109
+ const own = parameters.get(value);
110
+ if (!own) throw new TypeError("not a style value: make one with style()");
111
+ return value.underline || value.reverse || value.strikethrough === true || (color && own.background);
112
+ }
113
+
42
114
  /** NO_COLOR (no-color.org): set and not empty switches colour off. */
43
115
  export const colorEnabled = (env) => !(typeof env.NO_COLOR === "string" && env.NO_COLOR !== "");
@@ -1,10 +1,17 @@
1
1
  // Safe text: the only thing the screen draws. A terminal acts on what is written to it, so the
2
2
  // screen takes strings from nobody: it takes values only this module can make (docs/tui.md,
3
- // awebai/oats#855 section 3.9). There are two ways in, and no third:
4
- // lit(string) the TUI's own words;
5
- // shown(value) text the TUI did not write, through the shared display filter.
3
+ // awebai/oats#855 section 3.9). There are three ways in, and no fourth:
4
+ // lit(string) the TUI's own words;
5
+ // shown(value) text the TUI did not write, through the shared display filter;
6
+ // cellText(string) the cells of an agent's terminal, which term/capture.mjs has already
7
+ // filtered, drawn only in the terminal panel.
6
8
  // A safe value is for display only: nothing compares it, selects by it or passes it to a command.
7
9
  //
10
+ // The third exists because the display filter is right for a line and wrong for a terminal's
11
+ // cells: it folds runs of spaces and trims, and a terminal's spaces are its layout. cellText()
12
+ // keeps the spaces and refuses, rather than filters: every character it would have to take out
13
+ // is one capture.mjs drops first, so a refusal is a bug there, never text to repair here.
14
+ //
8
15
  // Every view meets this: the filter folds a run of spaces into one and trims both ends, so lit()
9
16
  // refuses a string with two spaces together or a space at an end. A row is therefore spans placed
10
17
  // by column (`{ col, text, style }`), never one padded string: the gap between two spans is the
@@ -99,11 +106,24 @@ export function shownLines(value, width, max, { ascii = false } = {}) {
99
106
  return rows.map((row) => make(joined(row)));
100
107
  }
101
108
 
109
+ /** What cellText() refuses: the C0 controls (ESC among them), DEL, the C1 controls, and the bidi
110
+ * controls (U+061C, U+200E, U+200F, U+202A to U+202E, U+2066 to U+2069), which would let a row
111
+ * reorder what is drawn in it. */
112
+ const NOT_A_CELL = /[\x00-\x1f\x7f-\x9f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/;
113
+
114
+ /** The text of an agent's terminal cells, as term/capture.mjs read them from a capture: spaces
115
+ * kept as they are. It throws on any character capture.mjs drops, and its message never repeats
116
+ * the string. For capture.mjs alone; any other text goes through lit() or shown(). */
117
+ export function cellText(string) {
118
+ if (typeof string !== "string" || NOT_A_CELL.test(string)) throw new TypeError("cellText() takes an agent's cells as term/capture.mjs filtered them: no control or bidi character");
119
+ return make(string);
120
+ }
121
+
102
122
  export const isSafeText = (value) => TEXT.has(value);
103
123
 
104
124
  /** The string of a safe value, for the screen (and the tests that read a row). A raw string and a
105
125
  * forged object are refused. */
106
126
  export function textOf(value) {
107
- if (!TEXT.has(value)) throw new TypeError("the screen draws safe text only: lit() for the TUI's own words, shown() for anything else");
127
+ if (!TEXT.has(value)) throw new TypeError("the screen draws safe text only: lit() for the TUI's own words, shown() for anything else, cellText() for an agent's cells");
108
128
  return TEXT.get(value);
109
129
  }
@@ -0,0 +1,213 @@
1
+ // What is typed through to an agent's terminal (docs/tui.md, "Open an agent's terminal"). While
2
+ // a terminal has the focus the TUI reads no keys: the bytes the outer terminal sends go to the
3
+ // agent exactly as they came, and the scanner here looks for two things only, the back key's own
4
+ // bytes (which take the focus back to the list) and a bracketed paste (which goes to the agent as
5
+ // a paste, so a back key inside it is pasted, not taken). Pure: no IO; the clock is injected.
6
+ //
7
+ // The back key is tui.json's `open.detachKey`. Its grammar is THE TUI'S OWN: the keys it can take
8
+ // back from a terminal and name in the footer. It began as the kernel's `--detach-key` grammar
9
+ // (lib/session-viewer.mjs) and keeps its set and its spelling, so a tui.json written for PR 4 means
10
+ // the same key; it is not tied to the kernel's, which never sees this key any more.
11
+ import { ESC_TIMEOUT_MS, PASTE_LIMIT, PASTE_PAUSE_MS } from "./keys.mjs";
12
+
13
+ /** The keys that can be the back key: Control with a letter other than h, i and m (Backspace on
14
+ * some terminals, Tab, Enter), or one of \ ] ^ _; Meta with a lowercase letter or a digit; or F1
15
+ * to F12 with at most one of C-, M-, S-. Outside it, among others: Escape, and the ESC + C1
16
+ * introducers a terminal's reply can begin with. */
17
+ export const BACK_KEY = /^(?:C-[a-gj-ln-z\\\]^_]|M-[a-z0-9]|(?:[CMS]-)?F(?:[1-9]|1[0-2]))$/;
18
+ /** The grammar as the refusal of a key outside it says it. */
19
+ export const BACK_KEY_RULE = "C-<a letter except h, i and m, or one of \\ ] ^ _>, M-<a lowercase letter or digit>, or F1 to F12 with at most one of C-, M-, S-";
20
+ export const isBackKey = (value) => typeof value === "string" && BACK_KEY.test(value);
21
+
22
+ const ESC = 0x1b;
23
+ /** An escape sequence as bytes: ESC, then the printable ASCII that follows it. Built from the
24
+ * number, as term/keys.mjs does: no module but the screen and the guard writes an ESC in a string. */
25
+ const escaped = (rest) => Uint8Array.of(ESC, ...Array.from(rest, (c) => c.charCodeAt(0)));
26
+ /** The xterm modifier parameter of S-, M- and C-. */
27
+ const MODIFIER = Object.freeze({ S: 2, M: 3, C: 5 });
28
+ /** The number of F5..F12 in `CSI <n> ~`, and of F1..F4 in the same form (the vt220 and rxvt one). */
29
+ const TILDE = Object.freeze({ 1: 11, 2: 12, 3: 13, 4: 14, 5: 15, 6: 17, 7: 18, 8: 19, 9: 20, 10: 21, 11: 23, 12: 24 });
30
+
31
+ /** The byte sequences a terminal sends for a back key, each as bytes: what the scanner takes as
32
+ * the key. A Control key is one byte; a Meta key is ESC and the character; a function key has
33
+ * each form the key parser (term/keys.mjs) reads for it: `SS3 P..S` and `CSI 1 ; m P..S` for F1 to
34
+ * F4, `CSI n ~` and `CSI n ; m ~` for all twelve, and the Linux console's `CSI [ A..E` for an
35
+ * unmodified F1 to F5. A value outside the grammar is refused. */
36
+ export function backKeySequences(key) {
37
+ if (!isBackKey(key)) throw new TypeError("not a back key");
38
+ if (key.startsWith("C-") && !key.startsWith("C-F")) return [Uint8Array.of(key.charCodeAt(2) & 0x1f)];
39
+ if (key.startsWith("M-") && !key.startsWith("M-F")) return [Uint8Array.of(ESC, key.charCodeAt(2))];
40
+ const [, mod, number] = /^(?:([CMS])-)?F(\d+)$/.exec(key);
41
+ const n = Number(number), m = mod ? MODIFIER[mod] : null, forms = [];
42
+ if (n <= 4) {
43
+ const final = "PQRS"[n - 1];
44
+ forms.push(m === null ? `O${final}` : `[1;${m}${final}`);
45
+ if (m !== null) forms.push(`O${m}${final}`);
46
+ }
47
+ forms.push(m === null ? `[${TILDE[n]}~` : `[${TILDE[n]};${m}~`);
48
+ if (m === null && n <= 5) forms.push(`[[${"ABCDE"[n - 1]}`);
49
+ return forms.map(escaped);
50
+ }
51
+
52
+ const PASTE_START = escaped("[200~");
53
+ const PASTE_END = escaped("[201~");
54
+ /** The first bytes of a paste's start marker that are held when a read ends on them: from `ESC [ 2`
55
+ * on. A lone ESC or `ESC [` is never held for the paste's sake (an agent's Esc must not wait):
56
+ * they go to the agent at once, and when the next read completes the marker (within
57
+ * PASTE_PAUSE_MS) the paste goes on to the agent RAW, as typed, its marks included, with no back
58
+ * key taken from it until its end marker (round 1 of the review: a split there must not let a
59
+ * back key inside a paste, or the keys after it, act). */
60
+ const PASTE_HELD_FROM = 3;
61
+
62
+ /** Whether `data` holds `seq` at `at`, whole. */
63
+ function at(data, from, seq) {
64
+ if (from + seq.length > data.length) return false;
65
+ for (let i = 0; i < seq.length; i++) if (data[from + i] !== seq[i]) return false;
66
+ return true;
67
+ }
68
+ /** Whether `data` from `from` to its end is the beginning of `seq`, and shorter than it. */
69
+ function begins(data, from, seq) {
70
+ const left = data.length - from;
71
+ if (left <= 0 || left >= seq.length) return false;
72
+ for (let i = 0; i < left; i++) if (data[from + i] !== seq[i]) return false;
73
+ return true;
74
+ }
75
+ const join = (a, b) => { if (a.length === 0) return b; const out = new Uint8Array(a.length + b.length); out.set(a); out.set(b, a.length); return out; };
76
+ const decoder = () => new TextDecoder("utf-8", { fatal: false });
77
+
78
+ /** A scanner of the bytes typed while a terminal has the focus. `feed(bytes)` answers events in
79
+ * order: `{ input: <bytes> }` (for the agent, as typed), `{ paste: <text> }` (a bracketed paste,
80
+ * unwrapped) and, at most once per feed and last, `{ back: true, rest: <bytes> }` (the back key:
81
+ * what came after it in the same read is no longer the agent's, and `rest` hands it on).
82
+ * A read is never held back from the agent but for a beginning of the back key's own bytes, or of
83
+ * a paste's start marker from its third byte: those wait for the next read, or until `expire()`
84
+ * past `timeoutAt()` (the key parser's Esc timeout) hands them on as input. A paste is held until
85
+ * its end marker; one that reaches PASTE_LIMIT is dropped whole, and one whose end has not come
86
+ * when a read arrives PASTE_PAUSE_MS after the one before is given to the agent as what it held,
87
+ * and that read is scanned anew, as the key parser abandons a stalled paste. */
88
+ export function createThrough({ sequences, now }) {
89
+ if (typeof now !== "function") throw new TypeError("createThrough needs an injected clock: { now: () => milliseconds }");
90
+ const keys = sequences.map((seq) => Uint8Array.from(seq));
91
+ let held = new Uint8Array(0), heldAt = 0;
92
+ /** The paste being read: its content so far (null when none; only the tail that may begin the
93
+ * end marker once it went past the limit), and whether it did. */
94
+ let paste = null, over = false, lastFeed = 0;
95
+ /** The last bytes handed on as input (at most a start marker less one), since the last event
96
+ * that was not input: by a read, or by expire() (round 2 of the review: bytes the Esc timeout
97
+ * handed on are as much the start of a paste as bytes a read did); how many first bytes of a
98
+ * paste's start marker they end with (0 to 5); and the paste passed on raw (see
99
+ * PASTE_HELD_FROM), with the last bytes it passed (`tail`, which may begin its end marker), or
100
+ * null. */
101
+ let sent = new Uint8Array(0), forwarded = 0, raw = null;
102
+
103
+ function endPaste(out, content) {
104
+ if (!over) out.push({ paste: decoder().decode(content) });
105
+ paste = null; over = false;
106
+ }
107
+ /** Inside a paste: content up to the end marker, which may arrive split at any byte (the
108
+ * content's tail is kept until it is known not to begin the marker). Answers what is left. */
109
+ function inPaste(out, data) {
110
+ const content = join(paste, data);
111
+ const scanFrom = Math.max(0, paste.length - (PASTE_END.length - 1));
112
+ for (let i = scanFrom; i < content.length; i++) {
113
+ if (content[i] === ESC && at(content, i, PASTE_END)) {
114
+ endPaste(out, content.subarray(0, i));
115
+ return content.subarray(i + PASTE_END.length);
116
+ }
117
+ }
118
+ if (content.length >= PASTE_LIMIT) { over = true; paste = Uint8Array.from(content.subarray(content.length - (PASTE_END.length - 1))); return new Uint8Array(0); }
119
+ paste = paste.length === 0 ? Uint8Array.from(content) : content; // never a view of the caller's read
120
+ return new Uint8Array(0);
121
+ }
122
+
123
+ /** A raw paste: every byte to the agent as it came, up to and with the end marker, which may be
124
+ * split across reads. Answers what is left after it, or nothing while it goes on. */
125
+ function inRaw(out, data) {
126
+ const seen = join(raw.tail, data);
127
+ for (let i = 0; i + PASTE_END.length <= seen.length; i++) {
128
+ if (seen[i] === ESC && at(seen, i, PASTE_END)) {
129
+ const end = i + PASTE_END.length - raw.tail.length;
130
+ if (end > 0) out.push({ input: data.subarray(0, end) });
131
+ raw = null;
132
+ return data.subarray(Math.max(0, end));
133
+ }
134
+ }
135
+ if (data.length) out.push({ input: data });
136
+ raw.tail = Uint8Array.from(seen.subarray(Math.max(0, seen.length - (PASTE_END.length - 1))));
137
+ return new Uint8Array(0);
138
+ }
139
+ /** Take note of the events handed out, and answer how many first bytes of a paste's start
140
+ * marker the input handed on now ends with: at any length, and across events and calls. */
141
+ function handedOn(out) {
142
+ for (const event of out) sent = event.input ? join(sent, event.input).slice(-(PASTE_START.length - 1)) : new Uint8Array(0);
143
+ if (held.length || paste !== null || raw !== null) return 0;
144
+ for (let k = Math.min(sent.length, PASTE_START.length - 1); k > 0; k--) if (at(sent, sent.length - k, PASTE_START.subarray(0, k))) return k;
145
+ return 0;
146
+ }
147
+
148
+ function scan(out, data) {
149
+ for (let i = 0; i < data.length; i++) {
150
+ const b = data[i];
151
+ if (b === ESC && at(data, i, PASTE_START)) {
152
+ if (i > 0) out.push({ input: data.subarray(0, i) });
153
+ paste = new Uint8Array(0); over = false;
154
+ const rest = inPaste(out, data.subarray(i + PASTE_START.length));
155
+ if (paste !== null) return; // the paste goes on in the next read
156
+ return scan(out, rest);
157
+ }
158
+ const key = keys.find((seq) => seq[0] === b && at(data, i, seq));
159
+ if (key) {
160
+ if (i > 0) out.push({ input: data.subarray(0, i) });
161
+ out.push({ back: true, rest: data.subarray(i + key.length) });
162
+ return;
163
+ }
164
+ // The read ends on what may be the beginning of the back key or of a paste: held.
165
+ if (keys.some((seq) => begins(data, i, seq)) || (data.length - i >= PASTE_HELD_FROM && begins(data, i, PASTE_START))) {
166
+ if (i > 0) out.push({ input: data.subarray(0, i) });
167
+ held = Uint8Array.from(data.subarray(i));
168
+ heldAt = now();
169
+ return;
170
+ }
171
+ }
172
+ if (data.length) out.push({ input: data });
173
+ }
174
+
175
+ return {
176
+ feed(bytes) {
177
+ if (!(bytes instanceof Uint8Array)) throw new TypeError("feed expects bytes (a Uint8Array)");
178
+ const out = [], t = now();
179
+ let data = bytes;
180
+ const soon = t - lastFeed < PASTE_PAUSE_MS;
181
+ if (paste !== null && !soon) endPaste(out, paste);
182
+ // A raw paste whose end has not come by the pause is over: what follows is scanned anew.
183
+ if (raw !== null && !soon) raw = null;
184
+ lastFeed = t;
185
+ if (paste !== null) {
186
+ data = inPaste(out, data);
187
+ if (paste !== null) return out;
188
+ }
189
+ if (held.length) { data = join(held, data); held = new Uint8Array(0); }
190
+ // The rest of a start marker whose first bytes the last read handed on: the paste is raw.
191
+ // A beginning of that rest waits for the next read, as a held key does.
192
+ if (raw === null && forwarded > 0 && soon) {
193
+ const rest = PASTE_START.subarray(forwarded);
194
+ if (at(data, 0, rest)) raw = { tail: new Uint8Array(0) };
195
+ else if (begins(data, 0, rest)) { held = Uint8Array.from(data); heldAt = t; return out; }
196
+ }
197
+ forwarded = 0;
198
+ if (raw !== null) data = inRaw(out, data);
199
+ if (raw === null && data.length) scan(out, data);
200
+ forwarded = handedOn(out);
201
+ // Events are handed out as copies: the caller may keep them past the next read.
202
+ return out.map((event) => (event.input ? { input: Uint8Array.from(event.input) } : event.rest ? { back: true, rest: Uint8Array.from(event.rest) } : event));
203
+ },
204
+ expire() {
205
+ if (!held.length || now() < heldAt + ESC_TIMEOUT_MS) return [];
206
+ const out = [{ input: held }];
207
+ held = new Uint8Array(0);
208
+ forwarded = handedOn(out);
209
+ return out;
210
+ },
211
+ timeoutAt() { return held.length ? heldAt + ESC_TIMEOUT_MS : null; },
212
+ };
213
+ }
@@ -4,8 +4,8 @@
4
4
  // no mouse or focus reporting, no keyboard protocol, no keypad or cursor-key mode, no title, no
5
5
  // clipboard, no bell, no query that expects a reply.
6
6
  //
7
- // Handing the terminal to someone else (the shell at a suspend; the kernel's viewer at a lend) is
8
- // leave() and enter(), and only that pair.
7
+ // Handing the terminal to someone else (the shell at a suspend) is leave() and enter(), and only
8
+ // that pair. An agent's terminal is never handed the terminal: the TUI draws it (lib/panel.mjs).
9
9
 
10
10
  const mode = (number, on) => `\x1b[?${number}${on ? "h" : "l"}`;
11
11
  /** After raw mode: the alternate screen, the cursor hidden, autowrap off, bracketed paste on.
@@ -22,9 +22,6 @@ export const SIGNAL_STATUS = Object.freeze({ SIGINT: 130, SIGTERM: 143, SIGHUP:
22
22
  export const TERMINAL_GONE_STATUS = SIGNAL_STATUS.SIGHUP;
23
23
  /** How long a suspend waits for the stop before it concludes there was none. */
24
24
  const STOP_GRACE_MS = 100;
25
- /** How long a run that is ending while the terminal is lent waits for the borrower to close after
26
- * it was asked to end, before it ends anyway. */
27
- export const LEND_END_GRACE_MS = 3000;
28
25
 
29
26
  /** A terminal on both ends that can be addressed: no escape byte is ever written to anything else. */
30
27
  export function isTerminal({ stdin, stdout, env }) {
@@ -44,9 +41,6 @@ export function createGuard({ stdin, stdout, proc, frame, onInput, onResize, onR
44
41
  let entered = false, raw = false, modes = false;
45
42
  let suspended = false, stopTimer = null;
46
43
  let over = false, blocked = false, stale = false;
47
- /** While the terminal is lent: `{ end, ending }`, the borrower's end() and, once the run is
48
- * ending, the `[status, error]` it ends with when the borrower has closed. Else null. */
49
- let lent = null, endTimer = null;
50
44
  let settle;
51
45
  const done = new Promise((resolve) => { settle = resolve; });
52
46
  const listeners = [];
@@ -78,7 +72,6 @@ export function createGuard({ stdin, stdout, proc, frame, onInput, onResize, onR
78
72
  if (over) return;
79
73
  over = true;
80
74
  leave();
81
- if (endTimer !== null) { clearTimer(endTimer); endTimer = null; }
82
75
  // What it throws must not keep the run from ending, nor replace the status it ends with.
83
76
  if (onEnd) quietly(onEnd);
84
77
  if (stopTimer !== null) { clearTimer(stopTimer); stopTimer = null; }
@@ -89,7 +82,7 @@ export function createGuard({ stdin, stdout, proc, frame, onInput, onResize, onR
89
82
  }
90
83
 
91
84
  /** Run one of the loop's own steps. What it throws ends the run as an uncaught error would,
92
- * without waiting for the process to say so (while the terminal is lent, the borrower first). */
85
+ * without waiting for the process to say so. */
93
86
  function attempt(step) {
94
87
  try { step(); } catch (error) { out(1, error); }
95
88
  }
@@ -97,7 +90,7 @@ export function createGuard({ stdin, stdout, proc, frame, onInput, onResize, onR
97
90
  /** One write per frame. While the last write has not drained nothing is queued: the newest frame
98
91
  * is made when it has. */
99
92
  function draw() {
100
- if (!entered || over || lent) return;
93
+ if (!entered || over) return;
101
94
  if (blocked) { stale = true; return; }
102
95
  const bytes = frame();
103
96
  if (bytes && stdout.write(bytes) === false) blocked = true;
@@ -150,68 +143,22 @@ export function createGuard({ stdin, stdout, proc, frame, onInput, onResize, onR
150
143
  /** SIGCONT. After our own suspend: come back. Otherwise the process was stopped and continued
151
144
  * from outside while it held the terminal. */
152
145
  function continued() {
153
- if (over || lent) return; // a lent terminal is the borrower's: it takes care of its own
146
+ if (over) return;
154
147
  if (suspended) return resume();
155
148
  if (onResume && entered) { attempt(() => onResume(false)); if (over) return; }
156
149
  reassert();
157
150
  }
158
151
 
159
- /** Lend the terminal to a program of its own (the kernel's viewer) and take it back when it
160
- * ends. The suspend path, without the stop: leave() (the modes, then raw mode off), input
161
- * paused, so two readers do not split the keys; then `run()`, which starts the borrower with
162
- * the terminal as its own and resolves when it has closed; then enter(), input resumed and a
163
- * full redraw. Answers a promise of `{ value }` (what run resolved with) or `{ error }` (what it
164
- * threw or rejected with: the terminal is taken back all the same).
165
- * WHILE LENT nothing is drawn, whatever asks; a SIGQUIT does not end the run (a second
166
- * Ctrl+\ after the viewer gave the terminal back is the terminal's QUIT, and the viewer handles
167
- * its own); a SIGTSTP is not heard, so its default action stops the whole group and SIGCONT
168
- * continues it, and nothing of the suspend path runs. SIGINT, SIGTERM, SIGHUP, a terminal that
169
- * goes away and an uncaught error end the run as always, but the borrower first: `end()` is
170
- * called and the run ends when the borrower has closed, or LEND_END_GRACE_MS later. The
171
- * terminal is already restored, so nothing more is written to it.
172
- * Lending a terminal that is not the TUI's now (not entered, lent, over) runs nothing. */
173
- function lend(run, { end = null, release = null } = {}) {
174
- if (!entered || over || lent) return Promise.resolve({ error: new Error("the terminal is not the TUI's to lend now") });
175
- leave();
176
- quietly(() => stdin.pause());
177
- proc.removeListener("SIGTSTP", suspend);
178
- const mine = lent = { end, release, ending: null };
179
- let running;
180
- try { running = Promise.resolve(run()); } catch (error) { running = Promise.reject(error); }
181
- return running.then((value) => ({ value }), (error) => ({ error })).then((outcome) => {
182
- lent = null;
183
- if (mine.ending) { finish(...mine.ending); return outcome; }
184
- if (over) return outcome;
185
- proc.on("SIGTSTP", suspend);
186
- try { enter(); } catch { finish(TERMINAL_GONE_STATUS); return outcome; }
187
- if (!over) stdin.resume();
188
- attempt(onRedraw);
189
- return outcome;
190
- });
191
- }
192
- /** A way out that arrives while the terminal is lent: end the borrower and wait for it. A second
193
- * one does not wait. */
194
- function endLent(status, error) {
195
- // The run does not wait for a borrower past this: what holds it (its handle, its pipe) is let
196
- // go, so the process can end with the status of the signal although the borrower lives on.
197
- const mine = lent, givenUp = () => { if (mine.release) attempt(mine.release); finish(status, error); };
198
- if (mine.ending) return givenUp();
199
- mine.ending = [status, error];
200
- if (mine.end) attempt(mine.end);
201
- if (over) return;
202
- endTimer = setTimer(() => { endTimer = null; givenUp(); }, LEND_END_GRACE_MS);
203
- }
204
152
  /** Every way out the run can be told of: a signal, an error nobody caught, a terminal gone. */
205
153
  function out(status, error) {
206
154
  if (over) return;
207
- if (lent) return endLent(status, error);
208
155
  finish(status, error);
209
156
  }
210
157
 
211
158
  /** Every way out is registered before the terminal is touched; then enter. A signal cannot land
212
159
  * inside enter(), which is synchronous, and one that lands after it finds its listener. */
213
160
  function start() {
214
- for (const [signal, status] of Object.entries(SIGNAL_STATUS)) on(proc, signal, () => { if (!(lent && signal === "SIGQUIT")) out(status); });
161
+ for (const [signal, status] of Object.entries(SIGNAL_STATUS)) on(proc, signal, () => out(status));
215
162
  on(proc, "SIGCONT", continued);
216
163
  proc.on("SIGTSTP", suspend);
217
164
  on(proc, "uncaughtException", (error) => out(1, error));
@@ -233,5 +180,5 @@ export function createGuard({ stdin, stdout, proc, frame, onInput, onResize, onR
233
180
  /** The terminal's size now; 80x24 when the terminal does not say. */
234
181
  const size = () => ({ cols: Number.isInteger(stdout.columns) && stdout.columns > 0 ? stdout.columns : 80, rows: Number.isInteger(stdout.rows) && stdout.rows > 0 ? stdout.rows : 24 });
235
182
 
236
- return { start, enter, leave, finish, suspend, reassert, attempt, draw, lend, size, done, get entered() { return entered; }, get lent() { return lent !== null; } };
183
+ return { start, enter, leave, finish, suspend, reassert, attempt, draw, size, done, get entered() { return entered; } };
237
184
  }