@awebai/oats 0.51.0 → 0.53.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 (166) hide show
  1. package/README.md +3 -1
  2. package/bin/oats.mjs +407 -123
  3. package/docs/capabilities.md +75 -6
  4. package/docs/configuration.md +200 -91
  5. package/docs/desktop-cli-api.md +1563 -113
  6. package/docs/desktop-instance-start.md +69 -0
  7. package/docs/desktop.md +10 -7
  8. package/docs/execution-targets.md +145 -58
  9. package/docs/first-team.md +3 -1
  10. package/docs/harness-trust.md +50 -2
  11. package/docs/implementation.md +238 -17
  12. package/docs/integrations.md +13 -9
  13. package/docs/knowledge-reference/acceptance.md +1 -0
  14. package/docs/knowledge-reference/harvester.md +5 -3
  15. package/docs/knowledge-reference/model.md +5 -3
  16. package/docs/knowledge-theory.md +1 -1
  17. package/docs/knowledge.md +25 -2
  18. package/docs/launch-prompt-completion.md +50 -48
  19. package/docs/macos-test-runs.md +246 -0
  20. package/docs/oats-local.schema.json +4 -3
  21. package/docs/official-catalog.md +5 -5
  22. package/docs/packages.md +14 -14
  23. package/docs/release-lane.md +225 -11
  24. package/docs/release-notes/v0.44.0.md +1 -1
  25. package/docs/release-notes/v0.52.0.md +933 -0
  26. package/docs/release-notes/v0.53.0.md +1274 -0
  27. package/docs/schedules.md +97 -4
  28. package/docs/souls-and-instances.md +332 -40
  29. package/docs/tui.md +584 -0
  30. package/docs/upgrading.md +298 -0
  31. package/docs/workspaces.md +3 -3
  32. package/lib/automations.mjs +22 -22
  33. package/lib/claim.mjs +278 -49
  34. package/lib/config-data.mjs +4 -1
  35. package/lib/core.mjs +1282 -289
  36. package/lib/errors.mjs +170 -0
  37. package/lib/harness-trust-write.mjs +68 -27
  38. package/lib/harness-trust.mjs +34 -16
  39. package/lib/instance-events.mjs +19 -1
  40. package/lib/instance-git.mjs +39 -3
  41. package/lib/instance-inspect.mjs +45 -17
  42. package/lib/instance-lifecycle.mjs +306 -57
  43. package/lib/instance-resolution.mjs +59 -6
  44. package/lib/launch-preference.mjs +236 -9
  45. package/lib/launch-prompt-completion.mjs +7 -43
  46. package/lib/launch-prompt-evidence.mjs +14 -7
  47. package/lib/launch-prompt-fixtures/README.md +86 -152
  48. package/lib/launch-prompt-fixtures/dev-channel-confirmation.json +50 -0
  49. package/lib/launch-prompt-fixtures.mjs +122 -109
  50. package/lib/launch-prompt-transport.mjs +2 -56
  51. package/lib/launch-prompts.mjs +102 -100
  52. package/lib/local-edit.mjs +118 -0
  53. package/lib/packages.mjs +13 -4
  54. package/lib/pi-bridge.mjs +308 -0
  55. package/lib/refused-text.mjs +11 -0
  56. package/lib/remote.mjs +190 -25
  57. package/lib/resolve.mjs +2 -1
  58. package/lib/retained-after-retire.mjs +2 -2
  59. package/lib/retire-output.mjs +12 -1
  60. package/lib/schedule-host.mjs +125 -22
  61. package/lib/schedule.mjs +73 -24
  62. package/lib/shell-word.mjs +13 -0
  63. package/lib/soul-launch-verbs.mjs +153 -0
  64. package/lib/stable-node.mjs +62 -0
  65. package/lib/system-tools.mjs +39 -0
  66. package/lib/teams-verbs.mjs +18 -46
  67. package/lib/tmux-server-scope.mjs +62 -0
  68. package/lib/triggers.mjs +4 -4
  69. package/lib/workspace.mjs +54 -30
  70. package/lib/worktree-hooks.mjs +98 -20
  71. package/lib/worktree.mjs +83 -24
  72. package/package-catalog.json +4 -4
  73. package/package.json +8 -2
  74. package/packages/client/attach-exit.mjs +25 -0
  75. package/packages/client/capability-show-contract.mjs +230 -0
  76. package/packages/client/capability-warnings-contract.mjs +57 -0
  77. package/packages/client/cli-adapter.mjs +561 -0
  78. package/packages/client/cli-environment.mjs +53 -0
  79. package/packages/client/cli-locator.mjs +253 -0
  80. package/packages/client/cli-probe-contract.mjs +47 -0
  81. package/packages/client/client-terms.mjs +60 -0
  82. package/packages/client/deployment-contract.mjs +72 -0
  83. package/packages/client/deployment-data.mjs +483 -0
  84. package/packages/client/deployment-facts.mjs +95 -0
  85. package/packages/client/deployment-label.mjs +76 -0
  86. package/packages/client/deployment-observer.mjs +89 -0
  87. package/packages/client/deployment-panel.mjs +180 -0
  88. package/packages/client/deployment-read-cli.mjs +57 -0
  89. package/packages/client/display-text.mjs +50 -0
  90. package/packages/client/harness-names.mjs +30 -0
  91. package/packages/client/inspect-contract.mjs +62 -0
  92. package/packages/client/instance-acts.mjs +90 -0
  93. package/packages/client/instance-admission.mjs +45 -0
  94. package/packages/client/instance-events-contract.mjs +76 -0
  95. package/packages/client/instance-git-contract.mjs +80 -0
  96. package/packages/client/instance-presentation.mjs +86 -0
  97. package/packages/client/instance-tree.mjs +462 -0
  98. package/packages/client/kernel-environment.mjs +11 -0
  99. package/packages/client/kernel-lines.mjs +31 -0
  100. package/packages/client/kernel-made.mjs +23 -0
  101. package/packages/client/launch-contract.mjs +51 -0
  102. package/packages/client/launch-prompt-outcome.mjs +200 -0
  103. package/packages/client/lifecycle-cli.mjs +61 -0
  104. package/packages/client/lifecycle-contract.mjs +413 -0
  105. package/packages/client/liveness-main.mjs +10 -0
  106. package/packages/client/liveness.mjs +48 -0
  107. package/packages/client/machine-contract.mjs +123 -0
  108. package/packages/client/own-codes.mjs +31 -0
  109. package/packages/client/own-environment.mjs +22 -0
  110. package/packages/client/panel-views.mjs +293 -0
  111. package/packages/client/readiness-contract.mjs +174 -0
  112. package/packages/client/refresh-loop.mjs +52 -0
  113. package/packages/client/remote-address.mjs +151 -0
  114. package/packages/client/remote-identity-memory.mjs +94 -0
  115. package/packages/client/remote-roster.mjs +153 -0
  116. package/packages/client/roster-sections.mjs +80 -0
  117. package/packages/client/session-attach.mjs +175 -0
  118. package/packages/client/spawn-apply-cli.mjs +104 -0
  119. package/packages/client/spawn-apply-contract.mjs +195 -0
  120. package/packages/client/spawn-decision.mjs +46 -0
  121. package/packages/client/spawn-messages.mjs +142 -0
  122. package/packages/client/spawn-preview-cli.mjs +38 -0
  123. package/packages/client/spawn-preview-contract.mjs +318 -0
  124. package/packages/client/team-members.mjs +41 -0
  125. package/packages/client/team-rows.mjs +45 -0
  126. package/packages/client/terminal-contract.mjs +57 -0
  127. package/packages/client/terminal-exec.mjs +21 -0
  128. package/packages/client/tmux-status.mjs +66 -0
  129. package/packages/client/waiting-on-you.mjs +88 -0
  130. package/packages/client/workspace-admission.mjs +45 -0
  131. package/packages/client/workspace-choices.mjs +95 -0
  132. package/packages/client/workspace-cli.mjs +142 -0
  133. package/packages/client/workspace-views.mjs +183 -0
  134. package/packages/record/README.md +21 -0
  135. package/packages/record/bin/setup.mjs +108 -15
  136. package/packages/tui/README.md +64 -0
  137. package/packages/tui/bin/tui.mjs +7 -0
  138. package/packages/tui/lib/actions.mjs +44 -0
  139. package/packages/tui/lib/client.mjs +35 -0
  140. package/packages/tui/lib/config.mjs +151 -0
  141. package/packages/tui/lib/main.mjs +176 -0
  142. package/packages/tui/lib/model.mjs +392 -0
  143. package/packages/tui/lib/read.mjs +473 -0
  144. package/packages/tui/lib/store.mjs +364 -0
  145. package/packages/tui/lib/term/keys.mjs +367 -0
  146. package/packages/tui/lib/term/screen.mjs +134 -0
  147. package/packages/tui/lib/term/style.mjs +43 -0
  148. package/packages/tui/lib/term/text.mjs +109 -0
  149. package/packages/tui/lib/term/tty.mjs +178 -0
  150. package/packages/tui/lib/term/width.mjs +124 -0
  151. package/packages/tui/lib/views/detail.mjs +46 -0
  152. package/packages/tui/lib/views/frame.mjs +256 -0
  153. package/packages/tui/lib/views/help.mjs +140 -0
  154. package/packages/tui/lib/views/instances.mjs +137 -0
  155. package/packages/tui/lib/views/scroll.mjs +19 -0
  156. package/packages/tui/lib/views/switcher.mjs +97 -0
  157. package/packages/tui/package.json +8 -0
  158. package/skills/oats-getting-started/SKILL.md +30 -23
  159. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-05-channel-seeded.txt +0 -35
  160. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-06-first-after-channel.txt +0 -35
  161. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-07-after-channel-200ms.txt +0 -35
  162. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-08-installed-after-channel-200ms.txt +0 -35
  163. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/manifest.json +0 -77
  164. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/max-bypass-source.json +0 -88
  165. package/lib/launch-prompt-fixtures/structural-completion.json +0 -205
  166. package/lib/launch-prompt-policy.mjs +0 -87
