@awebai/oats 0.65.0 → 0.67.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 (75) hide show
  1. package/README.md +11 -5
  2. package/bin/oats.mjs +74 -20
  3. package/docs/capabilities.md +4 -4
  4. package/docs/capability-manifest.schema.json +1 -1
  5. package/docs/desktop-cli-api.md +222 -10
  6. package/docs/desktop.md +101 -22
  7. package/docs/implementation.md +16 -6
  8. package/docs/integrations.md +1 -1
  9. package/docs/official-catalog.md +2 -2
  10. package/docs/packages.md +7 -7
  11. package/docs/release-lane.md +16 -0
  12. package/docs/release-notes/v0.66.0.md +183 -0
  13. package/docs/release-notes/v0.67.0.md +366 -0
  14. package/docs/release-notes/v0.67.1.md +64 -0
  15. package/docs/servers.md +5 -4
  16. package/docs/souls-and-instances.md +20 -3
  17. package/docs/tui.md +658 -143
  18. package/docs/upgrading.md +107 -25
  19. package/docs/workspaces.md +9 -2
  20. package/lib/capability-contract.mjs +2 -2
  21. package/lib/core.mjs +126 -54
  22. package/lib/deployments.mjs +21 -5
  23. package/lib/instance-color.mjs +58 -0
  24. package/lib/instance-inspect.mjs +107 -23
  25. package/lib/instance-lifecycle.mjs +21 -1
  26. package/lib/instance-naming.mjs +187 -0
  27. package/lib/instance-resolution.mjs +5 -1
  28. package/lib/materialize.mjs +62 -11
  29. package/lib/servers.mjs +15 -6
  30. package/lib/soul-composition.mjs +7 -3
  31. package/package-catalog.json +2 -2
  32. package/package.json +1 -1
  33. package/packages/client/cli-adapter.mjs +37 -5
  34. package/packages/client/cli-locator.mjs +2 -2
  35. package/packages/client/composed-gate.mjs +10 -2
  36. package/packages/client/deployment-data.mjs +5 -0
  37. package/packages/client/deployment-identity.mjs +40 -0
  38. package/packages/client/deployment-panel.mjs +3 -1
  39. package/packages/client/inspect-boundary.mjs +11 -7
  40. package/packages/client/inspect-cache.mjs +2 -2
  41. package/packages/client/instance-name.mjs +28 -0
  42. package/packages/client/instance-presentation.mjs +11 -0
  43. package/packages/client/keymap.mjs +99 -11
  44. package/packages/client/keys-file.mjs +122 -0
  45. package/packages/client/machine-contract.mjs +1 -5
  46. package/packages/client/own-codes.mjs +4 -2
  47. package/packages/client/panel-views.mjs +62 -9
  48. package/packages/client/spawn-naming.mjs +31 -0
  49. package/packages/client/spawn-preview-cli.mjs +22 -7
  50. package/packages/client/spawn-preview-contract.mjs +24 -0
  51. package/packages/client/spawn-preview-facts.mjs +8 -4
  52. package/packages/client/spawn-preview.mjs +47 -2
  53. package/packages/record/bin/setup.mjs +10 -2
  54. package/packages/record/docs/capture-service.md +45 -6
  55. package/packages/record/lib/capture-service-install.mjs +6 -95
  56. package/packages/record/lib/capture-setup-write.mjs +233 -0
  57. package/packages/tui/README.md +9 -8
  58. package/packages/tui/lib/actions.mjs +108 -64
  59. package/packages/tui/lib/client.mjs +8 -3
  60. package/packages/tui/lib/config.mjs +208 -26
  61. package/packages/tui/lib/main.mjs +91 -20
  62. package/packages/tui/lib/model.mjs +167 -61
  63. package/packages/tui/lib/read.mjs +53 -1
  64. package/packages/tui/lib/store.mjs +156 -47
  65. package/packages/tui/lib/term/keys.mjs +150 -34
  66. package/packages/tui/lib/term/kitty.mjs +223 -0
  67. package/packages/tui/lib/term/through.mjs +174 -27
  68. package/packages/tui/lib/term/tty.mjs +43 -12
  69. package/packages/tui/lib/views/frame.mjs +158 -79
  70. package/packages/tui/lib/views/help.mjs +143 -21
  71. package/packages/tui/lib/views/instances.mjs +59 -20
  72. package/packages/tui/lib/views/palette.mjs +14 -4
  73. package/packages/tui/lib/views/souls.mjs +2 -2
  74. package/packages/tui/lib/views/switcher.mjs +6 -1
  75. package/skills/oats-getting-started/SKILL.md +107 -34
