@awebai/oats 0.64.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 (51) hide show
  1. package/README.md +11 -5
  2. package/bin/oats.mjs +109 -11
  3. package/docs/desktop-cli-api.md +88 -5
  4. package/docs/desktop.md +14 -5
  5. package/docs/implementation.md +26 -3
  6. package/docs/integrations.md +1 -1
  7. package/docs/official-catalog.md +2 -2
  8. package/docs/packages.md +7 -7
  9. package/docs/release-notes/v0.65.0.md +187 -0
  10. package/docs/release-notes/v0.66.0.md +183 -0
  11. package/docs/servers.md +2 -2
  12. package/docs/tui.md +548 -249
  13. package/docs/upgrading.md +1 -1
  14. package/docs/workspaces.md +132 -1
  15. package/lib/core.mjs +14 -4
  16. package/lib/deployments.mjs +341 -0
  17. package/lib/resolved-deployment.mjs +37 -0
  18. package/lib/workspace.mjs +2 -0
  19. package/package-catalog.json +2 -2
  20. package/package.json +1 -1
  21. package/packages/client/cli-locator.mjs +2 -2
  22. package/packages/client/deployment-label.mjs +2 -2
  23. package/packages/client/deployment-list-cli.mjs +98 -0
  24. package/packages/client/deployment-list.mjs +91 -0
  25. package/packages/client/keymap.mjs +133 -0
  26. package/packages/client/machine-contract.mjs +1 -5
  27. package/packages/client/own-codes.mjs +2 -0
  28. package/packages/client/panel-views.mjs +1 -1
  29. package/packages/client/workspace-admission.mjs +2 -1
  30. package/packages/record/bin/setup.mjs +10 -2
  31. package/packages/record/docs/capture-service.md +45 -6
  32. package/packages/record/lib/capture-service-install.mjs +6 -95
  33. package/packages/record/lib/capture-setup-write.mjs +233 -0
  34. package/packages/tui/README.md +10 -9
  35. package/packages/tui/lib/actions.mjs +89 -64
  36. package/packages/tui/lib/client.mjs +4 -1
  37. package/packages/tui/lib/config.mjs +184 -36
  38. package/packages/tui/lib/main.mjs +161 -40
  39. package/packages/tui/lib/model.mjs +73 -41
  40. package/packages/tui/lib/read.mjs +15 -45
  41. package/packages/tui/lib/store.mjs +174 -40
  42. package/packages/tui/lib/term/keys.mjs +135 -33
  43. package/packages/tui/lib/term/kitty.mjs +198 -0
  44. package/packages/tui/lib/term/through.mjs +160 -24
  45. package/packages/tui/lib/term/tty.mjs +43 -12
  46. package/packages/tui/lib/views/act.mjs +17 -13
  47. package/packages/tui/lib/views/frame.mjs +418 -421
  48. package/packages/tui/lib/views/help.mjs +90 -29
  49. package/packages/tui/lib/views/instances.mjs +38 -9
  50. package/packages/tui/lib/views/switcher.mjs +65 -21
  51. package/skills/oats-getting-started/SKILL.md +102 -32
@@ -1,11 +1,14 @@
1
1
  /** The key parser of `oats tui`: raw terminal input bytes in, key events out.
2
- * Pure: no IO, no timers, no imports; the only clock is the injected `now`.
3
- * It reads escape sequences and never writes one.
2
+ * Pure: no IO, no timers; the only clock is the injected `now`. Its one import is the reading of
3
+ * the kitty keyboard protocol (term/kitty.mjs). It reads escape sequences and never writes one.
4
4
  *
5
- * Events are plain objects of exactly three shapes:
5
+ * Events are plain objects of exactly four shapes:
6
6
  * a named key { name, ctrl, alt, shift }
7
7
  * a grapheme { text } or { text, alt: true }
8
- * a paste { paste } or { paste: "", truncated: true } */
8
+ * a paste { paste } or { paste: "", truncated: true }
9
+ * an answer { keyboard: flags }: the terminal's answer to the protocol's query (`CSI ? flags u`),
10
+ * while the parser waits for one */
11
+ import { confirmed, kittyId, kittyKey, legacyBytes, legacyParams } from "./kitty.mjs";
9
12
 