@@ -0,0 +1,367 @@
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.
4
+ *
5
+ * Events are plain objects of exactly three shapes:
6
+ * a named key { name, ctrl, alt, shift }
7
+ * a grapheme { text } or { text, alt: true }
8
+ * a paste { paste } or { paste: "", truncated: true } */
9
+
10
+ export const ESC_TIMEOUT_MS = 50;
11
+ export const PASTE_LIMIT = 1024 * 1024;
12
+ export const PASTE_PAUSE_MS = 1000;
13
+
14
+ /** Parameter and intermediate bytes held for one CSI or SS3. A longer sequence
15
+ * is discarded as it streams: input can never grow the parser. */
16
+ const SEQUENCE_LIMIT = 64;
17
+ const ESC = 0x1b;
18
+ const PASTE_END = Uint8Array.of(ESC, 0x5b, 0x32, 0x30, 0x31, 0x7e); // CSI 201 ~
19
+
20
+ const GROUND = 0, ESCAPE = 1, CSI = 2, SS3 = 3, LINUX = 4, MOUSE = 5, STRING = 6, STRING_ESC = 7, PASTE = 8;
21
+
22
+ const LETTER_KEYS = Object.freeze({
23
+ __proto__: null,
24
+ A: "up", B: "down", C: "right", D: "left", H: "home", F: "end", P: "f1", Q: "f2", R: "f3", S: "f4",
25
+ });
26
+ const TILDE_KEYS = Object.freeze({
27
+ __proto__: null,
28
+ 1: "home", 7: "home", 4: "end", 8: "end", 2: "insert", 3: "delete", 5: "pageup", 6: "pagedown",
29
+ 11: "f1", 12: "f2", 13: "f3", 14: "f4", 15: "f5", 17: "f6", 18: "f7", 19: "f8", 20: "f9", 21: "f10", 23: "f11", 24: "f12",
30
+ });
31
+ /** The Linux console sends F1..F5 as `ESC [ [ A` .. `ESC [ [ E`. */
32
+ const LINUX_KEYS = Object.freeze({ __proto__: null, A: "f1", B: "f2", C: "f3", D: "f4", E: "f5" });
33
+ const KEY_PARAMS = /^\d*(?:;\d*)?$/;
34
+ const GRAPHEMES = new Intl.Segmenter("en", { granularity: "grapheme" });
35
+
36
+ const named = (name, ctrl = false, alt = false, shift = false) => ({ name, ctrl, alt, shift });
37
+
38
+ /** The key of a C0 byte or DEL, or null for a byte that is no key (NUL, 0x1c..0x1f). */
39
+ function c0Key(b) {
40
+ if (b === 0x0d || b === 0x0a) return named("enter");
41
+ if (b === 0x09) return named("tab");
42
+ if (b === 0x7f || b === 0x08) return named("backspace");
43
+ return b >= 0x01 && b <= 0x1a ? named(String.fromCharCode(b + 0x60), true) : null;
44
+ }
45
+
46
+ /** xterm's modifier parameter: m - 1 is a bit mask (1 shift, 2 alt, 4 ctrl, 8 meta,
47
+ * ignored). A value outside 1..16 is no key report, so the sequence is dropped:
48
+ * that keeps most cursor position reports (`CSI row ; col R`) from reading as F3. */
49
+ function modified(name, param, shift = false) {
50
+ const m = param === "" ? 1 : Number(param);
51
+ if (!(m >= 1 && m <= 16)) return null;
52
+ return named(name, ((m - 1) & 4) !== 0, ((m - 1) & 2) !== 0, shift || ((m - 1) & 1) !== 0);
53
+ }
54
+
55
+ /** A complete CSI as a key, or null when it is not one (then it is dropped whole).
56
+ * Only `CSI [n] [; m] final` is a key: a private marker, an intermediate or a
57
+ * third parameter makes it a terminal report. */
58
+ function csiKey(params, final) {
59
+ if (params === null || !KEY_PARAMS.test(params)) return null;
60
+ const [first, mod = ""] = params.split(";");
61
+ if (final === "~") return TILDE_KEYS[Number(first)] ? modified(TILDE_KEYS[Number(first)], mod) : null;
62
+ if (first !== "" && Number(first) !== 1) return null;
63
+ if (final === "Z") return modified("tab", mod, true);
64
+ return LETTER_KEYS[final] ? modified(LETTER_KEYS[final], mod) : null;
65
+ }
66
+
67
+ /** `ESC O X`, and the modifier forms `ESC O m X` and `ESC O 1 ; m X`. */
68
+ function ss3Key(params, final) {
69
+ if (params === null || !KEY_PARAMS.test(params) || !LETTER_KEYS[final]) return null;
70
+ return modified(LETTER_KEYS[final], params.slice(params.lastIndexOf(";") + 1));
71
+ }
72
+
73
+ const MORE = -1, BAD = -2, RETRY = -3;
74
+
75
+ /** A streaming UTF-8 decoder (the WHATWG algorithm: no overlong form, no surrogate,
76
+ * nothing above U+10FFFF). `push` returns a code point, MORE when the character is
77
+ * incomplete, BAD for a byte that is not UTF-8, or RETRY when the byte ended an
78
+ * incomplete character: that character is invalid and the byte must be offered again. */
79
+ function utf8Decoder() {
80
+ let need = 0, cp = 0, lo = 0x80, hi = 0xbf;
81
+ return {
82
+ get pending() { return need > 0; },
83
+ push(b) {
84
+ if (need === 0) {
85
+ if (b < 0x80) return b;
86
+ if (b >= 0xc2 && b <= 0xdf) { need = 1; cp = b & 0x1f; }
87
+ else if (b >= 0xe0 && b <= 0xef) { need = 2; cp = b & 0x0f; if (b === 0xe0) lo = 0xa0; else if (b === 0xed) hi = 0x9f; }
88
+ else if (b >= 0xf0 && b <= 0xf4) { need = 3; cp = b & 0x07; if (b === 0xf0) lo = 0x90; else if (b === 0xf4) hi = 0x8f; }
89
+ else return BAD;
90
+ return MORE;
91
+ }
92
+ const valid = b >= lo && b <= hi;
93
+ lo = 0x80; hi = 0xbf;
94
+ if (!valid) { need = 0; return RETRY; }
95
+ cp = (cp << 6) | (b & 0x3f);
96
+ return --need === 0 ? cp : MORE;
97
+ },
98
+ };
99
+ }
100
+
101
+ /** Paste content is decoded leniently: what is not UTF-8 becomes U+FFFD, never an error. */
102
+ function decodeLenient(bytes, length) {
103
+ const decoder = utf8Decoder(), points = [];
104
+ let text = "";
105
+ const put = (cp) => {
106
+ if (points.push(cp) < 4096) return;
107
+ text += String.fromCodePoint.apply(null, points);
108
+ points.length = 0;
109
+ };
110
+ for (let i = 0; i < length; i++) {
111
+ const cp = decoder.push(bytes[i]);
112
+ if (cp >= 0) put(cp);
113
+ else if (cp !== MORE) { put(0xfffd); if (cp === RETRY) i--; }
114
+ }
115
+ if (decoder.pending) put(0xfffd);
116
+ return text + String.fromCodePoint.apply(null, points);
117
+ }
118
+
119
+ /** `now` is the injected clock in milliseconds; the parser reads it once per
120
+ * `feed` and once per `expire`, and nowhere else.
121
+ *
122
+ * feed(bytes) the events of these bytes, in order. Text is never held back:
123
+ * a complete character is emitted by the feed that completes it.
124
+ * expire() call when the clock reaches timeoutAt(): the Esc key, if a lone
125
+ * ESC has waited ESC_TIMEOUT_MS; else nothing.
126
+ * timeoutAt() the clock time at which expire() is due, or null. */
127
+ export function createKeyParser({ now } = {}) {
128
+ if (typeof now !== "function") throw new TypeError("createKeyParser needs an injected clock: { now: () => milliseconds }");
129
+ const utf8 = utf8Decoder();
130
+ let state = GROUND, out = [], feedAt = 0, lastFeedAt = 0;
131
+ let run = ""; // consecutive printable code points of this feed, not yet cut into graphemes
132
+ let alt = false; // ESC came before the multi-byte character being decoded
133
+ let escAt = 0; // feed time of the pending lone ESC
134
+ let seq = ""; // CSI/SS3 parameter and intermediate bytes; null once over SEQUENCE_LIMIT
135
+ let bel = false; // the string sequence is an OSC, which BEL also ends
136
+ let mouse = 0; // bytes of an X10 mouse report still to swallow
137
+ let held = null, size = 0, over = false, matched = 0; // paste: content, its length, limit hit, end-marker bytes matched
138
+
139
+ /** Whatever comes between two code points, a key or a dropped byte or sequence,
140
+ * ends the run: only code points that arrive consecutively join into a grapheme. */
141
+ const flush = () => {
142
+ if (run.length === 1) out.push({ text: run });
143
+ else if (run !== "") for (const { segment } of GRAPHEMES.segment(run)) out.push({ text: segment });
144
+ run = "";
145
+ };
146
+ const emit = (event) => { flush(); out.push(event); };
147
+ const startEscape = () => { flush(); state = ESCAPE; escAt = feedAt; };
148
+
149
+ const ground = (b) => {
150
+ if (b >= 0x80 || utf8.pending) {
151
+ const cp = utf8.push(b);
152
+ if (cp === MORE) return;
153
+ const withAlt = alt;
154
+ alt = false;
155
+ if (cp === RETRY) { flush(); ground(b); return; }
156
+ if (cp === BAD || cp <= 0x9f) { flush(); return; } // not UTF-8, or a C1 control: dropped
157
+ if (withAlt) emit({ text: String.fromCodePoint(cp), alt: true });
158
+ else run += String.fromCodePoint(cp);
159
+ return;
160
+ }
161
+ if (b === ESC) { startEscape(); return; }
162
+ if (b >= 0x20 && b !== 0x7f) { run += String.fromCharCode(b); return; }
163
+ const key = c0Key(b);
164
+ if (key) emit(key);
165
+ else flush();
166
+ };
167
+
168
+ /** The byte after an ESC: a sequence introducer, or Alt plus a key. */
169
+ const afterEscape = (b) => {
170
+ state = GROUND;
171
+ if (b === ESC) { emit(named("escape")); startEscape(); }
172
+ else if (b === 0x5b) { state = CSI; seq = ""; }
173
+ else if (b === 0x4f) { state = SS3; seq = ""; }
174
+ else if (b === 0x5d) { state = STRING; bel = true; } // OSC
175
+ else if (b === 0x50 || b === 0x58 || b === 0x5e || b === 0x5f) { state = STRING; bel = false; } // DCS SOS PM APC
176
+ else if (b >= 0x80) { alt = true; ground(b); }
177
+ else if (b >= 0x20 && b !== 0x7f) emit({ text: String.fromCharCode(b), alt: true });
178
+ else {
179
+ const key = c0Key(b);
180
+ if (key) { key.alt = true; emit(key); }
181
+ }
182
+ };
183
+
184
+ /** Inside a CSI, an SS3 or the Linux console form. A control byte is dropped and
185
+ * the sequence goes on, an ESC starts over, a byte >= 0x80 aborts and is dropped. */
186
+ const inSequence = (b) => {
187
+ if (b === ESC) { startEscape(); return; }
188
+ if (b < 0x20 || b === 0x7f) return;
189
+ if (b >= 0x80) { state = GROUND; return; }
190
+ const from = state;
191
+ // CSI: parameters 0x30..0x3f and intermediates 0x20..0x2f. SS3: parameters only.
192
+ if (from !== LINUX && b <= 0x3f && (from === CSI || b >= 0x30)) {
193
+ seq = seq !== null && seq.length < SEQUENCE_LIMIT ? seq + String.fromCharCode(b) : null;
194
+ return;
195
+ }
196
+ const final = String.fromCharCode(b);
197
+ state = GROUND;
198
+ let key = null;
199
+ if (from === LINUX) key = LINUX_KEYS[final] ? named(LINUX_KEYS[final]) : null;
200
+ else if (from === SS3) key = ss3Key(seq, final);
201
+ else if (seq === "" && final === "[") state = LINUX;
202
+ else if (seq === "" && final === "M") { state = MOUSE; mouse = 3; } // X10 mouse report: 3 raw bytes follow
203
+ else if (seq === "200" && final === "~") state = PASTE;
204
+ else key = csiKey(seq, final);
205
+ if (key) emit(key);
206
+ };
207
+
208
+ const endPaste = (truncated) => {
209
+ emit(truncated ? { paste: "", truncated: true } : { paste: decodeLenient(held, size) });
210
+ held = null; size = 0; over = false; matched = 0;
211
+ state = GROUND;
212
+ };
213
+
214
+ /** Holds paste content, up to the limit. Content that reaches PASTE_LIMIT is
215
+ * dropped and nothing more is held: the paste will end as truncated. */
216
+ const hold = (source, from, to) => {
217
+ if (over) return;
218
+ const length = size + to - from;
219
+ if (length >= PASTE_LIMIT) { over = true; held = null; size = 0; return; }
220
+ if (held === null || length > held.length) {
221
+ const grown = new Uint8Array(Math.min(PASTE_LIMIT, Math.max(length, 2 * (held === null ? 128 : held.length))));
222
+ if (held !== null) grown.set(held.subarray(0, size));
223
+ held = grown;
224
+ }
225
+ held.set(source.subarray(from, to), size);
226
+ size = length;
227
+ };
228
+
229
+ /** Inside a bracketed paste every byte is content, up to the end marker `CSI 201 ~`,
230
+ * which may arrive split at any byte. Returns the index after the bytes it consumed. */
231
+ const inPaste = (bytes, i) => {
232
+ while (i < bytes.length) {
233
+ const b = bytes[i];
234
+ if (b === PASTE_END[matched]) {
235
+ i++;
236
+ if (++matched === PASTE_END.length) { endPaste(over); break; }
237
+ } else if (matched > 0) {
238
+ // Not the marker after all: its bytes were content. This byte is looked at again.
239
+ hold(PASTE_END, 0, matched);
240
+ matched = 0;
241
+ } else {
242
+ const stop = bytes.indexOf(ESC, i);
243
+ hold(bytes, i, stop === -1 ? bytes.length : stop);
244
+ i = stop === -1 ? bytes.length : stop;
245
+ }
246
+ }
247
+ return i;
248
+ };
249
+
250
+ /** The paste pause rule, and it lives only here. A paste whose end marker never
251
+ * arrives must not deafen the program for ever (Ctrl+C is a byte here): when a
252
+ * feed arrives PASTE_PAUSE_MS or more after the previous feed while a paste is
253
+ * open (under or over the limit), the paste is abandoned as truncated and this
254
+ * feed is read as keys. No timer: the clock is only read at feed.
255
+ *
256
+ * This is acceptable only because bracketed paste is a second guard, never the
257
+ * only one. A terminal may lack it, a paste can carry its own end marker, and a
258
+ * stalled paste ends here: nothing in the TUI may rely on this parser to stop a
259
+ * pasted key from acting. An act that matters asks for its own confirmation. */
260
+ const abandonStalledPaste = () => {
261
+ if (state === PASTE && feedAt - lastFeedAt >= PASTE_PAUSE_MS) endPaste(true);
262
+ };
263
+
264
+ return {
265
+ feed(bytes) {
266
+ if (!(bytes instanceof Uint8Array)) throw new TypeError("feed expects bytes (a Uint8Array)");
267
+ feedAt = now();
268
+ // A lone ESC that already waited its time is the Esc key; these bytes start fresh.
269
+ if (state === ESCAPE && feedAt >= escAt + ESC_TIMEOUT_MS) { state = GROUND; emit(named("escape")); }
270
+ abandonStalledPaste();
271
+ lastFeedAt = feedAt;
272
+ for (let i = 0; i < bytes.length; i++) {
273
+ if (state === PASTE) { i = inPaste(bytes, i) - 1; continue; }
274
+ const b = bytes[i];
275
+ switch (state) {
276
+ case GROUND: ground(b); break;
277
+ case ESCAPE: afterEscape(b); break;
278
+ case MOUSE:
279
+ if (b === ESC) startEscape();
280
+ else if (--mouse === 0) state = GROUND;
281
+ break;
282
+ case STRING: // swallowed as it streams, never held
283
+ if (b === ESC) state = STRING_ESC;
284
+ else if (bel && b === 0x07) state = GROUND;
285
+ break;
286
+ case STRING_ESC:
287
+ // `ESC \` is ST and ends the string. An ESC before anything else abandons
288
+ // the string and starts a new sequence, as in a CSI: the next key that
289
+ // sends an ESC recovers from a string whose end never arrives.
290
+ if (b === 0x5c) state = GROUND;
291
+ else if (b !== ESC) afterEscape(b);
292
+ break;
293
+ default: inSequence(b);
294
+ }
295
+ }
296
+ flush();
297
+ const events = out;
298
+ out = [];
299
+ return events;
300
+ },
301
+ expire() {
302
+ if (state !== ESCAPE || now() < escAt + ESC_TIMEOUT_MS) return [];
303
+ state = GROUND;
304
+ return [named("escape")];
305
+ },
306
+ /** Only a lone ESC has a deadline. Every other incomplete sequence waits for its end. */
307
+ timeoutAt() {
308
+ return state === ESCAPE ? escAt + ESC_TIMEOUT_MS : null;
309
+ },
310
+ };
311
+ }
312
+
313
+ /** The canonical string the action table binds: "ctrl+c", "shift+tab", "escape",
314
+ * "?", "space", "alt+q". Modifiers come in the order ctrl, alt, shift. A paste
315
+ * is not a key: null. */
316
+ export function keyId(event) {
317
+ if (typeof event?.name === "string") {
318
+ return `${event.ctrl ? "ctrl+" : ""}${event.alt ? "alt+" : ""}${event.shift ? "shift+" : ""}${event.name}`;
319
+ }
320
+ if (typeof event?.text !== "string") return null;
321
+ const id = event.text === " " ? "space" : event.text;
322
+ return event.alt ? `alt+${id}` : id;
323
+ }
324
+
325
+ /** The names that take every modifier: the keys read by `modified` from a CSI or an SS3. */
326
+ const MODIFIED_NAMES = new Set([...Object.values(LETTER_KEYS), ...Object.values(TILDE_KEYS)]);
327
+ const NAMED_ID = /^(ctrl\+)?(alt\+)?(shift\+)?([a-z][a-z0-9]*)$/;
328
+ /** What no text event holds: a control character (C0, DEL, C1) or half a surrogate pair. */
329
+ const NOT_TEXT = /[\p{Cc}\p{Cs}]/u;
330
+ /** The characters that, after an ESC, begin a sequence (CSI, SS3, OSC, DCS, SOS, PM, APC): Alt
331
+ * with one of them never arrives as a key. */
332
+ const INTRODUCERS = "[O]PX^_";
333
+ const oneGrapheme = (text) => GRAPHEMES.segment(text).containing(0).segment === text;
334
+ const oneCodePoint = (text) => text.length === (text.codePointAt(0) > 0xffff ? 2 : 1);
335
+
336
+ /** Whether a string is a key id: true exactly for the strings keyId answers for an event the
337
+ * parser above can emit, so a table that binds only key ids binds nothing that can never arrive
338
+ * from it. Whether a given terminal sends the key is not asked: `f12` and `alt+` an accented
339
+ * letter are key ids on a terminal that sends neither. The grammar is the parser's, branch for
340
+ * branch (the Linux console's F1..F5 are bare names the others already hold):
341
+ *
342
+ * text one grapheme without a control character, as itself (`+` is the plus key), and
343
+ * `space` for the space, which is never written " "
344
+ * alt+text `alt+` and ONE CODE POINT (`alt++`, `alt+space`): Alt reaches a single
345
+ * character, so `alt+` and a grapheme of several code points is no key; and not
346
+ * `alt+` with one of `[ O ] P X ^ _`, which after an ESC begin a sequence
347
+ * named up down left right home end insert delete pageup pagedown f1..f12, with any of
348
+ * `ctrl+`, `alt+`, `shift+`, in that order
349
+ * enter, backspace: bare or `alt+`. escape: bare
350
+ * tab: bare, `alt+tab`, and `shift+tab` with any of `ctrl+`, `alt+` before it
351
+ * ctrl `ctrl+` or `ctrl+alt+` and a letter a..z whose C0 byte is a key of its own:
352
+ * not h, i, j or m, which arrive as Backspace, Tab and Enter */
353
+ export function isKeyId(id) {
354
+ if (typeof id !== "string" || id === "" || NOT_TEXT.test(id)) return false;
355
+ if (id === "space" || id === "alt+space") return true;
356
+ if (id === " " || id === "alt+ ") return false;
357
+ if (oneGrapheme(id)) return true;
358
+ if (id.startsWith("alt+") && id.length > 4 && oneCodePoint(id.slice(4))) return !INTRODUCERS.includes(id.slice(4));
359
+ const match = NAMED_ID.exec(id);
360
+ if (!match) return false;
361
+ const [, ctrl, alt, shift, name] = match;
362
+ if (MODIFIED_NAMES.has(name)) return true;
363
+ if (name === "tab") return shift !== undefined || ctrl === undefined;
364
+ if (name === "enter" || name === "backspace") return ctrl === undefined && shift === undefined;
365
+ if (name === "escape") return ctrl === undefined && alt === undefined && shift === undefined;
366
+ return name.length === 1 && ctrl !== undefined && shift === undefined && c0Key(name.charCodeAt(0) - 0x60).name === name;
367
+ }
@@ -0,0 +1,134 @@
1
+ // The screen: a buffer of cells and the bytes that turn the previous frame into the next one.
2
+ // With term/tty.mjs it is the only module that produces an ESC byte, and what it writes is a closed
3
+ // list: a position, an erase, an SGR of style.mjs's parameters. Text reaches it as safe text only
4
+ // (term/text.mjs); a string is refused.
5
+ //
6
+ // The rules a width disagreement cannot break (docs/tui.md): every row write starts with an
7
+ // absolute position and is erased to its end, so a character the terminal draws wider or narrower
8
+ // than width.mjs counts moves nothing outside its own row; nothing is written past the last column.
9
+ import { cells } from "./width.mjs";
10
+ import { textOf } from "./text.mjs";
11
+ import { PLAIN, isStyle, sgr } from "./style.mjs";
12
+
13
+ const CSI = "\x1b[";
14
+ const RESET = `${CSI}0m`;
15
+ const CLEAR = `${CSI}2J`;
16
+ const ERASE_TO_END = `${CSI}K`;
17
+ const position = (row, col) => `${CSI}${row + 1};${col + 1}H`;
18
+
19
+ const cell = (text, width, style) => Object.freeze({ text, width, style });
20
+ const BLANK = cell(" ", 1, PLAIN);
21
+ /** The second cell of a two-cell grapheme: it holds nothing to write. */
22
+ const TAIL = cell("", 0, PLAIN);
23
+ const PRINTABLE_ASCII = /^[\x20-\x7e]$/;
24
+ /** A cell that shows nothing: a space in a style that draws nothing on a space. */
25
+ const shows = (c) => c.text !== " " || c.style.underline || c.style.reverse;
26
+
27
+ /** What the locale and `--ascii` decide: `utf8`, whether the terminal is told to read UTF-8
28
+ * (LC_ALL, else LC_CTYPE, else LANG names it), and `ascii`, whether the TUI's own marks and rules
29
+ * are ASCII (not UTF-8, or asked for). */
30
+ export function glyphs(env, { ascii = false } = {}) {
31
+ const locale = [env.LC_ALL, env.LC_CTYPE, env.LANG].find((value) => typeof value === "string" && value !== "") ?? "";
32
+ const utf8 = /utf-?8/i.test(locale);
33
+ return { utf8, ascii: ascii || !utf8 };
34
+ }
35
+
36
+ /** A screen. `render(rows, size, { full })` answers the bytes for one frame and remembers it.
37
+ * `rows[r]` is the spans of row r, drawn in order, a later one over an earlier one:
38
+ * `{ col, text, style?, width? }`, `text` safe text, `width` the cells the span may take (default:
39
+ * to the right edge); or a fill, `{ col, width, style? }`, `width` blank cells in that style.
40
+ * `cells(rows, size)` answers the same frame as cells and writes nothing: `{ text, width, style }`
41
+ * per cell, the second cell of a two-cell grapheme with `width: 0`. */
42
+ export function createScreen({ utf8 = true, ascii = !utf8, color = true } = {}) {
43
+ const mark = cells(ascii ? "..." : "\u2026");
44
+ let previous = null;
45
+
46
+ /** Overwriting one half of a two-cell grapheme blanks the other half. */
47
+ function clear(line, x) {
48
+ if (line[x] === TAIL) line[x - 1] = BLANK;
49
+ else if (line[x].width === 2) line[x + 1] = BLANK;
50
+ line[x] = BLANK;
51
+ }
52
+ function place(line, span) {
53
+ const { col, style = PLAIN } = span;
54
+ if (!isStyle(style)) throw new TypeError("a span's style is a style value: make one with style()");
55
+ if (!Number.isInteger(col) || col < 0) throw new RangeError("a span's column is a cell index from 0");
56
+ const limit = span.width === undefined ? line.length : Math.min(line.length, col + span.width);
57
+ // A fill: no text, a width. Blank cells in the span's style, which is how a bar is drawn
58
+ // (a selected row in reverse video): text.mjs rightly makes no text of a run of spaces.
59
+ // A span that names a text, even an absent one, is never a fill: it is refused below.
60
+ if (!Object.hasOwn(span, "text") && span.width !== undefined) {
61
+ if (!Number.isInteger(span.width) || span.width < 0) throw new RangeError("a fill has a width in cells");
62
+ const blank = cell(" ", 1, style);
63
+ for (let x = col; x < limit; x++) { clear(line, x); line[x] = blank; }
64
+ return;
65
+ }
66
+ const source = textOf(span.text);
67
+ if (col >= limit) return;
68
+ let drawn = cells(source);
69
+ // A terminal that is not reading UTF-8 would show each byte of a character on its own.
70
+ if (!utf8) drawn = drawn.map((g) => (PRINTABLE_ASCII.test(g.text) ? g : { text: "?", width: 1 }));
71
+ if (drawn.reduce((sum, g) => sum + g.width, 0) > limit - col) {
72
+ // Clipped: what fits before the mark, then the mark (or as much of it as the span holds).
73
+ const room = limit - col - mark.reduce((sum, g) => sum + g.width, 0);
74
+ const kept = [];
75
+ for (let used = 0, i = 0; i < drawn.length && used + drawn[i].width <= room; used += drawn[i].width, i++) kept.push(drawn[i]);
76
+ drawn = [...kept, ...mark];
77
+ }
78
+ let x = col;
79
+ for (const g of drawn) {
80
+ if (x + g.width > limit) break;
81
+ clear(line, x);
82
+ if (g.width === 2) { clear(line, x + 1); line[x + 1] = TAIL; }
83
+ line[x] = cell(g.text, g.width, style);
84
+ x += g.width;
85
+ }
86
+ }
87
+ function layout(rows, size) {
88
+ return Array.from({ length: size.rows }, (_, r) => {
89
+ const line = Array.from({ length: size.cols }, () => BLANK);
90
+ for (const span of rows[r] ?? []) place(line, span);
91
+ return line;
92
+ });
93
+ }
94
+
95
+ const same = (a, b) => a === b || (a.text === b.text && a.style === b.style);
96
+ const asciiOnly = (line) => line.every((c) => PRINTABLE_ASCII.test(c.text));
97
+ /** The bytes of one row from column `from`: a position, the cells up to the last one that shows,
98
+ * and an erase when the row ends before the right edge. Every row ends in the plain style, so the
99
+ * erase paints nothing and the next row starts from a known state. */
100
+ function writeRow(r, line, from) {
101
+ let end = line.length;
102
+ while (end > 0 && !shows(line[end - 1])) end--;
103
+ const start = Math.min(from, end);
104
+ let out = position(r, start), current = RESET;
105
+ for (let x = start; x < end; x++) {
106
+ const c = line[x];
107
+ if (c === TAIL) continue;
108
+ // Always from a reset: a style never inherits from the cell before it.
109
+ const look = `${CSI}${[0, ...sgr(c.style, { color })].join(";")}m`;
110
+ if (look !== current) { out += look; current = look; }
111
+ out += c.text;
112
+ }
113
+ if (current !== RESET) out += RESET;
114
+ return end < line.length ? out + ERASE_TO_END : out;
115
+ }
116
+
117
+ function render(rows, size, { full = false } = {}) {
118
+ const lines = layout(rows, size);
119
+ const redraw = full || !previous || previous.cols !== size.cols || previous.rows !== size.rows;
120
+ let out = redraw ? RESET + CLEAR : "";
121
+ for (let r = 0; r < size.rows; r++) {
122
+ const line = lines[r], old = redraw ? null : previous.lines[r];
123
+ if (!old) { if (line.some(shows)) out += writeRow(r, line, 0); continue; }
124
+ const changed = line.findIndex((c, x) => !same(c, old[x]));
125
+ if (changed < 0) continue;
126
+ // A row with any grapheme outside printable ASCII is rewritten whole: its columns are only
127
+ // as sure as the width table, so nothing in it is addressed by column.
128
+ out += writeRow(r, line, asciiOnly(line) && asciiOnly(old) ? changed : 0);
129
+ }
130
+ previous = { cols: size.cols, rows: size.rows, lines };
131
+ return out;
132
+ }
133
+ return { render, cells: layout };
134
+ }
@@ -0,0 +1,43 @@
1
+ // Style values, by name. A style is the terminal's own sixteen colours and four attributes
2
+ // (docs/tui.md): no background, no 256-colour or RGB value, so the user's theme stays the theme.
3
+ // This module holds SGR parameters as numbers; the screen is what writes the sequence.
4
+
5
+ const FOREGROUND = Object.freeze({
6
+ black: 30, red: 31, green: 32, yellow: 33, blue: 34, magenta: 35, cyan: 36, white: 37,
7
+ brightBlack: 90, brightRed: 91, brightGreen: 92, brightYellow: 93, brightBlue: 94, brightMagenta: 95, brightCyan: 96, brightWhite: 97,
8
+ });
9
+ const ATTRIBUTE = Object.freeze({ bold: 1, dim: 2, underline: 4, reverse: 7 });
10
+ export const COLORS = Object.freeze(Object.keys(FOREGROUND));
11
+ export const ATTRIBUTES = Object.freeze(Object.keys(ATTRIBUTE));
12
+
13
+ /** One value per distinct style, so two equal styles are the same object and the screen compares
14
+ * cells by identity. */
15
+ const made = new Map();
16
+ const parameters = new WeakMap();
17
+
18
+ /** The style with that colour and those attributes: `style({ fg: "red", bold: true })`. */
19
+ export function style(spec = {}) {
20
+ for (const key of Object.keys(spec)) if (key !== "fg" && !ATTRIBUTES.includes(key)) throw new TypeError(`unknown style key ${key}`);
21
+ if (spec.fg !== undefined && !Object.hasOwn(FOREGROUND, spec.fg)) throw new TypeError("a style's colour is one of the sixteen ANSI names");
22
+ const attributes = ATTRIBUTES.filter((name) => spec[name] === true);
23
+ const id = [...attributes, spec.fg ?? ""].join(",");
24
+ if (!made.has(id)) {
25
+ const value = Object.freeze({ fg: spec.fg ?? null, ...Object.fromEntries(ATTRIBUTES.map((name) => [name, attributes.includes(name)])) });
26
+ parameters.set(value, Object.freeze({ attributes: attributes.map((name) => ATTRIBUTE[name]), colour: spec.fg === undefined ? [] : [FOREGROUND[spec.fg]] }));
27
+ made.set(id, value);
28
+ }
29
+ return made.get(id);
30
+ }
31
+ export const PLAIN = style();
32
+ export const isStyle = (value) => parameters.has(value);
33
+
34
+ /** The SGR parameters of a style, attributes first. Without `color` the colour is dropped and the
35
+ * attributes stay. */
36
+ export function sgr(value, { color = true } = {}) {
37
+ const own = parameters.get(value);
38
+ if (!own) throw new TypeError("not a style value: make one with style()");
39
+ return color ? [...own.attributes, ...own.colour] : [...own.attributes];
40
+ }
41
+
42
+ /** NO_COLOR (no-color.org): set and not empty switches colour off. */
43
+ export const colorEnabled = (env) => !(typeof env.NO_COLOR === "string" && env.NO_COLOR !== "");
@@ -0,0 +1,109 @@
1
+ // Safe text: the only thing the screen draws. A terminal acts on what is written to it, so the
2
+ // screen takes strings from nobody: it takes values only this module can make (docs/tui.md,
3
+ // awebai/oats#855 section 3.9). There are two ways in, and no third:
4
+ // lit(string) the TUI's own words;
5
+ // shown(value) text the TUI did not write, through the shared display filter.
6
+ // A safe value is for display only: nothing compares it, selects by it or passes it to a command.
7
+ //
8
+ // Every view meets this: the filter folds a run of spaces into one and trims both ends, so lit()
9
+ // refuses a string with two spaces together or a space at an end. A row is therefore spans placed
10
+ // by column (`{ col, text, style }`), never one padded string: the gap between two spans is the
11
+ // screen's blank cells, not text.
12
+ import { displayLine, DETAIL_WITHHELD } from "../client.mjs";
13
+ import { cells } from "./width.mjs";
14
+
15
+ /** The brand: a value is safe text when it is a key here. Nothing outside this module can add one,
16
+ * and a look-alike object is not one. */
17
+ const TEXT = new WeakMap();
18
+ function make(string) {
19
+ const value = Object.freeze(Object.create(null));
20
+ TEXT.set(value, string);
21
+ return value;
22
+ }
23
+
24
+ /** Nothing to show. */
25
+ export const EMPTY = make("");
26
+ /** Text the filter withheld whole (a control character, a secret shape): the TUI's own mark. */
27
+ export const WITHHELD = make("[withheld]");
28
+
29
+ /** The TUI's own one-line text. It throws unless the display filter would show the string as it is:
30
+ * a developer who hands it kernel text by mistake still cannot write a control character. The
31
+ * message never repeats the string, which may be the very thing that must not be written. */
32
+ export function lit(string) {
33
+ if (typeof string !== "string" || displayLine(string) !== string) throw new TypeError("lit() takes the TUI's own one-line text, exactly as the display filter shows it; text from anywhere else goes through shown()");
34
+ return make(string);
35
+ }
36
+
37
+ /** Text the TUI did not write (a kernel answer, a name, anything relayed), as one display line. */
38
+ export function shown(value) {
39
+ const line = displayLine(value);
40
+ return line === null ? EMPTY : line === DETAIL_WITHHELD ? WITHHELD : make(line);
41
+ }
42
+
43
+ /** The cut mark, the screen's own (term/screen.mjs): one cell, or three in ASCII. */
44
+ const cutMark = (ascii) => (ascii ? "..." : "\u2026");
45
+ const widthOf = (graphemes) => graphemes.reduce((sum, g) => sum + g.width, 0);
46
+ const joined = (graphemes) => graphemes.map((g) => g.text).join("");
47
+
48
+ /** Text the TUI did not write, as the END of its display line: what fits `width` cells, with the
49
+ * cut mark in front when the start is left out. For a value read from its end (a path).
50
+ * Filtered first and cut after, by cells and between graphemes: a part of a display line is
51
+ * itself fit to show, so nothing reaches the screen that shown() would not have let through. */
52
+ export function shownEnd(value, width, { ascii = false } = {}) {
53
+ const line = displayLine(value);
54
+ if (line === null) return EMPTY;
55
+ if (line === DETAIL_WITHHELD) return WITHHELD;
56
+ const all = cells(line);
57
+ if (widthOf(all) <= width) return make(joined(all));
58
+ const mark = cutMark(ascii), room = width - mark.length;
59
+ const kept = [];
60
+ for (let i = all.length - 1, used = 0; i >= 0 && used + all[i].width <= room; used += all[i].width, i--) kept.unshift(all[i]);
61
+ return make(room < 0 ? "" : mark + joined(kept).replace(/^ +/, ""));
62
+ }
63
+
64
+ /** Text the TUI did not write, as at most `max` rows of at most `width` cells: its display line
65
+ * broken at spaces where it can be and between graphemes where it cannot, the last row ending
66
+ * in the cut mark when more was left. For a sentence that must be read whole (a kernel's
67
+ * reason). Filtered first and cut after, as shownEnd is; nothing to show gives no row, and
68
+ * neither does a row too narrow for the first grapheme. */
69
+ export function shownLines(value, width, max, { ascii = false } = {}) {
70
+ const line = displayLine(value);
71
+ if (line === null || width < 1 || max < 1) return [];
72
+ if (line === DETAIL_WITHHELD) return [WITHHELD];
73
+ const rows = [];
74
+ let rest = cells(line);
75
+ while (rest.length && rows.length < max) {
76
+ if (widthOf(rest) <= width) { rows.push(rest); rest = []; break; }
77
+ let end = 0;
78
+ for (let used = 0; end < rest.length && used + rest[end].width <= width; used += rest[end].width) end++;
79
+ // Back to the last space inside the row, when there is one: the row ends before it.
80
+ let cut = end;
81
+ while (cut > 0 && rest[cut]?.text !== " " && rest[cut - 1].text !== " ") cut--;
82
+ if (cut === 0) cut = end;
83
+ if (cut === 0) break; // a grapheme wider than the row: nothing more can be set
84
+ const row = rest.slice(0, cut);
85
+ while (row.length && row[row.length - 1].text === " ") row.pop();
86
+ rest = rest.slice(cut);
87
+ while (rest.length && rest[0].text === " ") rest.shift();
88
+ rows.push(row);
89
+ }
90
+ const mark = cutMark(ascii);
91
+ if (rest.length && rows.length && mark.length <= width) {
92
+ // More was left: the last row gives up its end to the mark. (A row too narrow for the mark
93
+ // keeps what it has: no row is ever wider than `width`.)
94
+ const last = rows[rows.length - 1];
95
+ while (last.length && widthOf(last) + mark.length > width) last.pop();
96
+ while (last.length && last[last.length - 1].text === " ") last.pop();
97
+ last.push(...cells(mark));
98
+ }
99
+ return rows.map((row) => make(joined(row)));
100
+ }
101
+
102
+ export const isSafeText = (value) => TEXT.has(value);
103
+
104
+ /** The string of a safe value, for the screen (and the tests that read a row). A raw string and a
105
+ * forged object are refused. */
106
+ export function textOf(value) {
107
+ if (!TEXT.has(value)) throw new TypeError("the screen draws safe text only: lit() for the TUI's own words, shown() for anything else");
108
+ return TEXT.get(value);
109
+ }