@awebai/oats 0.65.0 → 0.66.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 (36) hide show
  1. package/README.md +11 -5
  2. package/bin/oats.mjs +8 -7
  3. package/docs/desktop-cli-api.md +5 -4
  4. package/docs/implementation.md +10 -1
  5. package/docs/integrations.md +1 -1
  6. package/docs/official-catalog.md +2 -2
  7. package/docs/packages.md +7 -7
  8. package/docs/release-notes/v0.66.0.md +183 -0
  9. package/docs/servers.md +2 -2
  10. package/docs/tui.md +137 -16
  11. package/docs/upgrading.md +1 -1
  12. package/docs/workspaces.md +9 -2
  13. package/lib/deployments.mjs +21 -5
  14. package/package-catalog.json +2 -2
  15. package/package.json +1 -1
  16. package/packages/client/cli-locator.mjs +2 -2
  17. package/packages/client/keymap.mjs +36 -9
  18. package/packages/client/machine-contract.mjs +1 -5
  19. package/packages/record/bin/setup.mjs +10 -2
  20. package/packages/record/docs/capture-service.md +45 -6
  21. package/packages/record/lib/capture-service-install.mjs +6 -95
  22. package/packages/record/lib/capture-setup-write.mjs +233 -0
  23. package/packages/tui/README.md +7 -6
  24. package/packages/tui/lib/actions.mjs +65 -64
  25. package/packages/tui/lib/client.mjs +1 -0
  26. package/packages/tui/lib/config.mjs +167 -26
  27. package/packages/tui/lib/main.mjs +53 -9
  28. package/packages/tui/lib/model.mjs +2 -0
  29. package/packages/tui/lib/store.mjs +18 -3
  30. package/packages/tui/lib/term/keys.mjs +135 -33
  31. package/packages/tui/lib/term/kitty.mjs +198 -0
  32. package/packages/tui/lib/term/through.mjs +128 -14
  33. package/packages/tui/lib/term/tty.mjs +43 -12
  34. package/packages/tui/lib/views/frame.mjs +1 -1
  35. package/packages/tui/lib/views/help.mjs +52 -13
  36. package/skills/oats-getting-started/SKILL.md +96 -28
@@ -2,13 +2,16 @@
2
2
  // a terminal has the focus the TUI reads no keys: the bytes the outer terminal sends go to the
3
3
  // agent exactly as they came, and the scanner here looks for two things only, the back key's own
4
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.
5
+ // a paste, so a back key inside it is pasted, not taken). Under the kitty keyboard protocol
6
+ // (docs/tui.md, "Chords") it also takes the chords, and types every other key as the bytes it
7
+ // sends without the protocol (see createThrough). Pure: no IO; the clock is injected.
6
8
  //
7
9
  // The back key is tui.json's `open.detachKey`. Its grammar is THE TUI'S OWN: the keys it can take
8
10
  // back from a terminal and name in the cheat sheet. It began as the kernel's `--detach-key` grammar
9
11
  // (lib/session-viewer.mjs) and keeps its set and its spelling, so a tui.json written for PR 4 means
10
12
  // 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, createKeyParser, keyId } from "./keys.mjs";
13
+ import { ESC_TIMEOUT_MS, PASTE_LIMIT, PASTE_PAUSE_MS, createKeyParser, keyId, legacyEvents } from "./keys.mjs";
14
+ import { confirmed, kittyId, kittyKey, legacyBytes, legacySequence } from "./kitty.mjs";
12
15
 