10
13
  export const ESC_TIMEOUT_MS = 50;
11
14
  export const PASTE_LIMIT = 1024 * 1024;
@@ -31,6 +34,7 @@ const TILDE_KEYS = Object.freeze({
31
34
  /** The Linux console sends F1..F5 as `ESC [ [ A` .. `ESC [ [ E`. */
32
35
  const LINUX_KEYS = Object.freeze({ __proto__: null, A: "f1", B: "f2", C: "f3", D: "f4", E: "f5" });
33
36
  const KEY_PARAMS = /^\d*(?:;\d*)?$/;
37
+ const NO_CHORDS = new Map();
34
38
  const GRAPHEMES = new Intl.Segmenter("en", { granularity: "grapheme" });
35
39
 
36
40
  const named = (name, ctrl = false, alt = false, shift = false) => ({ name, ctrl, alt, shift });
@@ -121,16 +125,56 @@ function decodeLenient(bytes, length) {
121
125
  return text + String.fromCodePoint.apply(null, points);
122
126
  }
123
127
 
128
+ /** The events a key's legacy bytes read as, whole: a fresh parser without the protocol, the Esc of a
129
+ * lone ESC taken at once (the bytes are one key, nothing follows them). */
130
+ export function legacyEvents(bytes) {
131
+ let t = 0;
132
+ const parser = createKeyParser({ now: () => t });
133
+ const events = parser.feed(bytes);
134
+ t = Infinity;
135
+ return [...events, ...parser.expire()];
136
+ }
137
+
124
138
  /** `now` is the injected clock in milliseconds; the parser reads it once per
125
139
  * `feed` and once per `expire`, and nowhere else.
126
140
  *
141
+ * `keyboard` is the kitty keyboard protocol (docs/tui.md, "Chords"): null, the default, without it;
142
+ * "asking" while the terminal's answer to the query is awaited; or the flags it answered once they
143
+ * hold flag 1. `chords` are the key ids the TUI binds as chords (packages/client/keymap.mjs CHORDS):
144
+ * a Map of key id to what it does, of which only the ids are read here. While asking, the answer `CSI ? flags u` is the event `{ keyboard: flags }`, and the bytes
145
+ * after it are read as it says: with flag 1 under the protocol, else as before. Under the protocol
146
+ * a `CSI … u` key is read as its legacy bytes are (term/kitty.mjs legacyBytes, legacyEvents above),
147
+ * so Ctrl+Shift+C is Ctrl+C as without it, and a chord as its own key id (`ctrl+shift+k`). An answer
148
+ * at any other time is dropped, as is a `u` key while not under the protocol. Under it a key in a
149
+ * legacy shape has its modifier made xterm's (term/kitty.mjs legacyParams: the lock keys dropped),
150
+ * and nothing is timed: a terminal under the protocol sends no lone ESC for a key, so an ESC, like
151
+ * any sequence begun, waits for what follows it however late that comes, and Esc is its own
152
+ * sequence.
153
+ * While asking, the answer may come split across reads, and over a slow link late: with `answerBy`
154
+ * (the clock time the run stops waiting for it) an ESC that a later read follows with `[` is kept as
155
+ * its possible beginning (a `candidate`) up to then. What turns out not to be the answer is read as
156
+ * it was typed: the Esc key, then `[` and the rest as text. A late ESC that `[` does not follow is
157
+ * the Esc key, as before, and so a lone ESC is, at `answerBy` at the latest.
158
+ *
127
159
  * feed(bytes) the events of these bytes, in order. Text is never held back:
128
160
  * a complete character is emitted by the feed that completes it.
129
161
  * expire() call when the clock reaches timeoutAt(): the Esc key, if a lone
130
162
  * ESC has waited ESC_TIMEOUT_MS; else nothing.
131
- * timeoutAt() the clock time at which expire() is due, or null. */
132
- export function createKeyParser({ now } = {}) {
163
+ * timeoutAt() the clock time at which expire() is due, or null.
164
+ * giveUp() the answer is no longer awaited (none came in time): a late one is dropped, and
165
+ * the events of what was kept for it are answered.
166
+ * keyboard the protocol as it is now: null, "asking" or the confirmed flags. */
167
+ export function createKeyParser({ now, keyboard = null, chords = NO_CHORDS, answerBy = null } = {}) {
133
168
  if (typeof now !== "function") throw new TypeError("createKeyParser needs an injected clock: { now: () => milliseconds }");
169
+ if (!(keyboard === null || keyboard === "asking" || confirmed(keyboard))) throw new TypeError("keyboard is null, \"asking\" or flags that hold flag 1");
170
+ if (!(chords instanceof Map)) throw new TypeError("chords is a Map of key ids");
171
+ let kb = keyboard;
172
+ /** An ESC kept past its timeout as the possible beginning of the answer, and the CSI it began. */
173
+ let candidate = false;
174
+ const asking = () => kb === "asking" && answerBy !== null;
175
+ /** When a lone ESC is the Esc key: after ESC_TIMEOUT_MS, and while the answer is awaited not
176
+ * before `answerBy` (a later read decides it sooner, see feed). */
177
+ const escDue = () => (asking() ? Math.max(escAt + ESC_TIMEOUT_MS, answerBy) : escAt + ESC_TIMEOUT_MS);
134
178
  const utf8 = utf8Decoder();
135
179
  let state = GROUND, out = [], feedAt = 0, lastFeedAt = 0;
136
180
  let run = ""; // consecutive printable code points of this feed, not yet cut into graphemes
@@ -189,6 +233,12 @@ export function createKeyParser({ now } = {}) {
189
233
  /** Inside a CSI, an SS3 or the Linux console form. A control byte is dropped and
190
234
  * the sequence goes on, an ESC starts over, a byte >= 0x80 aborts and is dropped. */
191
235
  const inSequence = (b) => {
236
+ // A candidate goes on only as the answer does: `?`, at most three digits, `u`.
237
+ if (candidate) {
238
+ const goesOn = seq === "" ? b === 0x3f : b === 0x75 ? /^\?\d{1,3}$/.test(seq) : b >= 0x30 && b <= 0x39 && /^\?\d{0,2}$/.test(seq);
239
+ if (!goesOn) { replay(); step(b); return; }
240
+ if (b === 0x75) candidate = false;
241
+ }
192
242
  if (b === ESC) { startEscape(); return; }
193
243
  if (b < 0x20 || b === 0x7f) return;
194
244
  if (b >= 0x80) { state = GROUND; return; }
@@ -206,10 +256,38 @@ export function createKeyParser({ now } = {}) {
206
256
  else if (seq === "" && final === "[") state = LINUX;
207
257
  else if (seq === "" && final === "M") { state = MOUSE; mouse = 3; } // X10 mouse report: 3 raw bytes follow
208
258
  else if (seq === "200" && final === "~") state = PASTE;
209
- else key = csiKey(seq, final);
259
+ else if (final === "u") { kittyEvents(seq); return; }
260
+ else key = csiKey(confirmed(kb) ? legacyParams(seq, final) : seq, final);
210
261
  if (key) emit(key);
211
262
  };
212
263
 
264
+ /** A candidate that is not the answer, as it was typed: the Esc key, then `[` and what followed. */
265
+ const replay = () => {
266
+ const typed = `[${seq ?? ""}`;
267
+ candidate = false; state = GROUND;
268
+ emit(named("escape"));
269
+ for (const c of typed) ground(c.charCodeAt(0));
270
+ };
271
+
272
+ /** A `CSI … u`: the protocol's answer while it is awaited, or a key under the protocol. */
273
+ const kittyEvents = (seq) => {
274
+ const answer = seq === null ? null : /^\?(\d{1,3})$/.exec(seq);
275
+ if (answer) {
276
+ if (kb !== "asking") { flush(); return; }
277
+ const flags = Number(answer[1]);
278
+ kb = confirmed(flags) ? flags : null;
279
+ emit({ keyboard: flags });
280
+ return;
281
+ }
282
+ const key = kb === null || kb === "asking" ? null : kittyKey(seq);
283
+ if (key === null) { flush(); return; }
284
+ const id = kittyId(key);
285
+ if (id !== null && chords.has(id)) { emit(named(key.code === 9 ? "tab" : String.fromCharCode(key.code), true, key.alt, key.shift)); return; }
286
+ const bytes = legacyBytes(key, kb);
287
+ if (bytes === null) { flush(); return; }
288
+ for (const event of legacyEvents(bytes)) emit(event);
289
+ };
290
+
213
291
  const endPaste = (truncated) => {
214
292
  emit(truncated ? { paste: "", truncated: true } : { paste: decodeLenient(held, size) });
215
293
  held = null; size = 0; over = false; matched = 0;
@@ -266,37 +344,46 @@ export function createKeyParser({ now } = {}) {
266
344
  if (state === PASTE && feedAt - lastFeedAt >= PASTE_PAUSE_MS) endPaste(true);
267
345
  };
268
346
 
347
+ /** One byte, in whatever state the parser is (a paste's content is read by inPaste). */
348
+ function step(b) {
349
+ switch (state) {
350
+ case GROUND: ground(b); break;
351
+ case ESCAPE: afterEscape(b); break;
352
+ case MOUSE:
353
+ if (b === ESC) startEscape();
354
+ else if (--mouse === 0) state = GROUND;
355
+ break;
356
+ case STRING: // swallowed as it streams, never held
357
+ if (b === ESC) state = STRING_ESC;
358
+ else if (bel && b === 0x07) state = GROUND;
359
+ break;
360
+ case STRING_ESC:
361
+ // `ESC \` is ST and ends the string. An ESC before anything else abandons
362
+ // the string and starts a new sequence, as in a CSI: the next key that
363
+ // sends an ESC recovers from a string whose end never arrives.
364
+ if (b === 0x5c) state = GROUND;
365
+ else if (b !== ESC) afterEscape(b);
366
+ break;
367
+ default: inSequence(b);
368
+ }
369
+ }
370
+
269
371
  return {
270
372
  feed(bytes) {
271
373
  if (!(bytes instanceof Uint8Array)) throw new TypeError("feed expects bytes (a Uint8Array)");
272
374
  feedAt = now();
273
- // A lone ESC that already waited its time is the Esc key; these bytes start fresh.
274
- if (state === ESCAPE && feedAt >= escAt + ESC_TIMEOUT_MS) { state = GROUND; emit(named("escape")); }
375
+ // A lone ESC that already waited its time is the Esc key; these bytes start fresh. Under the
376
+ // protocol nothing is timed. While the answer is awaited, one these bytes follow with `[` may
377
+ // begin it: kept, as a candidate.
378
+ if (state === ESCAPE && !confirmed(kb) && feedAt >= escAt + ESC_TIMEOUT_MS) {
379
+ if (asking() && feedAt < answerBy && bytes[0] === 0x5b) candidate = true;
380
+ else { state = GROUND; emit(named("escape")); }
381
+ }
275
382
  abandonStalledPaste();
276
383
  lastFeedAt = feedAt;
277
384
  for (let i = 0; i < bytes.length; i++) {
278
385
  if (state === PASTE) { i = inPaste(bytes, i) - 1; continue; }
279
- const b = bytes[i];
280
- switch (state) {
281
- case GROUND: ground(b); break;
282
- case ESCAPE: afterEscape(b); break;
283
- case MOUSE:
284
- if (b === ESC) startEscape();
285
- else if (--mouse === 0) state = GROUND;
286
- break;
287
- case STRING: // swallowed as it streams, never held
288
- if (b === ESC) state = STRING_ESC;
289
- else if (bel && b === 0x07) state = GROUND;
290
- break;
291
- case STRING_ESC:
292
- // `ESC \` is ST and ends the string. An ESC before anything else abandons
293
- // the string and starts a new sequence, as in a CSI: the next key that
294
- // sends an ESC recovers from a string whose end never arrives.
295
- if (b === 0x5c) state = GROUND;
296
- else if (b !== ESC) afterEscape(b);
297
- break;
298
- default: inSequence(b);
299
- }
386
+ step(bytes[i]);
300
387
  }
301
388
  flush();
302
389
  const events = out;
@@ -304,14 +391,29 @@ export function createKeyParser({ now } = {}) {
304
391
  return events;
305
392
  },
306
393
  expire() {
307
- if (state !== ESCAPE || now() < escAt + ESC_TIMEOUT_MS) return [];
394
+ if (state !== ESCAPE || confirmed(kb) || now() < escDue()) return [];
308
395
  state = GROUND;
309
396
  return [named("escape")];
310
397
  },
311
- /** Only a lone ESC has a deadline. Every other incomplete sequence waits for its end. */
398
+ /** Only a lone ESC has a deadline, and none under the protocol. Every other incomplete sequence
399
+ * waits for its end. */
312
400
  timeoutAt() {
313
- return state === ESCAPE ? escAt + ESC_TIMEOUT_MS : null;
401
+ return state === ESCAPE && !confirmed(kb) ? escDue() : null;
402
+ },
403
+ giveUp() {
404
+ if (kb !== "asking") return [];
405
+ kb = null;
406
+ if (candidate) replay();
407
+ else if (state === ESCAPE && now() >= escAt + ESC_TIMEOUT_MS) { state = GROUND; emit(named("escape")); }
408
+ // An answer begun in one read whose end never came: no key sends `CSI ?`, so it is dropped,
409
+ // and the next key is read afresh.
410
+ else if (state === CSI && seq !== null && /^\?\d{0,3}$/.test(seq)) state = GROUND;
411
+ flush();
412
+ const events = out;
413
+ out = [];
414
+ return events;
314
415
  },
416
+ get keyboard() { return kb; },
315
417
  };
316
418
  }
317
419
 
@@ -0,0 +1,198 @@
1
+ /** The kitty keyboard protocol, as `oats tui` reads it (docs/tui.md, "Chords"): the flags it asks
2
+ * for, a `CSI … u` key read, and the bytes the same key sends without the protocol. Pure: no IO,
3
+ * no state, no imports, no global; as the key parser's one import it is held to the parser's rule
4
+ * (packages/tui/test/keys.test.mjs). The guard (term/tty.mjs) pushes, queries and pops the
5
+ * protocol; the key parser (term/keys.mjs) and the scanner of what is typed into a terminal
6
+ * (term/through.mjs) read what comes back with these.
7
+ *
8
+ * Under the protocol a terminal sends Esc, and every key held with Ctrl or Alt, as
9
+ * `CSI code[:shifted[:base]] [; mods] u`: one sequence, never an ESC alone, so Alt+O and Esc then
10
+ * `o` are told apart exactly. Everything else (text, Shift and a character, Enter, Tab and
11
+ * Backspace alone, the arrows, the function keys) keeps the bytes it has without it.
12
+ *
13
+ * What the TUI reads is what the legacy bytes of a key read as, with two exceptions: the chords
14
+ * (packages/client/keymap.mjs CHORDS), which keep their own key id (`ctrl+shift+k`), and the exact
15
+ * Alt and Esc above. What it types into an agent is those legacy bytes (`legacyBytes`), so the
16
+ * agent's program gets what it gets without the protocol. */
17
+
18
+ /** The flags pushed (`CSI > flags u`): 1, disambiguate the escape codes, and 4, report alternate
19
+ * keys, so the shifted key a key with Shift makes on the person's layout comes with it. The
20
+ * maintainer's decision of 2026-10-19; set it to 1 and flag 4 is never asked for: the US table
21
+ * below is then the only way to the shifted key. No other flag (2, 8, 16) is ever asked for. */
22
+ export const KEYBOARD_FLAGS = 1 | 4;
23
+ /** The flag the TUI needs confirmed to read the protocol at all, and the one that makes the shifted
24
+ * key exact. */
25
+ export const DISAMBIGUATE = 1, ALTERNATE_KEYS = 4;
26
+
27
+ /** Whether the flags a terminal confirmed (its `CSI ? flags u` answer) let the TUI read the
28
+ * protocol: the answer must hold flag 1. Any other answer is as no answer. */
29
+ export const confirmed = (flags) => Number.isInteger(flags) && (flags & DISAMBIGUATE) !== 0;
30
+
31
+ /** `code[:shifted[:base]][;mods]`: the parameters of a `CSI … u` key under flags 1 and 4. Flag 4
32
+ * puts the subfields on every key, so they are taken on every one; the base-layout key (the
33
+ * third) is read and ignored. No event type, no text: flags 2 and 16 are never asked for. */
34
+ const PARAMS = /^(\d{1,7})(?::(\d{0,7})(?::\d{0,7})?)?(?:;(\d{1,3}))?$/;
35
+ /** The modifier bits after the 1 is taken away: Shift, Alt, Ctrl. Super, Hyper, Meta and the lock
36
+ * bits are dropped: a terminal sends a key held with them as it sends the key without them. */
37
+ const SHIFT = 1, ALT = 2, CTRL = 4;
38
+
39
+ /** A `CSI … u` key's parameters (the bytes between `CSI` and `u`) as `{ code, shifted, shift, alt,
40
+ * ctrl }`, or null when they are no key: a reply (`?flags`), an event type or a text field, a
41
+ * modifier outside 1..256, a code that is no Unicode scalar. `shifted` is the alternate key flag 4
42
+ * reports, or null when it is absent or empty. */
43
+ export function kittyKey(params) {
44
+ const match = typeof params === "string" ? PARAMS.exec(params) : null;
45
+ if (!match) return null;
46
+ const code = Number(match[1]), shifted = match[2] ? Number(match[2]) : null, m = match[3] === undefined ? 1 : Number(match[3]);
47
+ if (!scalar(code) || (shifted !== null && !scalar(shifted)) || !(m >= 1 && m <= 256)) return null;
48
+ const bits = m - 1;
49
+ return { code, shifted, shift: (bits & SHIFT) !== 0, alt: (bits & ALT) !== 0, ctrl: (bits & CTRL) !== 0 };
50
+ }
51
+ const scalar = (cp) => Number.isInteger(cp) && cp > 0 && cp <= 0x10ffff && !(cp >= 0xd800 && cp <= 0xdfff);
52
+
53
+ /** The key id a key held with Ctrl keeps under the protocol, the chords' spelling
54
+ * (packages/client/keymap.mjs: `ctrl+shift+k`, `ctrl+tab`): Ctrl, Alt and Shift, in that order,
55
+ * then a letter or Tab. Null for every other key: those are read as their legacy bytes are. */
56
+ export function kittyId(key) {
57
+ if (key === null || !key.ctrl) return null;
58
+ const name = key.code === 9 ? "tab" : key.code >= 0x61 && key.code <= 0x7a ? String.fromCharCode(key.code) : null;
59
+ return name === null ? null : `ctrl+${key.alt ? "alt+" : ""}${key.shift ? "shift+" : ""}${name}`;
60
+ }
61
+
62
+ const ESC = 0x1b;
63
+ /** The functional keys of the protocol's private-use range the TUI forwards: the keypad, as the key
64
+ * each one is without the protocol. Every other code of that range (F13 and above, the media keys,
65
+ * the lock and modifier keys, Menu) is a key a legacy terminal sends no bytes of its own for, or the
66
+ * TUI reads as no key: nothing. */
67
+ const KEYPAD = Object.freeze({
68
+ __proto__: null,
69
+ 57399: "0", 57400: "1", 57401: "2", 57402: "3", 57403: "4", 57404: "5", 57405: "6", 57406: "7", 57407: "8", 57408: "9",
70
+ 57409: ".", 57410: "/", 57411: "*", 57412: "-", 57413: "+", 57414: "enter", 57415: "=", 57416: ",",
71
+ 57417: "left", 57418: "right", 57419: "up", 57420: "down", 57421: "pageup", 57422: "pagedown",
72
+ 57423: "home", 57424: "end", 57425: "insert", 57426: "delete", 57427: "begin",
73
+ });
74
+ const PRIVATE_FIRST = 57344, PRIVATE_LAST = 63743;
75
+ /** The legacy form of a named key: `CSI <final>` / `CSI 1 ; m <final>`, or `CSI n ~` / `CSI n ; m ~`. */
76
+ const LETTER = Object.freeze({ __proto__: null, up: "A", down: "B", right: "C", left: "D", home: "H", end: "F", begin: "E" });
77
+ const TILDE = Object.freeze({ __proto__: null, insert: 2, delete: 3, pageup: 5, pagedown: 6 });
78
+
79
+ /** Shift on the 21 keys of the US layout that are not letters: the character it makes there. Only
80
+ * where flag 4 is not confirmed (the terminal answered flag 1 alone), and then it is the one limit
81
+ * of the rule that what is typed into an agent is the bytes of the same key without the protocol:
82
+ * on another layout Shift makes another character (docs/tui.md, "Chords"). */
83
+ export const US_SHIFTED = Object.freeze({
84
+ __proto__: null,
85
+ "`": "~", 1: "!", 2: "@", 3: "#", 4: "$", 5: "%", 6: "^", 7: "&", 8: "*", 9: "(", 0: ")",
86
+ "-": "_", "=": "+", "[": "{", "]": "}", "\\": "|", ";": ":", "'": "\"", ",": "<", ".": ">", "/": "?",
87
+ });
88
+
89
+ /** Ctrl with a character, as a legacy terminal sends it: the letters and `@ [ \ ] ^ _` (and `?`,
90
+ * `~`, Space, and the digits 2 to 8, which a terminal maps as xterm does) as their C0 byte or DEL;
91
+ * every other character as itself. */
92
+ function ctrlByte(ch) {
93
+ const c = ch.codePointAt(0);
94
+ if ((c >= 0x61 && c <= 0x7a) || (c >= 0x40 && c <= 0x5f)) return c & 0x1f;
95
+ const mapped = { " ": 0, 2: 0, 3: 0x1b, 4: 0x1c, 5: 0x1d, 6: 0x1e, 7: 0x1f, 8: 0x7f, "/": 0x1f, "?": 0x7f, "~": 0x1e }[ch];
96
+ return mapped ?? null;
97
+ }
98
+
99
+ /** A string's UTF-8 bytes. Its code points are Unicode scalars (kittyKey), so no surrogate is met. */
100
+ function utf8(text) {
101
+ const bytes = [];
102
+ for (const ch of text) {
103
+ const c = ch.codePointAt(0);
104
+ if (c < 0x80) bytes.push(c);
105
+ else if (c < 0x800) bytes.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f));
106
+ else if (c < 0x10000) bytes.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));
107
+ else bytes.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));
108
+ }
109
+ return bytes;
110
+ }
111
+ const csi = (rest) => [ESC, 0x5b, ...Array.from(rest, (c) => c.charCodeAt(0))];
112
+
113
+ /** The character Shift makes on `code`: the alternate key flag 4 reported (only while Shift is held:
114
+ * `shifted` is read only then), else a letter's capital, else, with flag 4 not confirmed, the US
115
+ * layout's (US_SHIFTED), else the character itself. */
116
+ function shiftedText(key, flags) {
117
+ const ch = String.fromCodePoint(key.code);
118
+ if (!key.shift) return ch;
119
+ if (key.shifted !== null && (flags & ALTERNATE_KEYS) !== 0) return String.fromCodePoint(key.shifted);
120
+ const upper = ch.toUpperCase();
121
+ if (upper !== ch && [...upper].length === 1) return upper;
122
+ return (flags & ALTERNATE_KEYS) === 0 ? US_SHIFTED[ch] ?? ch : ch;
123
+ }
124
+
125
+ /** The bytes the key `key` (kittyKey's) sends WITHOUT the protocol, the legacy encoding of xterm and
126
+ * of the terminals that follow it, as a Uint8Array; null for a key that sends none. `flags` are the
127
+ * confirmed ones: with flag 4, Shift's character is the one the terminal reported.
128
+ * Esc ESC; Enter CR; Tab TAB, with Shift `CSI Z`; Backspace DEL, with Ctrl BS; Space SP, with Ctrl
129
+ * NUL; a character with Shift its shifted character, with Ctrl its C0 byte (ctrlByte); a keypad key
130
+ * as the key it is; Alt puts ESC before any of these. The arrows, Home, End, Insert, Delete,
131
+ * PageUp, PageDown and Begin are `CSI` forms with the modifier as their parameter (1 + Shift 1 +
132
+ * Alt 2 + Ctrl 4), as xterm sends them. */
133
+ export function legacyBytes(key, flags) {
134
+ if (key === null) return null;
135
+ let { code } = key;
136
+ if (code >= PRIVATE_FIRST && code <= PRIVATE_LAST) {
137
+ const pad = KEYPAD[code];
138
+ if (pad === undefined) return null;
139
+ if (pad === "enter") code = 13;
140
+ else if (pad.length === 1) code = pad.codePointAt(0);
141
+ else {
142
+ const m = 1 + (key.shift ? SHIFT : 0) + (key.alt ? ALT : 0) + (key.ctrl ? CTRL : 0);
143
+ const bytes = pad in LETTER ? csi(m === 1 ? LETTER[pad] : `1;${m}${LETTER[pad]}`) : csi(m === 1 ? `${TILDE[pad]}~` : `${TILDE[pad]};${m}~`);
144
+ return Uint8Array.from(bytes);
145
+ }
146
+ key = { ...key, code, shifted: null, shift: false, ctrl: false }; // the keypad's own character, which Shift and Ctrl leave as it is
147
+ }
148
+ let bytes;
149
+ if (code === 27) bytes = [ESC];
150
+ else if (code === 13) bytes = [0x0d];
151
+ else if (code === 9) bytes = key.shift ? csi("Z") : [0x09];
152
+ else if (code === 127 || code === 8) bytes = [key.ctrl ? 0x08 : 0x7f];
153
+ else if (code === 32) bytes = [key.ctrl ? 0x00 : 0x20];
154
+ else if (code < 0x20 || code === 0x7f || (code >= 0x80 && code <= 0x9f)) return null;
155
+ else {
156
+ const text = shiftedText(key, flags);
157
+ const byte = key.ctrl ? ctrlByte(text) : null;
158
+ bytes = byte === null ? utf8(text) : [byte];
159
+ }
160
+ return Uint8Array.from(key.alt ? [ESC, ...bytes] : bytes);
161
+ }
162
+
163
+ /** The finals of the keys a terminal sends in the legacy shapes under the protocol: `CSI 1 ; m X`
164
+ * (the arrows, Home, End, Begin, F1 to F4) and `CSI n ; m ~`. Not `R`: under the protocol F3 is
165
+ * `CSI 13 ~`, and `CSI row ; col R` is a cursor report, which stays no key. */
166
+ const KEY_FINALS = "ABCDEFHPQS~";
167
+ /** The parameters of such a key with the protocol's modifier made xterm's: the protocol reports the
168
+ * lock keys and Super, Hyper and Meta in the modifier (Up with Caps Lock is `CSI 1 ; 65 A`), where
169
+ * a terminal without it sends the key as it is without them (`CSI A`). Shift, Alt and Ctrl stay;
170
+ * a modifier of none is left out, with the `1` before a letter (`CSI 1 ; 69 A` is `CSI 1 ; 5 A`,
171
+ * `CSI 15 ; 65 ~` is `CSI 15 ~`). Every other sequence's parameters are answered as they are. */
172
+ export function legacyParams(params, final) {
173
+ const match = typeof params === "string" && final.length === 1 && KEY_FINALS.includes(final) ? /^(\d*);(\d{1,3})$/.exec(params) : null;
174
+ if (!match) return params;
175
+ const m = Number(match[2]);
176
+ if (!(m >= 1 && m <= 256)) return params;
177
+ const bits = (m - 1) & (SHIFT | ALT | CTRL);
178
+ if (bits !== 0) return `${match[1]};${bits + 1}`;
179
+ if (final === "~") return match[1];
180
+ return match[1] === "" || match[1] === "1" ? "" : params;
181
+ }
182
+
183
+ /** A complete `CSI` sequence other than a `u` key, as a terminal sends it under the protocol, made
184
+ * the bytes it is without it: its modifier made xterm's (legacyParams); F1, F2 and F4 unmodified
185
+ * come as `CSI P`, `CSI Q`, `CSI S` (legacy `SS3 P`, `SS3 Q`, `SS3 S`), and F3 as `CSI 13 ~` (legacy
186
+ * `SS3 R`, and `CSI 1 ; m R` with a modifier). Every other sequence is the same bytes. `params` are
187
+ * the bytes between `CSI` and `final`. */
188
+ export function legacySequence(given, final) {
189
+ const params = legacyParams(given, final);
190
+ const ss3 = (letter) => Uint8Array.of(ESC, 0x4f, letter.charCodeAt(0));
191
+ if ((params === "" || params === "1" || params === "1;1") && "PQS".includes(final) && final !== "") return ss3(final);
192
+ if (final === "~") {
193
+ if (params === "13" || params === "13;1") return ss3("R");
194
+ const modified = /^13;(\d{1,3})$/.exec(params);
195
+ if (modified) return Uint8Array.from(csi(`1;${modified[1]}R`));
196
+ }
197
+ return Uint8Array.from(csi(`${params}${final}`));
198
+ }