@@ -1,19 +1,23 @@
1
1
  // What is typed through to an agent's terminal (docs/tui.md, "Open an agent's terminal"). While
2
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.
3
+ // agent exactly as they came, and the scanner here looks for three things only: the back key's own
4
+ // bytes (which take the focus back to the list), a bracketed paste (which goes to the agent as a
5
+ // paste, so a back key inside it is pasted, not taken) and the chords (docs/tui.md, "Chords"): the
6
+ // Alt+Shift arrows in every state, and under the kitty keyboard protocol the Ctrl+Alt ones too (or,
7
+ // when keys.json chose that family, the Ctrl+Shift ones), every other key then typed as the bytes it sends without the protocol (see createThrough). Pure:
8
+ // no IO; the clock is injected.
6
9
  //
7
10
  // The back key is tui.json's `open.detachKey`. Its grammar is THE TUI'S OWN: the keys it can take
8
11
  // back from a terminal and name in the cheat sheet. It began as the kernel's `--detach-key` grammar
9
12
  // (lib/session-viewer.mjs) and keeps its set and its spelling, so a tui.json written for PR 4 means
10
13
  // 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";
14
+ import { ESC_TIMEOUT_MS, PASTE_LIMIT, PASTE_PAUSE_MS, createKeyParser, keyId, legacyEvents } from "./keys.mjs";
15
+ import { LEGACY_CHORDS, confirmed, kittyId, kittyKey, legacyBytes, legacyChord, legacySequence } from "./kitty.mjs";
12
16
 
13
- /** How long bytes held only as a beginning of the back key wait for the rest of it, in
14
- * milliseconds: the back key counts only as ONE keypress (a terminal writes a key's bytes at
15
- * once; a split read of them comes within this), so Esc and then `o` typed as two keys reach the
16
- * agent as they were typed, and never as M-o. Bytes that may begin a paste's start marker wait
17
+ /** How long bytes held only as a beginning of the back key (or of an Alt+Shift arrow chord, see
18
+ * createThrough) wait for the rest of it, in milliseconds: the back key counts only as ONE
19
+ * keypress (a terminal writes a key's bytes at once; a split read of them comes within this), so
20
+ * Esc and then `o` typed as two keys reach the agent as they were typed, and never as M-o. Bytes that may begin a paste's start marker wait
17
21
  * the key parser's Esc timeout (ESC_TIMEOUT_MS) instead, as before. */
18
22
  export const BACK_KEY_SPLIT_MS = 10;
19
23
 
@@ -95,23 +99,63 @@ const decoder = () => new TextDecoder("utf-8", { fatal: false });
95
99
 