13
16
  /** How long bytes held only as a beginning of the back key wait for the rest of it, in
14
17
  * milliseconds: the back key counts only as ONE keypress (a terminal writes a key's bytes at
@@ -95,8 +98,27 @@ const decoder = () => new TextDecoder("utf-8", { fatal: false });
95
98
 
96
99
  /** A scanner of the bytes typed while a terminal has the focus. `feed(bytes)` answers events in
97
100
  * order: `{ input: <bytes> }` (for the agent, as typed), `{ paste: <text> }` (a bracketed paste,
98
- * unwrapped) and, at most once per feed and last, `{ back: true, rest: <bytes> }` (the back key:
99
- * what came after it in the same read is no longer the agent's, and `rest` hands it on).
101
+ * unwrapped), `{ keyboard: flags }` (the terminal's answer to the kitty keyboard protocol's query,
102
+ * while `keyboard` is "asking": never the agent's) and, at most once per feed and last,
103
+ * `{ back: true, rest: <bytes> }` (the back key: what came after it in the same read is no longer
104
+ * the agent's, and `rest` hands it on) or `{ chord: <does>, rest: <bytes> }` (a chord, the same).
105
+ *
106
+ * UNDER THE PROTOCOL (`keyboard` the confirmed flags, term/kitty.mjs; docs/tui.md, "Chords") the
107
+ * scanner reads every `CSI` sequence typed. A `u` key is a chord when its id is one of `chords`
108
+ * (a Map of key id to the `does` it names), else the bytes it sends without the protocol
109
+ * (legacyBytes), which are the back key when they read as `leader` (the back key's key id,
110
+ * backKeyId), with no timing: Alt+O is one sequence and Esc is another. Any other sequence is
111
+ * the same, made legacy where the protocol changed it (legacySequence: the modifier, F1 to F4).
112
+ * What is not a sequence goes to the agent as it came. Nothing is timed: a sequence a read ends
113
+ * inside, or a lone ESC (which no key sends under the protocol), waits for the next read however
114
+ * late it comes; one longer than SEQUENCE_HELD is no key and goes on as it came.
115
+ * Without it (`keyboard` null or "asking") nothing of that is read, and what follows holds. While
116
+ * "asking", the answer may arrive split across reads, and over a slow link late: a read that ends
117
+ * in what may begin it (ESC, `ESC [`, `ESC [ ?` and digits) is held until `answerBy` (the clock time
118
+ * the run stops waiting for it), at least the key parser's Esc timeout. A later read that does not
119
+ * go on with the answer comes after them: within BACK_KEY_SPLIT_MS joined to them as before (the
120
+ * back key, a paste), later handed on after them, as a key of its own, so they never make the back
121
+ * key with it. giveUp() hands on what is held for the answer.
100
122
  * A read is never held back from the agent but for a beginning of the back key's own bytes, or of
101
123
  * a paste's start marker from its third byte: those wait for the next read, or until `timeoutAt()`
102
124
  * (BACK_KEY_SPLIT_MS for the back key's alone, the key parser's Esc timeout when they may begin a
@@ -105,13 +127,15 @@ const decoder = () => new TextDecoder("utf-8", { fatal: false });
105
127
  * its end marker; one that reaches PASTE_LIMIT is dropped whole, and one whose end has not come
106
128
  * when a read arrives PASTE_PAUSE_MS after the one before is given to the agent as what it held,
107
129
  * and that read is scanned anew, as the key parser abandons a stalled paste. */
108
- export function createThrough({ sequences, now }) {
130
+ export function createThrough({ sequences, now, keyboard = null, leader = null, chords = new Map(), answerBy = null }) {
109
131
  if (typeof now !== "function") throw new TypeError("createThrough needs an injected clock: { now: () => milliseconds }");
132
+ if (!(keyboard === null || keyboard === "asking" || confirmed(keyboard))) throw new TypeError("keyboard is null, \"asking\" or flags that hold flag 1");
110
133
  const keys = sequences.map((seq) => Uint8Array.from(seq));
134
+ let kb = keyboard;
111
135
  /** The bytes held for the next read, since when, and how long they may wait: BACK_KEY_SPLIT_MS
112
136
  * when they are held only as a beginning of the back key, ESC_TIMEOUT_MS when they may begin a
113
137
  * paste's start marker (or its rest, see PASTE_HELD_FROM). */
114
- let held = new Uint8Array(0), heldAt = 0, heldFor = ESC_TIMEOUT_MS;
138
+ let held = new Uint8Array(0), heldAt = 0, heldFor = ESC_TIMEOUT_MS, answerHeld = false;
115
139
  /** The paste being read: its content so far (null when none; only the tail that may begin the
116
140
  * end marker once it went past the limit), and whether it did. */
117
141
  let paste = null, over = false, lastFeed = 0;
@@ -169,6 +193,7 @@ export function createThrough({ sequences, now }) {
169
193
  }
170
194
 
171
195
  function scan(out, data) {
196
+ if (confirmed(kb)) return scanKitty(out, data);
172
197
  for (let i = 0; i < data.length; i++) {
173
198
  const b = data[i];
174
199
  if (b === ESC && at(data, i, PASTE_START)) {
@@ -178,32 +203,85 @@ export function createThrough({ sequences, now }) {
178
203
  if (paste !== null) return; // the paste goes on in the next read
179
204
  return scan(out, rest);
180
205
  }
206
+ // The protocol's answer, while it is awaited: the TUI's, never the agent's, and what follows
207
+ // it is read as it says.
208
+ const answer = kb === "asking" && b === ESC ? answerAt(data, i) : null;
209
+ if (answer !== null) {
210
+ if (i > 0) out.push({ input: data.subarray(0, i) });
211
+ out.push({ keyboard: answer.flags });
212
+ kb = confirmed(answer.flags) ? answer.flags : null;
213
+ return scan(out, data.subarray(answer.end));
214
+ }
181
215
  const key = keys.find((seq) => seq[0] === b && at(data, i, seq));
182
216
  if (key) {
183
217
  if (i > 0) out.push({ input: data.subarray(0, i) });
184
218
  out.push({ back: true, rest: data.subarray(i + key.length) });
185
219
  return;
186
220
  }
187
- // The read ends on what may be the beginning of the back key or of a paste: held, as long
188
- // as the one it may begin allows (a paste's, when it may begin both).
221
+ // The read ends on what may be the beginning of the back key, of a paste or of the answer
222
+ // awaited: held, as long as the longest that it may begin allows.
189
223
  const pasting = data.length - i >= PASTE_HELD_FROM && begins(data, i, PASTE_START);
190
- if (pasting || keys.some((seq) => begins(data, i, seq))) {
224
+ const answering = kb === "asking" && answerBegins(data, i);
225
+ const keying = keys.some((seq) => begins(data, i, seq));
226
+ if (pasting || answering || keying) {
191
227
  if (i > 0) out.push({ input: data.subarray(0, i) });
192
228
  held = Uint8Array.from(data.subarray(i));
193
229
  heldAt = now();
194
- heldFor = pasting ? ESC_TIMEOUT_MS : BACK_KEY_SPLIT_MS;
230
+ const asked = answerBy !== null ? Math.max(ESC_TIMEOUT_MS, answerBy - heldAt) : data.length - i < 3 ? BACK_KEY_SPLIT_MS : ESC_TIMEOUT_MS;
231
+ heldFor = Math.max(pasting ? ESC_TIMEOUT_MS : 0, answering ? asked : 0, keying ? BACK_KEY_SPLIT_MS : 0);
232
+ answerHeld = answering;
195
233
  return;
196
234
  }
197
235
  }
198
236
  if (data.length) out.push({ input: data });
199
237
  }
200
238
 
239
+ /** Under the protocol (see above): every sequence read, the rest handed on as it came. */
240
+ function scanKitty(out, data) {
241
+ let from = 0;
242
+ const handOn = (to) => { if (to > from) out.push({ input: data.subarray(from, to) }); from = to; };
243
+ const hold = (i) => { handOn(i); held = Uint8Array.from(data.subarray(i)); heldAt = now(); heldFor = Infinity; from = data.length; };
244
+ for (let i = 0; i < data.length; i++) {
245
+ if (data[i] !== ESC) continue;
246
+ if (at(data, i, PASTE_START)) {
247
+ handOn(i);
248
+ paste = new Uint8Array(0); over = false;
249
+ const rest = inPaste(out, data.subarray(i + PASTE_START.length));
250
+ if (paste !== null) return; // the paste goes on in the next read
251
+ return scan(out, rest);
252
+ }
253
+ if (i + 1 === data.length) return hold(i);
254
+ if (data[i + 1] !== 0x5b) continue; // ESC and not `[`: no key of the protocol's, as it came
255
+ let j = i + 2;
256
+ while (j < data.length && data[j] >= 0x20 && data[j] <= 0x3f) j++;
257
+ if (j === data.length) { if (j - i <= SEQUENCE_HELD) return hold(i); continue; }
258
+ if (data[j] < 0x40 || data[j] > 0x7e) continue; // no sequence: as it came
259
+ const params = String.fromCharCode(...data.subarray(i + 2, j)), final = String.fromCharCode(data[j]), end = j + 1;
260
+ handOn(i);
261
+ from = end;
262
+ i = end - 1;
263
+ let bytes;
264
+ if (final === "u") {
265
+ if (/^\?\d{1,3}$/.test(params)) continue; // the protocol's answer again: never the agent's
266
+ const key = kittyKey(params), id = kittyId(key);
267
+ if (id !== null && chords.has(id)) { out.push({ chord: chords.get(id), rest: data.subarray(end) }); return; }
268
+ bytes = legacyBytes(key, kb);
269
+ } else bytes = legacySequence(params, final);
270
+ if (bytes === null) continue; // a key that sends nothing without the protocol: nothing
271
+ const events = leader === null ? [] : legacyEvents(bytes);
272
+ if (events.length === 1 && keyId(events[0]) === leader) { out.push({ back: true, rest: data.subarray(end) }); return; }
273
+ out.push({ input: bytes });
274
+ }
275
+ handOn(data.length);
276
+ }
277
+
201
278
  /** The held bytes, once they waited as long as they may at `t`: handed on as input, as one event
202
279
  * of their own (and noted, so a paste they begin is still raw), or nothing. */
203
280
  function lapse(t) {
204
281
  if (!held.length || t < heldAt + heldFor) return [];
205
282
  const out = [{ input: held }];
206
283
  held = new Uint8Array(0);
284
+ answerHeld = false;
207
285
  forwarded = handedOn(out);
208
286
  return out;
209
287
  }
@@ -212,6 +290,9 @@ export function createThrough({ sequences, now }) {
212
290
  feed(bytes) {
213
291
  if (!(bytes instanceof Uint8Array)) throw new TypeError("feed expects bytes (a Uint8Array)");
214
292
  const t = now();
293
+ // Bytes held for the answer that this read does not go on with, past the one-keypress window:
294
+ // their wait is over.
295
+ if (held.length && answerHeld && t >= heldAt + BACK_KEY_SPLIT_MS && !answerGoesOn(join(held, bytes))) heldFor = 0;
215
296
  // Held bytes whose wait is over are the agent's before this read is looked at, whether or not
216
297
  // expire() ran: a read that comes later never completes the back key with them (one keypress).
217
298
  const late = lapse(t), out = [];
@@ -225,7 +306,7 @@ export function createThrough({ sequences, now }) {
225
306
  data = inPaste(out, data);
226
307
  if (paste !== null) return out; // nothing was held: a paste and held bytes never meet
227
308
  }
228
- if (held.length) { data = join(held, data); held = new Uint8Array(0); }
309
+ if (held.length) { data = join(held, data); held = new Uint8Array(0); answerHeld = false; }
229
310
  // The rest of a start marker whose first bytes the last read handed on: the paste is raw.
230
311
  // A beginning of that rest waits for the next read, as a held key does.
231
312
  if (raw === null && forwarded > 0 && soon) {
@@ -236,11 +317,44 @@ export function createThrough({ sequences, now }) {
236
317
  forwarded = 0;
237
318
  if (raw !== null) data = inRaw(out, data);
238
319
  if (raw === null && data.length) scan(out, data);
239
- forwarded = handedOn(out);
320
+ // Under the protocol a paste's start marker is held whole: no paste is ever passed on raw.
321
+ forwarded = confirmed(kb) ? (handedOn(out), 0) : handedOn(out);
240
322
  // Events are handed out as copies: the caller may keep them past the next read.
241
- return [...late, ...out].map((event) => (event.input ? { input: Uint8Array.from(event.input) } : event.rest ? { back: true, rest: Uint8Array.from(event.rest) } : event));
323
+ return [...late, ...out].map((event) => (event.input ? { input: Uint8Array.from(event.input) } : event.rest ? { ...event, rest: Uint8Array.from(event.rest) } : event));
242
324
  },
243
325
  expire() { return lapse(now()); },
244
- timeoutAt() { return held.length ? heldAt + heldFor : null; },
326
+ timeoutAt() { return held.length && Number.isFinite(heldFor) ? heldAt + heldFor : null; },
327
+ /** The answer is no longer awaited (none came in time): a late one goes on as it came, and what
328
+ * was held for it is handed on (the events answered). */
329
+ giveUp() {
330
+ if (kb === "asking") kb = null;
331
+ if (!answerHeld) return [];
332
+ heldFor = 0;
333
+ return lapse(now()).map((event) => ({ input: Uint8Array.from(event.input) }));
334
+ },
245
335
  };
246
336
  }
337
+
338
+ /** The most bytes of a `CSI` sequence held for its end under the protocol; a longer one is no key,
339
+ * and goes on as it came. */
340
+ const SEQUENCE_HELD = 64;
341
+ /** Whether `data` from `i` to its end may begin the protocol's answer `CSI ? flags u`: ESC, `ESC [`,
342
+ * or `ESC [ ?` and digits, short of the `u`. */
343
+ function answerBegins(data, i) {
344
+ const left = data.length - i;
345
+ if (left < 1 || left > 6 || data[i] !== ESC) return false;
346
+ if (left >= 2 && data[i + 1] !== 0x5b) return false;
347
+ if (left >= 3 && data[i + 2] !== 0x3f) return false;
348
+ for (let j = i + 3; j < data.length; j++) if (data[j] < 0x30 || data[j] > 0x39) return false;
349
+ return true;
350
+ }
351
+ /** Whether `data` begins with the answer, whole or begun. */
352
+ const answerGoesOn = (data) => answerAt(data, 0) !== null || answerBegins(data, 0);
353
+ /** The protocol's answer `CSI ? flags u` whole at `i`: `{ flags, end }`, or null. */
354
+ function answerAt(data, i) {
355
+ if (data[i + 1] !== 0x5b || data[i + 2] !== 0x3f) return null;
356
+ let j = i + 3;
357
+ while (j < data.length && j - i < 7 && data[j] >= 0x30 && data[j] <= 0x39) j++;
358
+ if (j === i + 3 || data[j] !== 0x75) return null;
359
+ return { flags: Number(String.fromCharCode(...data.subarray(i + 3, j))), end: j + 1 };
360
+ }
@@ -1,12 +1,14 @@
1
1
  // The guard: everything the TUI changes in the terminal, and the promise that it is put back.
2
- // With term/screen.mjs it is the only module that produces an ESC byte. docs/tui.md lists the
3
- // changes for operators; ENTER and LEAVE below are that list, and nothing else is ever switched on:
4
- // no mouse or focus reporting, no keyboard protocol, no keypad or cursor-key mode, no title, no
5
- // clipboard, no bell, no query that expects a reply.
2
+ // With term/screen.mjs it is the only module that writes an ESC byte to the terminal. docs/tui.md
3
+ // lists the changes for operators; ENTER and LEAVE below are that list, with the kitty keyboard
4
+ // protocol (PUSH, QUERY, POP), and nothing else is ever switched on: no mouse or focus reporting, no
5
+ // keypad or cursor-key mode, no title, no clipboard, no bell, and no query but the protocol's.
6
6
  //
7
7
  // Handing the terminal to someone else (the shell at a suspend) is leave() and enter(), and only
8
8
  // that pair. An agent's terminal is never handed the terminal: the TUI draws it (lib/panel.mjs).
9
9
 
10
+ import { KEYBOARD_FLAGS } from "./kitty.mjs";
11
+
10
12
  const mode = (number, on) => `\x1b[?${number}${on ? "h" : "l"}`;
11
13
  /** After raw mode: the alternate screen, the cursor hidden, autowrap off, bracketed paste on.
12
14
  * Autowrap is off so no row wraps where the terminal and width.mjs disagree about a character (a
@@ -15,6 +17,13 @@ const mode = (number, on) => `\x1b[?${number}${on ? "h" : "l"}`;
15
17
  export const ENTER = mode(1049, true) + mode(25, false) + mode(7, false) + mode(2004, true);
16
18
  /** The reverse, with the style reset; then raw mode off. */
17
19
  export const LEAVE = mode(2004, false) + mode(7, true) + "\x1b[0m" + mode(25, true) + mode(1049, false);
20
+ /** The kitty keyboard protocol (term/kitty.mjs; docs/tui.md, "Chords"): pushed with the flags the TUI
21
+ * asks for, on the alternate screen (a terminal keeps one stack of flags per screen), and asked
22
+ * about; popped before the alternate screen is left, on every way out, at a suspend, and before any
23
+ * other program is given the terminal. A terminal that does not know it ignores all three. */
24
+ export const PUSH = `\x1b[>${KEYBOARD_FLAGS}u`;
25
+ export const QUERY = "\x1b[?u";
26
+ export const POP = "\x1b[<u";
18
27
 
19
28
  /** 128 + the signal's number, as a shell reports a process the signal ended. */
20
29
  export const SIGNAL_STATUS = Object.freeze({ SIGINT: 130, SIGTERM: 143, SIGHUP: 129, SIGQUIT: 131 });
@@ -28,8 +37,11 @@ export function isTerminal({ stdin, stdout, env }) {
28
37
  return stdin.isTTY === true && stdout.isTTY === true && typeof env.TERM === "string" && env.TERM !== "" && env.TERM !== "dumb";
29
38
  }
30
39
 
31
- /** The guard of one run. `frame()` answers the bytes of the newest frame when it is time to write
32
- * one; `onInput(bytes)`, `onResize()` and `onRedraw()` (the screen must be drawn in full: after a
40
+ /** The guard of one run. `keyboard` true asks for the kitty keyboard protocol: PUSH and QUERY after
41
+ * ENTER; then `keyboardAnswered(true)` keeps it (it is pushed again after every LEAVE and ENTER),
42
+ * and `keyboardAnswered(false)` (an answer without flag 1, or none in time) pops it and never
43
+ * pushes it again. While pushed, every LEAVE is written after POP. `frame()` answers the bytes of
44
+ * the newest frame when it is time to write one; `onInput(bytes)`, `onResize()` and `onRedraw()` (the screen must be drawn in full: after a
33
45
  * suspend, after SIGCONT) are the events. `done` resolves once, with `{ status, error }`, after the
34
46
  * terminal is restored and every listener is removed.
35
47
  * Three more, for whoever started work that outlives a frame (the reads of lib/read.mjs), each
@@ -37,8 +49,15 @@ export function isTerminal({ stdin, stdout, env }) {
37
49
  * the terminal is handed back and before the signal; `onResume(asked)` when it runs again, `asked`
38
50
  * true after its own suspend and false when it was stopped and continued from outside; `onEnd()`
39
51
  * once on every way out, after the terminal is restored and before `done` resolves. */
40
- export function createGuard({ stdin, stdout, proc, frame, onInput, onResize, onRedraw, onStop = null, onResume = null, onEnd = null, setTimer = setTimeout, clearTimer = clearTimeout }) {
52
+ export function createGuard({ stdin, stdout, proc, frame, onInput, onResize, onRedraw, onStop = null, onResume = null, onEnd = null, keyboard = false, setTimer = setTimeout, clearTimer = clearTimeout }) {
41
53
  let entered = false, raw = false, modes = false;
54
+ /** The protocol: "asking" until the terminal answered, "on" once it did with flag 1, "off" without
55
+ * it; and whether it is pushed now. */
56
+ let kb = keyboard ? "asking" : "off", pushed = false;
57
+ /** What is written after ENTER: the protocol pushed, and asked about while no answer came. */
58
+ const pushing = () => (kb === "off" ? "" : kb === "asking" ? PUSH + QUERY : PUSH);
59
+ /** What is written before LEAVE: the protocol popped, when it is pushed. */
60
+ const popping = () => { if (!pushed) return ""; pushed = false; return POP; };
42
61
  let suspended = false, stopTimer = null;
43
62
  let over = false, blocked = false, stale = false;
44
63
  let settle;
@@ -57,15 +76,24 @@ export function createGuard({ stdin, stdout, proc, frame, onInput, onResize, onR
57
76
  stdin.setRawMode(true);
58
77
  if (!entered) return; // left while entering: nothing more is switched on
59
78
  modes = true;
60
- stdout.write(ENTER);
79
+ const push = pushing();
80
+ pushed = push !== "";
81
+ stdout.write(ENTER + push);
61
82
  }
62
83
  /** Put the terminal back. Idempotent; never throws. */
63
84
  function leave() {
64
85
  if (!entered) return;
65
86
  entered = false;
66
- if (modes) { modes = false; quietly(() => stdout.write(LEAVE)); }
87
+ if (modes) { modes = false; const pop = popping(); quietly(() => stdout.write(pop + LEAVE)); }
67
88
  if (raw) { raw = false; quietly(() => stdin.setRawMode(false)); }
68
89
  }
90
+ /** The terminal's answer to the protocol's query, or none in time (`false`): kept, or popped and
91
+ * never pushed again in this run. An answer after either is not taken. */
92
+ function keyboardAnswered(on) {
93
+ if (kb !== "asking" || over) return;
94
+ kb = on ? "on" : "off";
95
+ if (!on && entered) { const pop = popping(); if (pop) quietly(() => stdout.write(pop)); }
96
+ }
69
97
 
70
98
  /** The end of the run, by any way out: restore, stop listening, report once. */
71
99
  function finish(status, error) {
@@ -133,11 +161,14 @@ export function createGuard({ stdin, stdout, proc, frame, onInput, onResize, onR
133
161
  * write. Entering the alternate screen also saves the cursor, and a terminal that is still on
134
162
  * it may take a second entry as a new save, over the shell's position: the prompt would then
135
163
  * land on the wrong row at the end. Leaving first puts back the cursor the first entry saved,
136
- * so the second saves the same one. On a terminal that was reset, the leave changes nothing. */
164
+ * so the second saves the same one. On a terminal that was reset, the leave changes nothing.
165
+ * The kitty keyboard protocol goes with the modes: popped before LEAVE, pushed again after ENTER. */
137
166
  function reassert() {
138
167
  if (!entered || over) return;
139
168
  quietly(() => { stdin.setRawMode(false); stdin.setRawMode(true); });
140
- quietly(() => stdout.write(LEAVE + ENTER));
169
+ const pop = popping(), push = pushing();
170
+ pushed = push !== "";
171
+ quietly(() => stdout.write(pop + LEAVE + ENTER + push));
141
172
  attempt(onRedraw);
142
173
  }
143
174
  /** SIGCONT. After our own suspend: come back. Otherwise the process was stopped and continued
@@ -180,5 +211,5 @@ export function createGuard({ stdin, stdout, proc, frame, onInput, onResize, onR
180
211
  /** The terminal's size now; 80x24 when the terminal does not say. */
181
212
  const size = () => ({ cols: Number.isInteger(stdout.columns) && stdout.columns > 0 ? stdout.columns : 80, rows: Number.isInteger(stdout.rows) && stdout.rows > 0 ? stdout.rows : 24 });
182
213
 
183
- return { start, enter, leave, finish, suspend, reassert, attempt, draw, size, done, get entered() { return entered; } };
214
+ return { start, enter, leave, finish, suspend, reassert, attempt, draw, size, done, keyboardAnswered, get entered() { return entered; }, get keyboard() { return kb; } };
184
215
  }
@@ -539,7 +539,7 @@ function framed(m, size) {
539
539
  }
540
540
  // The help, under its top row (readRow).
541
541
  if (m.view === "help") {
542
- const drawn = help(m.actions, { cols: main.cols, rows: size.rows - 1 }, { top: m.helpTop, ascii: m.ascii, detachKey: m.detachKey });
542
+ const drawn = help(m.actions, { cols: main.cols, rows: size.rows - 1 }, { top: m.helpTop, ascii: m.ascii, detachKey: m.detachKey, chords: m.chords ?? null });
543
543
  overlay([readRow(m), ...drawn.rows]);
544
544
  return { rows, page: Math.max(1, g.page), extent: drawn.extent, room: Math.max(1, size.rows - 1) };
545
545
  }
@@ -38,7 +38,7 @@ export const NOT_YET = Object.freeze([
38
38
  Object.freeze({ what: "see a capability's skills and files", command: "oats capabilities show <name>" }),
39
39
  Object.freeze({ what: "open an agent in its own tmux window", command: "oats session attach --home <home>" }),
40
40
  Object.freeze({ what: "start with another harness or model", command: "oats session start --home <home>" }),
41
- Object.freeze({ what: "add a machine to this workspace", command: "oats server connect <id> --ssh <alias>" }),
41
+ Object.freeze({ what: "add a machine to this workspace", command: "oats server connect <id> --ssh <alias> --dir <path on that machine>" }),
42
42
  Object.freeze({ what: "check a machine", command: "oats server check <id>" }),
43
43
  Object.freeze({ what: "remove a machine", command: "oats server remove <id>" }),
44
44
  // The switcher lists the deployments opened in this run and those on this computer's list, and no other.
@@ -68,10 +68,11 @@ const flow = (pieces, room) => pieces.reduce((lines, piece) => {
68
68
  return lines;
69
69
  }, []);
70
70
  /** A table: a left column as wide as its widest entry, then what each entry means, given as
71
- * pieces that are never broken (a word, or a whole command: a command cut in two cannot be
72
- * typed). What does not fit `cols` goes on in the same column on the next row. A table with a
73
- * piece wider than that column puts every meaning under its entry instead, so no row is cut at
74
- * the smallest width the frame draws at; a piece wider than even that starts further left. */
71
+ * pieces that are never cut (a word, or a whole command: a command cut short cannot be typed).
72
+ * What does not fit `cols` goes on in the same column on the next row. A table with a piece
73
+ * wider than that column puts every meaning under its entry instead, so no row is cut at the
74
+ * smallest width the frame draws at; a piece wider than even that starts further left, and a
75
+ * command wider than the whole area is broken before its flags (commandRows). */
75
76
  function table(pairs, cols, look) {
76
77
  // An entry is the TUI's own word, or text made elsewhere with its width (a key's label). A
77
78
  // third member makes rows of its own under the entry's meaning: given the meaning's column and
@@ -85,12 +86,27 @@ function table(pairs, cols, look) {
85
86
  return pairs.flatMap(([left, pieces]) => {
86
87
  // A row wider than its column (a whole command, in a narrow area) starts as far left as it
87
88
  // must to stand whole, down to the area's first column: a command cut short cannot be typed.
88
- const lines = flow(pieces, cols - at).map((text) => ({ col: Math.max(0, Math.min(at, cols - text.length)), text: lit(text) }));
89
+ const lines = flow(pieces, cols - at).flatMap((text) => (text.length <= cols ? [{ col: Math.max(0, Math.min(at, cols - text.length)), text: lit(text) }] : commandRows(text, at, cols)));
89
90
  const more = (under.get(pieces)?.(cols - at) ?? []).map((spans) => spans.map((span) => ({ ...span, col: span.col + at })));
90
91
  return [...(stacked ? [[entry(left)], ...lines.map((line) => [line])] : lines.map((line, i) => (i === 0 ? [entry(left), line] : [line]))), ...more];
91
92
  });
92
93
  }
93
94
 
95
+ /** A command wider than the whole area (`oats server connect`'s, at 80 columns and under), on as
96
+ * few rows as it needs: broken only before a flag (`--dir`), each flag with its value, the rows
97
+ * after the first 2 cells further in, so read in order they are the command, and every row
98
+ * stands whole inside the area, as far right as `at` when there is room. */
99
+ function commandRows(command, at, cols) {
100
+ const rows = command.split(/ (?=--)/).reduce((rows, part) => {
101
+ const last = rows.length - 1;
102
+ if (last >= 0 && rows[last].length + 1 + part.length <= (last === 0 ? cols : cols - 2)) rows[last] += ` ${part}`;
103
+ else rows.push(part);
104
+ return rows;
105
+ }, []);
106
+ const start = Math.max(0, Math.min(at, cols - Math.max(rows[0].length, ...rows.slice(1).map((row) => row.length + 2))));
107
+ return rows.map((row, i) => ({ col: start + (i === 0 ? 0 : 2), text: lit(row) }));
108
+ }
109
+
94
110
  /** The TUI's own sentences under the line of `open` in the list of instances: what the terminal
95
111
  * takes, what it does not do, and where the keys that can be the back key are listed (the help
96
112
  * does not restate the grammar). */
@@ -102,7 +118,7 @@ export const OPEN_RULES = Object.freeze([
102
118
  /** The rows under the line of `open`, in `room` cells: the leader then Esc, which takes the focus
103
119
  * from the open terminal, and the leader twice, which types it into the terminal (tui.json's
104
120
  * open.detachKey, text from outside), then OPEN_RULES, each sentence on as many rows as it needs. */
105
- function openRows(detachKey, room) {
121
+ function openRows(detachKey, room, chorded = false) {
106
122
  const label = backKeyLabel(detachKey), esc = keyLabel(LEADER.find((entry) => entry.does === "list").keys[0]);
107
123
  const pair = (keys, said) => {
108
124
  const key = keyText(keys), lines = flow(words(said), Math.max(1, room - key.width - 1));
@@ -111,9 +127,11 @@ function openRows(detachKey, room) {
111
127
  return [
112
128
  ...pair(`${label} ${esc}`, "takes the focus from the terminal back to the list; the agent keeps running."),
113
129
  ...pair(`${label} ${label}`, "types the leader into the terminal."),
114
- ...OPEN_RULES.flatMap((sentence) => flow(words(sentence), room).map((text) => [{ col: 0, text: lit(text) }])),
130
+ ...[...OPEN_RULES, ...(chorded ? [CHORD_OPEN_RULE] : [])].flatMap((sentence) => flow(words(sentence), room).map((text) => [{ col: 0, text: lit(text) }])),
115
131
  ];
116
132
  }
133
+ /** Under OPEN_RULES, while the chords are listed: they too are the TUI's in a terminal. */
134
+ export const CHORD_OPEN_RULE = "The chords (below) are taken there too: they never reach the agent.";
117
135
  /** The TUI's own sentences under the line of the last act: how a confirmation is worked, and that
118
136
  * what it sent is never ended by the TUI. */
119
137
  export const ACT_RULES = Object.freeze([
@@ -132,6 +150,24 @@ const sentences = (list, cols) => list.flatMap((sentence) => {
132
150
  /** What the leader pressed again does, the last line of the leader's table. */
133
151
  export const LEADER_AGAIN = "the leader again: types it into the terminal that has the focus; with the list focused, closes the hint";
134
152
 
153
+ /** THE CHORDS (docs/tui.md, "Chords"): listed only while the terminal confirms the kitty keyboard
154
+ * protocol, which alone sends them, as extras: the leader is the key that always works. What a
155
+ * terminal may take first is said, with foot's list. */
156
+ export const CHORD_RULES = Object.freeze([
157
+ "Your terminal may take some of these first: foot takes Ctrl+Shift+C, V, R, N, O, U, Z, X and Q. The leader works in every terminal.",
158
+ ]);
159
+ /** The chords' rows: `chords` are `[key id, does]`, each said as the leader's table says its `does`. */
160
+ function chordRows(chords, cols) {
161
+ const said = (does) => LEADER.find((entry) => entry.does === does)?.label ?? does;
162
+ return [
163
+ heading("Chords"),
164
+ [],
165
+ ...sentences(["Your terminal sends these keys too: each does what the leader then its key does, from every focus, a terminal's too."], cols),
166
+ ...table(chords.map(([key, does]) => [keyLabel(key), words(said(does))]), cols, KEYS),
167
+ ...sentences(CHORD_RULES, cols),
168
+ ];
169
+ }
170
+
135
171
  /** The palette's keys (docs/tui.md, "The palette"): it reads its keys itself, so they are fixed
136
172
  * and the TUI's words. */
137
173
  export const PALETTE_KEYS = Object.freeze([
@@ -181,8 +217,10 @@ const spawnRows = (cols) => [heading("The spawn prompt"), [], ...table(SPAWN_KEY
181
217
  * now. An action that does one thing in each view has a line per view, its key on each; under
182
218
  * the line of opening an agent stand the back key (`detachKey`, tui.json's `open.detachKey`) and
183
219
  * the rules of OPEN_RULES; under the line of the last act, ACT_RULES. After the leader's table,
184
- * the palette's keys (PALETTE_KEYS) and the spawn prompt's (SPAWN_KEYS, SPAWN_RULES). */
185
- export function helpRows(actions, ascii, cols = 100, detachKey = null) {
220
+ * the chords (`chords`, `[key id, does]`, or null while the terminal has not confirmed the kitty
221
+ * keyboard protocol: then they are not listed), the palette's keys (PALETTE_KEYS) and the spawn
222
+ * prompt's (SPAWN_KEYS, SPAWN_RULES). */
223
+ export function helpRows(actions, ascii, cols = 100, detachKey = null, chords = null) {
186
224
  const marks = marksOf(ascii);
187
225
  const closing = keyText(["close", "help"].map((id) => actions.find((action) => action.id === id)).filter((action) => action?.keys.length).map((action) => keyLabel(action.keys[0])).join(" or "));
188
226
  return [
@@ -191,10 +229,11 @@ export function helpRows(actions, ascii, cols = 100, detachKey = null) {
191
229
  ...table(actions.flatMap((action) => {
192
230
  const left = action.keys.length ? keyText(keysLabel(action)) : "(no key)";
193
231
  if (!action.views) return [[left, words(action.label)]];
194
- return action.views.map(([view, said]) => [left, words(said), action.id === "open" && view === "instances" && detachKey !== null ? (room) => openRows(detachKey, room)
232
+ return action.views.map(([view, said]) => [left, words(said), action.id === "open" && view === "instances" && detachKey !== null ? (room) => openRows(detachKey, room, chords !== null && chords.length > 0)
195
233
  : action.id === "restart" ? actRows : undefined]);
196
234
  }), cols, KEYS),
197
235
  ...(detachKey !== null ? [[], ...leaderRows(detachKey, cols)] : []),
236
+ ...(chords !== null && chords.length > 0 ? [[], ...chordRows(chords, cols)] : []),
198
237
  [],
199
238
  ...paletteRows(cols),
200
239
  [],
@@ -234,8 +273,8 @@ export function helpRows(actions, ascii, cols = 100, detachKey = null) {
234
273
 
235
274
  /** `{ rows, extent }`: `size.rows` rows for an area `size.cols` wide, scrolled to `top`, and how
236
275
  * many rows the whole help has. The movement keys scroll it. */
237
- export function help(actions, size, { top = 0, ascii = false, detachKey = null } = {}) {
238
- const all = helpRows(actions, ascii, size.cols, detachKey);
276
+ export function help(actions, size, { top = 0, ascii = false, detachKey = null, chords = null } = {}) {
277
+ const all = helpRows(actions, ascii, size.cols, detachKey, chords);
239
278
  const rows = Array.from({ length: size.rows }, () => []);
240
279
  const win = windowOf({ top, count: all.length, height: size.rows });
241
280
  all.slice(win.top, win.top + win.size).forEach((spans, i) => { rows[i] = spans; });