96
100
  /** A scanner of the bytes typed while a terminal has the focus. `feed(bytes)` answers events in
97
101
  * 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).
100
- * A read is never held back from the agent but for a beginning of the back key's own bytes, or of
101
- * a paste's start marker from its third byte: those wait for the next read, or until `timeoutAt()`
102
- * (BACK_KEY_SPLIT_MS for the back key's alone, the key parser's Esc timeout when they may begin a
103
- * paste) hands them on as input, through `expire()` or the first read that comes later, which
104
- * then never completes the back key with them. A paste is held until
105
- * its end marker; one that reaches PASTE_LIMIT is dropped whole, and one whose end has not come
102
+ * unwrapped), `{ keyboard: flags }` (the terminal's answer to the kitty keyboard protocol's query,
103
+ * while `keyboard` is "asking": never the agent's) and, at most once per feed and last,
104
+ * `{ back: true, rest: <bytes> }` (the back key: what came after it in the same read is no longer
105
+ * the agent's, and `rest` hands it on) or `{ chord: <does>, rest: <bytes> }` (a chord, the same).
106
+ *
107
+ * UNDER THE PROTOCOL (`keyboard` the confirmed flags, term/kitty.mjs; docs/tui.md, "Chords") the
108
+ * scanner reads every `CSI` sequence typed. A `u` key is a chord when its id (kittyId, a Ctrl+Alt or
109
+ * a Ctrl+Shift chord's) is one of `chords` (a Map of key id to the `does` it names), else the bytes it sends
110
+ * without the protocol (legacyBytes), which are the back key when they read as `leader` (the back
111
+ * key's key id, backKeyId) and the key has no id of its own (kittyId: Ctrl+Shift+X, whose legacy
112
+ * byte is Ctrl+X's, is typed, never the back key), with no timing: Alt+O is one sequence and Esc is another. Any other sequence is
113
+ * the same, made legacy where the protocol changed it (legacySequence: the modifier, F1 to F4).
114
+ * What is not a sequence goes to the agent as it came. Nothing is timed: a sequence a read ends
115
+ * inside, or a lone ESC (which no key sends under the protocol), waits for the next read however
116
+ * late it comes; one longer than SEQUENCE_HELD is no key and goes on as it came.
117
+ * A Ctrl+Shift chord is read only so, from its event's Shift bit: a Ctrl+Shift letter that is not
118
+ * among `chords` (every one under the default family) is typed as Ctrl and the letter
119
+ * (`CSI 100;6u` is 0x04, the agent's Ctrl+D), and a C0 byte typed is never a chord.
120
+ * The legacy bytes are read as the key they are: an Alt+Shift arrow among `chords`
121
+ * (term/kitty.mjs LEGACY_CHORDS) is the chord however the protocol reports the lock keys in its
122
+ * modifier (legacyParams: `CSI 1 ; 68 A` with Caps Lock is `CSI 1 ; 4 A`), and so is a keypad
123
+ * arrow whose legacy bytes are that sequence.
124
+ * Without it (`keyboard` null or "asking") no `CSI u` key is read and no key is made legacy, and
125
+ * what follows holds. While
126
+ * "asking", the answer may arrive split across reads, and over a slow link late: a read that ends
127
+ * in what may begin it (ESC, `ESC [`, `ESC [ ?` and digits) is held until `answerBy` (the clock time
128
+ * the run stops waiting for it), at least the key parser's Esc timeout. A later read that does not
129
+ * go on with the answer comes after them: within BACK_KEY_SPLIT_MS joined to them as before (the
130
+ * back key, a paste), later handed on after them, as a key of its own, so they never make the back
131
+ * key with it. giveUp() hands on what is held for the answer.
132
+ * A Control back key's byte right after ESC in a read is Ctrl+Alt with that key (ESC 0x18 is
133
+ * Ctrl+Alt+X), as the key parser reads it: the agent's, never the back key.
134
+ * The Alt+Shift arrow chords among `chords` are taken as the back key is: their one legacy
135
+ * sequence exactly (`CSI 1 ; 4 A` to `D`, nothing but Alt and Shift in the modifier), with what
136
+ * came after it in the read handed on as the rest.
137
+ * A read is never held back from the agent but for a beginning of the back key's own bytes or of
138
+ * such a chord's, or of a paste's start marker from its third byte: those wait for the next read,
139
+ * or until `timeoutAt()` (BACK_KEY_SPLIT_MS for a key's alone, the key parser's Esc timeout when
140
+ * they may begin a paste) hands them on as input, through `expire()` or the first read that comes
141
+ * later, which then never completes the key with them. An Alt+Shift arrow chord is one keypress,
142
+ * as the back key is: its bytes split across reads within BACK_KEY_SPLIT_MS are the chord, and
143
+ * split further apart they reach the agent as they came (Alt+Shift+Up for the agent's program),
144
+ * so a key of the agent's that begins as one does (Esc, `ESC [ 1`) waits no longer than that for
145
+ * its sake. A paste is held until its end marker; one that reaches PASTE_LIMIT is dropped whole, and one whose end has not come
106
146
  * when a read arrives PASTE_PAUSE_MS after the one before is given to the agent as what it held,
107
147
  * and that read is scanned anew, as the key parser abandons a stalled paste. */
108
- export function createThrough({ sequences, now }) {
148
+ export function createThrough({ sequences, now, keyboard = null, leader = null, chords = new Map(), answerBy = null }) {
109
149
  if (typeof now !== "function") throw new TypeError("createThrough needs an injected clock: { now: () => milliseconds }");
150
+ if (!(keyboard === null || keyboard === "asking" || confirmed(keyboard))) throw new TypeError("keyboard is null, \"asking\" or flags that hold flag 1");
110
151
  const keys = sequences.map((seq) => Uint8Array.from(seq));
152
+ /** The Alt+Shift arrow chords, `[bytes, does]`: their legacy sequence, read without the protocol. */
153
+ const arrows = [...chords].filter(([id]) => legacyChord(id)).map(([id, does]) => [escaped(`[1;4${LEGACY_CHORDS[id]}`), does]);
154
+ let kb = keyboard;
111
155
  /** The bytes held for the next read, since when, and how long they may wait: BACK_KEY_SPLIT_MS
112
156
  * when they are held only as a beginning of the back key, ESC_TIMEOUT_MS when they may begin a
113
157
  * paste's start marker (or its rest, see PASTE_HELD_FROM). */
114
- let held = new Uint8Array(0), heldAt = 0, heldFor = ESC_TIMEOUT_MS;
158
+ let held = new Uint8Array(0), heldAt = 0, heldFor = ESC_TIMEOUT_MS, answerHeld = false;
115
159
  /** The paste being read: its content so far (null when none; only the tail that may begin the
116
160
  * end marker once it went past the limit), and whether it did. */
117
161
  let paste = null, over = false, lastFeed = 0;
@@ -169,6 +213,7 @@ export function createThrough({ sequences, now }) {
169
213
  }
170
214
 
171
215
  function scan(out, data) {
216
+ if (confirmed(kb)) return scanKitty(out, data);
172
217
  for (let i = 0; i < data.length; i++) {
173
218
  const b = data[i];
174
219
  if (b === ESC && at(data, i, PASTE_START)) {
@@ -178,32 +223,98 @@ export function createThrough({ sequences, now }) {
178
223
  if (paste !== null) return; // the paste goes on in the next read
179
224
  return scan(out, rest);
180
225
  }
181
- const key = keys.find((seq) => seq[0] === b && at(data, i, seq));
226
+ // The protocol's answer, while it is awaited: the TUI's, never the agent's, and what follows
227
+ // it is read as it says.
228
+ const answer = kb === "asking" && b === ESC ? answerAt(data, i) : null;
229
+ if (answer !== null) {
230
+ if (i > 0) out.push({ input: data.subarray(0, i) });
231
+ out.push({ keyboard: answer.flags });
232
+ kb = confirmed(answer.flags) ? answer.flags : null;
233
+ return scan(out, data.subarray(answer.end));
234
+ }
235
+ // A Control back key right after ESC is Ctrl+Alt with it (ESC 0x18 is Ctrl+Alt+X), never the
236
+ // back key: it goes to the agent as it came, as the key parser reads it as ctrl+alt+x.
237
+ const key = keys.find((seq) => seq[0] === b && at(data, i, seq) && !(seq.length === 1 && i > 0 && data[i - 1] === ESC));
182
238
  if (key) {
183
239
  if (i > 0) out.push({ input: data.subarray(0, i) });
184
240
  out.push({ back: true, rest: data.subarray(i + key.length) });
185
241
  return;
186
242
  }
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).
243
+ const arrow = b === ESC ? arrows.find(([seq]) => at(data, i, seq)) : undefined;
244
+ if (arrow) {
245
+ if (i > 0) out.push({ input: data.subarray(0, i) });
246
+ out.push({ chord: arrow[1], rest: data.subarray(i + arrow[0].length) });
247
+ return;
248
+ }
249
+ // The read ends on what may be the beginning of the back key, of an Alt+Shift arrow chord, of
250
+ // a paste or of the answer awaited: held, as long as the longest that it may begin allows.
189
251
  const pasting = data.length - i >= PASTE_HELD_FROM && begins(data, i, PASTE_START);
190
- if (pasting || keys.some((seq) => begins(data, i, seq))) {
252
+ const answering = kb === "asking" && answerBegins(data, i);
253
+ const keying = keys.some((seq) => begins(data, i, seq)) || arrows.some(([seq]) => begins(data, i, seq));
254
+ if (pasting || answering || keying) {
191
255
  if (i > 0) out.push({ input: data.subarray(0, i) });
192
256
  held = Uint8Array.from(data.subarray(i));
193
257
  heldAt = now();
194
- heldFor = pasting ? ESC_TIMEOUT_MS : BACK_KEY_SPLIT_MS;
258
+ const asked = answerBy !== null ? Math.max(ESC_TIMEOUT_MS, answerBy - heldAt) : data.length - i < 3 ? BACK_KEY_SPLIT_MS : ESC_TIMEOUT_MS;
259
+ heldFor = Math.max(pasting ? ESC_TIMEOUT_MS : 0, answering ? asked : 0, keying ? BACK_KEY_SPLIT_MS : 0);
260
+ answerHeld = answering;
195
261
  return;
196
262
  }
197
263
  }
198
264
  if (data.length) out.push({ input: data });
199
265
  }
200
266
 
267
+ /** Under the protocol (see above): every sequence read, the rest handed on as it came. */
268
+ function scanKitty(out, data) {
269
+ let from = 0;
270
+ const handOn = (to) => { if (to > from) out.push({ input: data.subarray(from, to) }); from = to; };
271
+ const hold = (i) => { handOn(i); held = Uint8Array.from(data.subarray(i)); heldAt = now(); heldFor = Infinity; from = data.length; };
272
+ for (let i = 0; i < data.length; i++) {
273
+ if (data[i] !== ESC) continue;
274
+ if (at(data, i, PASTE_START)) {
275
+ handOn(i);
276
+ paste = new Uint8Array(0); over = false;
277
+ const rest = inPaste(out, data.subarray(i + PASTE_START.length));
278
+ if (paste !== null) return; // the paste goes on in the next read
279
+ return scan(out, rest);
280
+ }
281
+ if (i + 1 === data.length) return hold(i);
282
+ if (data[i + 1] !== 0x5b) continue; // ESC and not `[`: no key of the protocol's, as it came
283
+ let j = i + 2;
284
+ while (j < data.length && data[j] >= 0x20 && data[j] <= 0x3f) j++;
285
+ if (j === data.length) { if (j - i <= SEQUENCE_HELD) return hold(i); continue; }
286
+ if (data[j] < 0x40 || data[j] > 0x7e) continue; // no sequence: as it came
287
+ const params = String.fromCharCode(...data.subarray(i + 2, j)), final = String.fromCharCode(data[j]), end = j + 1;
288
+ handOn(i);
289
+ from = end;
290
+ i = end - 1;
291
+ let bytes, own = null;
292
+ if (final === "u") {
293
+ if (/^\?\d{1,3}$/.test(params)) continue; // the protocol's answer again: never the agent's
294
+ const key = kittyKey(params), id = kittyId(key);
295
+ if (id !== null && chords.has(id)) { out.push({ chord: chords.get(id), rest: data.subarray(end) }); return; }
296
+ own = id;
297
+ bytes = legacyBytes(key, kb);
298
+ } else bytes = legacySequence(params, final);
299
+ if (bytes === null) continue; // a key that sends nothing without the protocol: nothing
300
+ // What the bytes read as without the protocol: the back key, or an Alt+Shift arrow chord. A
301
+ // key with an id of its own (kittyId: Ctrl+Shift or Ctrl+Alt with a letter) is never the back
302
+ // key, though its legacy bytes may read as it (Ctrl+Shift+X is 0x18, as Ctrl+X): it types them.
303
+ const events = legacyEvents(bytes), id = events.length === 1 ? keyId(events[0]) : null;
304
+ if (id !== null && id === leader && own === null) { out.push({ back: true, rest: data.subarray(end) }); return; }
305
+ if (legacyChord(id) && chords.has(id)) { out.push({ chord: chords.get(id), rest: data.subarray(end) }); return; }
306
+ out.push({ input: bytes });
307
+ }
308
+ handOn(data.length);
309
+ }
310
+
201
311
  /** The held bytes, once they waited as long as they may at `t`: handed on as input, as one event
202
312
  * of their own (and noted, so a paste they begin is still raw), or nothing. */
203
313
  function lapse(t) {
204
314
  if (!held.length || t < heldAt + heldFor) return [];
205
315
  const out = [{ input: held }];
206
316
  held = new Uint8Array(0);
317
+ answerHeld = false;
207
318
  forwarded = handedOn(out);
208
319
  return out;
209
320
  }
@@ -212,6 +323,9 @@ export function createThrough({ sequences, now }) {
212
323
  feed(bytes) {
213
324
  if (!(bytes instanceof Uint8Array)) throw new TypeError("feed expects bytes (a Uint8Array)");
214
325
  const t = now();
326
+ // Bytes held for the answer that this read does not go on with, past the one-keypress window:
327
+ // their wait is over.
328
+ if (held.length && answerHeld && t >= heldAt + BACK_KEY_SPLIT_MS && !answerGoesOn(join(held, bytes))) heldFor = 0;
215
329
  // Held bytes whose wait is over are the agent's before this read is looked at, whether or not
216
330
  // expire() ran: a read that comes later never completes the back key with them (one keypress).
217
331
  const late = lapse(t), out = [];
@@ -225,7 +339,7 @@ export function createThrough({ sequences, now }) {
225
339
  data = inPaste(out, data);
226
340
  if (paste !== null) return out; // nothing was held: a paste and held bytes never meet
227
341
  }
228
- if (held.length) { data = join(held, data); held = new Uint8Array(0); }
342
+ if (held.length) { data = join(held, data); held = new Uint8Array(0); answerHeld = false; }
229
343
  // The rest of a start marker whose first bytes the last read handed on: the paste is raw.
230
344
  // A beginning of that rest waits for the next read, as a held key does.
231
345
  if (raw === null && forwarded > 0 && soon) {
@@ -236,11 +350,44 @@ export function createThrough({ sequences, now }) {
236
350
  forwarded = 0;
237
351
  if (raw !== null) data = inRaw(out, data);
238
352
  if (raw === null && data.length) scan(out, data);
239
- forwarded = handedOn(out);
353
+ // Under the protocol a paste's start marker is held whole: no paste is ever passed on raw.
354
+ forwarded = confirmed(kb) ? (handedOn(out), 0) : handedOn(out);
240
355
  // 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));
356
+ return [...late, ...out].map((event) => (event.input ? { input: Uint8Array.from(event.input) } : event.rest ? { ...event, rest: Uint8Array.from(event.rest) } : event));
242
357
  },
243
358
  expire() { return lapse(now()); },
244
- timeoutAt() { return held.length ? heldAt + heldFor : null; },
359
+ timeoutAt() { return held.length && Number.isFinite(heldFor) ? heldAt + heldFor : null; },
360
+ /** The answer is no longer awaited (none came in time): a late one goes on as it came, and what
361
+ * was held for it is handed on (the events answered). */
362
+ giveUp() {
363
+ if (kb === "asking") kb = null;
364
+ if (!answerHeld) return [];
365
+ heldFor = 0;
366
+ return lapse(now()).map((event) => ({ input: Uint8Array.from(event.input) }));
367
+ },
245
368
  };
246
369
  }
370
+
371
+ /** The most bytes of a `CSI` sequence held for its end under the protocol; a longer one is no key,
372
+ * and goes on as it came. */
373
+ const SEQUENCE_HELD = 64;
374
+ /** Whether `data` from `i` to its end may begin the protocol's answer `CSI ? flags u`: ESC, `ESC [`,
375
+ * or `ESC [ ?` and digits, short of the `u`. */
376
+ function answerBegins(data, i) {
377
+ const left = data.length - i;
378
+ if (left < 1 || left > 6 || data[i] !== ESC) return false;
379
+ if (left >= 2 && data[i + 1] !== 0x5b) return false;
380
+ if (left >= 3 && data[i + 2] !== 0x3f) return false;
381
+ for (let j = i + 3; j < data.length; j++) if (data[j] < 0x30 || data[j] > 0x39) return false;
382
+ return true;
383
+ }
384
+ /** Whether `data` begins with the answer, whole or begun. */
385
+ const answerGoesOn = (data) => answerAt(data, 0) !== null || answerBegins(data, 0);
386
+ /** The protocol's answer `CSI ? flags u` whole at `i`: `{ flags, end }`, or null. */
387
+ function answerAt(data, i) {
388
+ if (data[i + 1] !== 0x5b || data[i + 2] !== 0x3f) return null;
389
+ let j = i + 3;
390
+ while (j < data.length && j - i < 7 && data[j] >= 0x30 && data[j] <= 0x39) j++;
391
+ if (j === i + 3 || data[j] !== 0x75) return null;
392
+ return { flags: Number(String.fromCharCode(...data.subarray(i + 3, j))), end: j + 1 };
393
+ }
@@ -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
  }