@awebai/oats 0.65.0 → 0.66.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +11 -5
  2. package/bin/oats.mjs +8 -7
  3. package/docs/desktop-cli-api.md +5 -4
  4. package/docs/implementation.md +10 -1
  5. package/docs/integrations.md +1 -1
  6. package/docs/official-catalog.md +2 -2
  7. package/docs/packages.md +7 -7
  8. package/docs/release-notes/v0.66.0.md +183 -0
  9. package/docs/servers.md +2 -2
  10. package/docs/tui.md +137 -16
  11. package/docs/upgrading.md +1 -1
  12. package/docs/workspaces.md +9 -2
  13. package/lib/deployments.mjs +21 -5
  14. package/package-catalog.json +2 -2
  15. package/package.json +1 -1
  16. package/packages/client/cli-locator.mjs +2 -2
  17. package/packages/client/keymap.mjs +36 -9
  18. package/packages/client/machine-contract.mjs +1 -5
  19. package/packages/record/bin/setup.mjs +10 -2
  20. package/packages/record/docs/capture-service.md +45 -6
  21. package/packages/record/lib/capture-service-install.mjs +6 -95
  22. package/packages/record/lib/capture-setup-write.mjs +233 -0
  23. package/packages/tui/README.md +7 -6
  24. package/packages/tui/lib/actions.mjs +65 -64
  25. package/packages/tui/lib/client.mjs +1 -0
  26. package/packages/tui/lib/config.mjs +167 -26
  27. package/packages/tui/lib/main.mjs +53 -9
  28. package/packages/tui/lib/model.mjs +2 -0
  29. package/packages/tui/lib/store.mjs +18 -3
  30. package/packages/tui/lib/term/keys.mjs +135 -33
  31. package/packages/tui/lib/term/kitty.mjs +198 -0
  32. package/packages/tui/lib/term/through.mjs +128 -14
  33. package/packages/tui/lib/term/tty.mjs +43 -12
  34. package/packages/tui/lib/views/frame.mjs +1 -1
  35. package/packages/tui/lib/views/help.mjs +52 -13
  36. package/skills/oats-getting-started/SKILL.md +96 -28
@@ -1,15 +1,16 @@
1
1
  // The user's key file, tui.json: which keys do what, whether the screen is drawn in ASCII, and the
2
2
  // key that takes the focus from an agent's terminal back to the list.
3
- // Read once at start and never written. A file that is wrong in any way is refused whole, each
4
- // problem as one line that says what to change: the TUI resolves no conflict and guesses nothing
3
+ // Read once at start, and never written but by its move from where it was before (moved()). A file
4
+ // that is wrong in any way is refused whole, each problem as one line that says what to change:
5
+ // the TUI resolves no conflict and guesses nothing
5
6
  // (there is no "last wins"), because a key that silently does something else is worse than a
6
7
  // program that does not start. The lines go to a terminal, so nothing taken from the file, and
7
8
  // no path, reaches one unless it is plain printable ASCII.
8
- import { closeSync, openSync, readSync, statSync } from "node:fs";
9
+ import { closeSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readSync, renameSync, statSync, unlinkSync, writeSync } from "node:fs";
9
10
  import { homedir } from "node:os";
10
- import { isAbsolute, join } from "node:path";
11
+ import { basename, dirname, isAbsolute, join } from "node:path";
11
12
  import { ACTIONS, bindings, keyLabel } from "./actions.mjs";
12
- import { displayLine } from "./client.mjs";
13
+ import { displayLine, leaderKey } from "./client.mjs";
13
14
  import { isKeyId } from "./term/keys.mjs";
14
15
  import { BACK_KEY_RULE, backKeyId, isBackKey } from "./term/through.mjs";
15
16
 
@@ -19,12 +20,19 @@ export const CONFIG_LIMIT = 64 * 1024;
19
20
  const TOO_LARGE = `it is larger than ${CONFIG_LIMIT / 1024} KiB`;
20
21
  const NOT_AN_OBJECT = 'it is not one JSON object, like {"keys": {"quit": ["q"]}}';
21
22
  const SETTINGS = "the settings are keys, ascii and open";
23
+ /** A key id of the shared keymap (`ctrl+\\`, `alt+o`) in the back key's spelling (`C-\\`, `M-o`):
24
+ * Ctrl or Alt and one character, which is what the shared leader is. Anything else: null. */
25
+ function backKeyOf(keyId) {
26
+ const [, mod, rest] = /^(ctrl|alt)\+(.)$/.exec(keyId) ?? [];
27
+ return mod === undefined ? null : `${mod === "ctrl" ? "C" : "M"}-${rest}`;
28
+ }
22
29
  /** The back key when tui.json names none, on `platform` (a `process.platform` value): the key that
23
30
  * takes the focus from an agent's terminal back to the list, the leader (the setting keeps its
24
- * name, `open.detachKey`, from when it left a viewer). `C-\\` on macOS, whose terminals send
25
- * Option as Meta only when told to; `M-o` (Alt+O) elsewhere. Both are read as keys no action of
26
- * ACTIONS holds (`ctrl+\\`, `alt+o`), which the check of the leader below keeps true. */
27
- export const defaultDetachKey = (platform = process.platform) => (platform === "darwin" ? "C-\\" : "M-o");
31
+ * name, `open.detachKey`, from when it left a viewer). It is the shared leader, the Desktop's too
32
+ * (packages/client/keymap.mjs leaderKey): `C-\\` on macOS, whose terminals send Option as Meta
33
+ * only when told to; `M-o` (Alt+O) elsewhere. Both are read as keys no action of ACTIONS holds
34
+ * (`ctrl+\\`, `alt+o`), which the check of the leader below keeps true. */
35
+ export const defaultDetachKey = (platform = process.platform) => backKeyOf(leaderKey(platform === "darwin"));
28
36
  /** An action id this program had and has no more, with what it is called now. */
29
37
  const RENAMED = Object.freeze({ "open-workspace": "open" });
30
38
  const KEY_IDS = "key ids look like q, ctrl+c, shift+tab, f5, space";
@@ -45,12 +53,22 @@ const isObject = (value) => value !== null && typeof value === "object" && !Arra
45
53
  /** Never the text of an error, which may hold anything: its code, when that is a plain one. */
46
54
  const unreadable = (error) => { const code = error?.code; return `it cannot be read${typeof code === "string" && ERROR_CODE.test(code) ? ` (${code})` : ""}`; };
47
55
 
48
- /** The path of tui.json: `$XDG_CONFIG_HOME/oats/tui.json` when that variable is set, not empty
49
- * and absolute (the XDG rule: a relative value is ignored), else `<home>/.config/oats/tui.json`. */
56
+ /** The path of tui.json: `config/tui.json` in OATS's own directory of this user, `$OATS_HOME_DIR`
57
+ * when that is set and not empty, else `<home>/.oats` (the kernel's rule for its files, as
58
+ * lib/deployments.mjs has it for this computer's list of deployments). */
50
59
  export function configPath(env, home) {
60
+ const own = env?.OATS_HOME_DIR;
61
+ return join(typeof own === "string" && own !== "" ? own : join(home, ".oats"), "config", "tui.json");
62
+ }
63
+ /** Where tui.json was before awebai/oats#1390 step (b), and is looked for only to move it
64
+ * (moved()): `$XDG_CONFIG_HOME/oats/tui.json` when that variable is set, not empty and absolute
65
+ * (the XDG rule: a relative value is ignored), else `<home>/.config/oats/tui.json`. */
66
+ export function oldConfigPath(env, home) {
51
67
  const xdg = env?.XDG_CONFIG_HOME;
52
68
  return join(typeof xdg === "string" && xdg !== "" && isAbsolute(xdg) ? xdg : join(home, ".config"), "oats", "tui.json");
53
69
  }
70
+ /** What the old file is renamed to once it is copied: beside it, so it is never lost. */
71
+ export const MIGRATED = "tui.json.migrated";
54
72
 
55
73
  /** What tui.json says, checked: `value` is the file already parsed, `defaults` the action table,
56
74
  * `platform` the one the TUI runs on (a `process.platform` value). Pure. Answers
@@ -137,9 +155,36 @@ function openProblem(given) {
137
155
 
138
156
  /** The file system as loadConfig needs it. `stat` follows symbolic links and answers null for a
139
157
  * path that does not exist, which includes a path under something that is not a directory (an
140
- * XDG_CONFIG_HOME of /dev/null); every other failure is thrown. `read` never takes in more than
141
- * the limit and one byte, whatever the file became since it was measured. */
158
+ * OATS_HOME_DIR of /dev/null); every other failure is thrown. `read` never takes in more than
159
+ * the limit and one byte, whatever the file became since it was measured, and `bytes` the same as
160
+ * bytes. For the move (moved()): `entry` answers `{ ino }` when an entry is at the path, a link
161
+ * not followed (a link to nothing is an entry), or null; `place` writes `bytes` as a new file at
162
+ * `path`, never over one: a file of its own first (mode 0600, synced), in the directory it makes
163
+ * with mode 0700 when it is missing, then linked there. It answers that file's `{ ino }`, with
164
+ * `taken: true` when an entry was at `path` already and nothing was placed; every failure is
165
+ * thrown, marked `noLinks` when the file system has no hard links. `rename` and `remove` are rename(2) and unlink(2), which act on a link itself. */
142
166
  const NODE_IO = Object.freeze({
167
+ entry: entryAt,
168
+ bytes(path) { return readCapped(path); },
169
+ place(bytes, to) {
170
+ mkdirSync(dirname(to), { recursive: true, mode: 0o700 });
171
+ const own = join(dirname(to), `.${basename(to)}.${process.pid}.${Date.now()}.tmp`);
172
+ const ino = written(own, bytes);
173
+ try {
174
+ linkSync(own, to);
175
+ return { ino };
176
+ } catch (error) {
177
+ if (error?.code === "EEXIST") return { ino, taken: true };
178
+ // A file system without hard links has no step that is both whole and never over a file
179
+ // (there is no rename that refuses one): the move is refused, nothing placed.
180
+ if (NO_LINKS.has(error?.code)) error.noLinks = true;
181
+ throw error;
182
+ } finally {
183
+ try { unlinkSync(own); } catch { /* its own file, in a directory it could write */ }
184
+ }
185
+ },
186
+ rename(from, to) { renameSync(from, to); },
187
+ remove(path) { unlinkSync(path); },
143
188
  stat(path) {
144
189
  try {
145
190
  const found = statSync(path);
@@ -149,19 +194,112 @@ const NODE_IO = Object.freeze({
149
194
  throw error;
150
195
  }
151
196
  },
152
- read(path) {
153
- const fd = openSync(path, "r");
154
- try {
155
- const bytes = Buffer.alloc(CONFIG_LIMIT + 1);
156
- let length = 0, got = 0;
157
- while (length < bytes.length && (got = readSync(fd, bytes, length, bytes.length - length, null)) > 0) length += got;
158
- if (length > CONFIG_LIMIT) throw Object.assign(new Error("tui.json grew past the limit while it was read"), { code: "EFBIG" });
159
- return bytes.toString("utf8", 0, length);
160
- } finally { closeSync(fd); }
161
- },
197
+ read(path) { return readCapped(path).toString("utf8"); },
162
198
  });
199
+ /** What link(2) answers on a file system without hard links (FAT, exFAT, some network mounts). */
200
+ const NO_LINKS = new Set(["EPERM", "ENOTSUP", "EOPNOTSUPP", "ENOSYS"]);
201
+ /** `bytes` as a new file at `path`, made only where nothing is (mode 0600) and synced; answers its
202
+ * inode. A file it made and could not finish is removed. */
203
+ function written(path, bytes) {
204
+ const fd = openSync(path, "wx", 0o600);
205
+ let ino;
206
+ try {
207
+ for (let at = 0; at < bytes.length;) at += writeSync(fd, bytes, at, bytes.length - at);
208
+ fsyncSync(fd);
209
+ ino = fstatSync(fd).ino;
210
+ } catch (error) {
211
+ closeSync(fd);
212
+ try { unlinkSync(path); } catch { /* the error thrown says what failed */ }
213
+ throw error;
214
+ }
215
+ closeSync(fd);
216
+ return ino;
217
+ }
218
+ /** `{ ino }` of the entry at `path`, a link not followed, or null when there is none. */
219
+ function entryAt(path) {
220
+ try { return { ino: lstatSync(path).ino }; } catch (error) {
221
+ if (error?.code === "ENOENT" || error?.code === "ENOTDIR") return null;
222
+ throw error;
223
+ }
224
+ }
225
+ /** At most CONFIG_LIMIT bytes of a file, whatever it became since it was measured. */
226
+ function readCapped(path) {
227
+ const fd = openSync(path, "r");
228
+ try {
229
+ const bytes = Buffer.alloc(CONFIG_LIMIT + 1);
230
+ let length = 0, got = 0;
231
+ while (length < bytes.length && (got = readSync(fd, bytes, length, bytes.length - length, null)) > 0) length += got;
232
+ if (length > CONFIG_LIMIT) throw Object.assign(new Error("tui.json grew past the limit while it was read"), { code: "EFBIG" });
233
+ return bytes.subarray(0, length);
234
+ } finally { closeSync(fd); }
235
+ }
236
+
237
+ /** A path for a line: as it is when it is printable ASCII of at most 200 characters, else `named`. */
238
+ const shownPath = (path, named) => (PLAIN_PATH.test(path) ? path : named);
239
+ /** Why a step of the move failed, for its line: never the text of an error, only its code. */
240
+ const failedBy = (error) => { const code = error?.code; return typeof code === "string" && ERROR_CODE.test(code) ? code : "it failed"; };
241
+
242
+ /** THE MOVE OF tui.json (docs/tui.md, "Change the keys: tui.json"; awebai/oats#1390 §3), before
243
+ * it is read: the file the old rule found (`old`, oldConfigPath) and the one read now (`path`).
244
+ * old present, new absent its bytes are copied to the new path (placed: never over a file),
245
+ * then the old file is renamed to tui.json.migrated beside it (a link
246
+ * is renamed, not followed); then the new file is read. A copy that
247
+ * cannot be made, or a rename that fails, refuses with the line that
248
+ * says to move it by hand, the copy deleted first when it was made.
249
+ * both present refused: the old file is no longer read, and nothing is chosen.
250
+ * old absent nothing to move: the new file is read, or the defaults are used.
251
+ * "Present" is an entry at the path, a link to nothing included: it is reported, not guessed at.
252
+ * Answers null when the new file is to be read, else the line that refuses. A run that loses a
253
+ * race to another one starting (a new file placed by it after this run looked) asks the table
254
+ * again (again()): it reads the file that run placed once that run has moved the old file, and
255
+ * refuses as for both while an old file is still there, its own or the other's not yet renamed. */
256
+ function moved(old, path, io) {
257
+ const from = shownPath(old, "its old configuration file"), to = shownPath(path, "its configuration file");
258
+ const cannot = (reason) => `oats: \`oats tui\` cannot move ${from} to ${to} (${reason}); move it yourself (E_TUI_CONFIG)`;
259
+ const both = `oats: \`oats tui\`: ${from} is no longer read: the TUI reads ${to}. Copy what you need into ${to}, then remove ${from} (E_TUI_CONFIG)`;
260
+ // A step that fails because another run placed a new file since this one looked (the old file
261
+ // renamed, its backup made, the new path taken) asks the table again: a new file and no old one
262
+ // is that run's move, read; a new file beside this run's old one (another XDG_CONFIG_HOME's
263
+ // move) is both, refused; no new file is this step's failure.
264
+ const again = (reason) => {
265
+ try {
266
+ if (io.entry(path) === null) return cannot(reason);
267
+ return io.entry(old) === null ? null : both;
268
+ } catch { return cannot(reason); }
269
+ };
270
+ let had, has;
271
+ try { had = io.entry(old); } catch (error) { return cannot(failedBy(error)); }
272
+ if (had === null) return null;
273
+ try { has = io.entry(path); } catch (error) { return cannot(failedBy(error)); }
274
+ if (has !== null) return both;
275
+ const aside = join(dirname(old), MIGRATED);
276
+ let found, bytes, placed;
277
+ try {
278
+ // A backup of an earlier move is never written over.
279
+ if (io.entry(aside) !== null) return again(`${MIGRATED} is there already`);
280
+ found = io.stat(old);
281
+ } catch (error) { return again(failedBy(error)); }
282
+ if (found === null) return again("it is a link to nothing");
283
+ if (found.file !== true) return cannot("it is not a regular file");
284
+ if (!(typeof found.size === "number" && found.size <= CONFIG_LIMIT)) return cannot(TOO_LARGE);
285
+ try { bytes = io.bytes(old); } catch (error) { return error?.code === "EFBIG" ? cannot(TOO_LARGE) : again(failedBy(error)); }
286
+ try { placed = io.place(bytes, path); } catch (error) { return cannot(error?.noLinks === true ? "this file system has no hard links" : failedBy(error)); }
287
+ // Only an entry found at the new path itself is another run's file; an EEXIST thrown on the way
288
+ // (a `config` that is a file) is a failure like any other.
289
+ if (placed.taken === true) return again("EEXIST");
290
+ try { io.rename(old, aside); } catch (error) {
291
+ // The old file gone and a new one there (moved meanwhile by something else): the copy is the
292
+ // old file's bytes, and it is read; nothing is deleted.
293
+ try { if (io.entry(old) === null && io.entry(path) !== null) return null; } catch { /* refused below */ }
294
+ // The copy is deleted only while it is still the one this run made.
295
+ try { if (io.entry(path)?.ino === placed.ino) io.remove(path); } catch { /* the line says to move it by hand */ }
296
+ return cannot(failedBy(error));
297
+ }
298
+ return null;
299
+ }
163
300
 
164
- /** Read tui.json, once. Answers `{ ok: true, actions, ascii, detachKey, path }`, or
301
+ /** Read tui.json, once, after its move from where it was before (moved()). Answers
302
+ * `{ ok: true, actions, ascii, detachKey, path }`, or
165
303
  * `{ ok: false, lines }`: the complete lines to print (no trailing newline), after which the TUI
166
304
  * must not start. No file is the defaults: `actions` is ACTIONS itself, `ascii` is false and
167
305
  * `detachKey` is defaultDetachKey(platform); `platform` is the one the TUI runs on (a
@@ -169,11 +307,14 @@ const NODE_IO = Object.freeze({
169
307
  *
170
308
  * `io` is the file system (node:fs when omitted): `io.stat(path)` answers `{ file, size }` after
171
309
  * following symbolic links, or null when the path does not exist, and throws for anything else;
172
- * `io.read(path)` answers the text. The size is checked before `read` is called, so a file over
173
- * CONFIG_LIMIT, a directory or a FIFO is never opened. A line holds the path only when it is
310
+ * `io.read(path)` answers the text; the move uses `entry`, `bytes`, `place`, `rename` and `remove`
311
+ * (see NODE_IO). The size is checked before `read` or `bytes` is called, so a file over
312
+ * CONFIG_LIMIT, a directory or a FIFO is never opened. A line holds a path only when it is
174
313
  * printable ASCII, and never the text of an error: only its code, when it is a plain one. */
175
314
  export function loadConfig({ env = process.env, home = homedir(), io = NODE_IO, platform = process.platform } = {}) {
176
315
  const path = configPath(env, home);
316
+ const refusal = moved(oldConfigPath(env, home), path, io);
317
+ if (refusal !== null) return { ok: false, lines: [refusal] };
177
318
  const listed = (problems) => (problems.length > MAX_PROBLEMS ? [...problems.slice(0, MAX_PROBLEMS), problems.length - MAX_PROBLEMS === 1 ? "1 more problem is not listed" : `${problems.length - MAX_PROBLEMS} more problems are not listed`] : problems);
178
319
  const refused = (problems) => ({ ok: false, lines: listed(problems).map((problem) => `oats: \`oats tui\` cannot use ${PLAIN_PATH.test(path) ? path : "its configuration file"}: ${problem} (E_TUI_CONFIG)`) });
179
320
  let found, text, value;
@@ -20,6 +20,7 @@ import { CHANGE_FILES, admitDeployment, createReader, findDeployment, leaveInsta
20
20
  import { initialState, reduce } from "./store.mjs";
21
21
  import { captureRows } from "./term/capture.mjs";
22
22
  import { createKeyParser, keyId } from "./term/keys.mjs";
23
+ import { confirmed } from "./term/kitty.mjs";
23
24
  import { createScreen, glyphs } from "./term/screen.mjs";
24
25
  import { colorEnabled } from "./term/style.mjs";
25
26
  import { backKeySequences, createThrough } from "./term/through.mjs";
@@ -126,7 +127,15 @@ export function createRunTimers({ setTimer, clearTimer }) {
126
127
  * the terminal; the user's tui.json; the deployment; the kernel it shipped with; and, for a start
127
128
  * outside every deployment with no `--dir`, this computer's deployments list, read through that
128
129
  * kernel. */
129
- export async function main({ argv, stdin, stdout, stderr, env, proc = process, now = Date.now, setTimer = setTimeout, clearTimer = clearTimeout, cwd = () => process.cwd(), home = homedir(), effects: given = EFFECTS }) {
130
+ /** How long a run waits for the terminal's answer to the kitty keyboard protocol's query, in
131
+ * milliseconds, before it pops the protocol and reads keys as before for the rest of the run
132
+ * (docs/tui.md, "Chords"). A terminal answers as it reads the query, before any key typed after
133
+ * it, so the wait only bounds a terminal that never answers; it is long enough for a slow link. */
134
+ export const KEYBOARD_WAIT_MS = 2000;
135
+
136
+ /** `keyboard`: whether the run asks the terminal for the kitty keyboard protocol (term/tty.mjs PUSH,
137
+ * QUERY). Every run does; a test of a terminal that is never asked passes false. */
138
+ export async function main({ argv, stdin, stdout, stderr, env, proc = process, now = Date.now, setTimer = setTimeout, clearTimer = clearTimeout, cwd = () => process.cwd(), home = homedir(), keyboard = true, effects: given = EFFECTS }) {
130
139
  const effects = given === EFFECTS ? EFFECTS : { ...EFFECTS, ...given };
131
140
  const { options, error } = parseArgs(argv);
132
141
  if (error) { stderr.write(`${error}\n`); return 1; }
@@ -154,14 +163,23 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
154
163
  const clock = () => new Date(now()).toISOString();
155
164
  const look = glyphs(env, { ascii: options.ascii || config.ascii });
156
165
  const screen = createScreen({ ...look, color: colorEnabled(env) });
157
- let parser = createKeyParser({ now });
158
- let state = initialState({ deployment: found.ok ? found.deployment : null, cli: probe.cli, home, entry: found.ok ? pendingEntry(null, clock()) : null, actions: config.actions, ascii: look.ascii, detachKey: config.detachKey });
166
+ let state = initialState({ deployment: found.ok ? found.deployment : null, cli: probe.cli, home, entry: found.ok ? pendingEntry(null, clock()) : null, actions: config.actions, ascii: look.ascii, platform: proc.platform, detachKey: config.detachKey });
159
167
  const keymap = bindings(state.actions);
168
+ // THE KITTY KEYBOARD PROTOCOL (docs/tui.md, "Chords"): asked for as the terminal is taken (the
169
+ // guard's PUSH and QUERY), "asking" until it answers or KEYBOARD_WAIT_MS passes, then the flags
170
+ // it confirmed (flag 1 held), or null for the rest of the run. The key parser and the scanner
171
+ // below are made with it, and each reads the answer itself when it comes through it.
172
+ let kb = keyboard ? "asking" : null, kbTimer = null;
173
+ /** The clock time the wait for the answer ends: what may begin it is held up to then. */
174
+ const answerBy = keyboard ? now() + KEYBOARD_WAIT_MS : null;
175
+ const newParser = () => createKeyParser({ now, keyboard: kb, chords: state.chords, answerBy });
176
+ let parser = newParser();
160
177
  // While a terminal has the focus the bytes typed go to the agent: this scanner takes from them
161
- // only the back key and a bracketed paste (term/through.mjs). A new one each time the terminal
162
- // takes the focus, so nothing held from before is typed into it.
178
+ // only the back key, the chords and a bracketed paste (term/through.mjs). A new one each time the
179
+ // terminal takes the focus, so nothing held from before is typed into it.
163
180
  const backKey = backKeySequences(state.detachKey);
164
- let through = createThrough({ sequences: backKey, now }), throughTimer = null;
181
+ const newThrough = () => createThrough({ sequences: backKey, now, keyboard: kb, leader: state.leaderKey, chords: state.chords, answerBy });
182
+ let through = newThrough(), throughTimer = null;
165
183
  if (listedAtStart) state = reduce(state, { listed: { rows: listedAtStart } }, keymap).state;
166
184
  // What the last frame drew, for the store: how tall the list pane is and how far the other
167
185
  // pane scrolls. The store holds no size of its own; the panel's room goes with each key as it
@@ -667,14 +685,36 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
667
685
  for (const event of events) {
668
686
  if (event.input) { if (keysReady()) panel.input(event.input); }
669
687
  else if (event.paste !== undefined) { if (keysReady()) panel.paste(event.paste); }
688
+ else if (event.keyboard !== undefined) answered(event.keyboard);
670
689
  else if (event.back) {
671
- parser = createKeyParser({ now });
690
+ parser = newParser();
672
691
  if (took(reduce(state, { back: true, read: ++reads, rest: event.rest.length > 0 }, keymap))) return;
673
692
  guard.draw();
693
+ } else if (event.chord !== undefined) {
694
+ // A chord from the terminal's focus is the leader then its key (the store's `led`): it never
695
+ // reaches the agent, and the rest of its read is dropped, as after the leader's key.
696
+ parser = newParser();
697
+ if (took(reduce(state, { chord: event.chord, read: ++reads, ...drawn, panel: placed()?.panel ?? null }, keymap))) return;
698
+ guard.draw();
674
699
  }
675
700
  }
676
701
  watchThrough();
677
702
  }
703
+ /** The terminal's answer to the protocol's query (`flags`), or none in time (null): the protocol is
704
+ * read from now on when the answer holds flag 1, and popped otherwise; an answer after that is
705
+ * not taken. The parser or the scanner that read the answer reads the rest of its read as it
706
+ * says; the other is made again. */
707
+ function answered(flags) {
708
+ if (kb !== "asking") return;
709
+ if (kbTimer !== null) { clearTimer(kbTimer); kbTimer = null; }
710
+ kb = confirmed(flags) ? flags : null;
711
+ guard.keyboardAnswered(kb !== null);
712
+ if (parser.keyboard === "asking") parser = newParser();
713
+ // What the scanner held as a possible beginning of the answer is the agent's after all.
714
+ const released = through.giveUp();
715
+ if (released.length && typing()) typed(released);
716
+ if (kb !== null) { state = reduce(state, { keyboard: kb }, keymap).state; guard.draw(); }
717
+ }
678
718
  /** Whether the keys typed now reach the agent the state gives them to, the focused group's shown
679
719
  * tab: the panel is fitted to the state first when it was not, also while no frame is written
680
720
  * (the output blocked), so a tab or a group switched to takes what is typed after the switch,
@@ -694,7 +734,7 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
694
734
  if (due !== null) throughTimer = setTimer(() => { throughTimer = null; guard.attempt(() => { if (typing()) typed(through.expire()); }); }, Math.max(0, due - now()));
695
735
  }
696
736
  const guard = createGuard({
697
- stdin, stdout, proc, setTimer, clearTimer,
737
+ stdin, stdout, proc, setTimer, clearTimer, keyboard: kb === "asking",
698
738
  frame() {
699
739
  const { size, g, area, made } = composed();
700
740
  drawn = { page: made.page, extent: made.extent, room: made.room, cols: g.listCols, area };
@@ -754,10 +794,11 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
754
794
  function act(events) {
755
795
  const read = ++reads;
756
796
  for (const event of events) {
797
+ if (event.keyboard !== undefined) { answered(event.keyboard); continue; }
757
798
  if (took(reduce(state, "paste" in event ? { paste: event.paste, read } : { key: keyId(event), ...(typeof event.text === "string" && !event.alt ? { text: event.text } : {}), read, ...drawn, panel: placed()?.panel ?? null }, keymap))) return;
758
799
  if (typing()) {
759
800
  if (escTimer !== null) { clearTimer(escTimer); escTimer = null; }
760
- through = createThrough({ sequences: backKey, now });
801
+ through = newThrough();
761
802
  break;
762
803
  }
763
804
  }
@@ -771,6 +812,8 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
771
812
  }
772
813
 
773
814
  guard.start();
815
+ // At the wait's end what the key parser kept as a possible beginning of the answer is read as typed.
816
+ if (kb === "asking" && !ended) kbTimer = setTimer(() => { kbTimer = null; guard.attempt(() => { const released = parser.giveUp(); answered(null); if (released.length && !typing()) act(released); watchEscape(); }); }, Math.max(0, answerBy - now()));
774
817
  guard.attempt(() => { if (!ended) Promise.resolve(reader.start()).catch(() => {}); });
775
818
  if (found.ok) guard.attempt(() => { if (!ended) listStart(found.deployment); });
776
819
  guard.attempt(() => guard.draw());
@@ -780,6 +823,7 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
780
823
  const end = await guard.done;
781
824
  if (escTimer !== null) clearTimer(escTimer);
782
825
  if (throughTimer !== null) clearTimer(throughTimer);
826
+ if (kbTimer !== null) clearTimer(kbTimer);
783
827
  // After the alternate screen is left, so the message stays on the screen the user returns to.
784
828
  // One line per change still running, to a terminal or a file only; the status never depends on it.
785
829
  const running = reader.changes?.() ?? [];
@@ -678,6 +678,8 @@ export function model(state, { page, body = page, now, at, cols, area = cols })
678
678
  workspace: r.workspace, machines: r.machines, here: r.here, machine: r.machine, counts: r.counts, readAt: r.readAt, notice: r.notice, note: r.note, empty: r.empty, observed: r.observed,
679
679
  detailTop: state.detailTop, helpTop: state.helpTop, open: state.open !== null,
680
680
  detachKey: state.detachKey, opening: state.opening, openable: false,
681
+ // The chords, `[key id, does]`, while the terminal confirms the kitty keyboard protocol; else null.
682
+ chords: state.keyboard === null ? null : [...state.chords],
681
683
  terminal: state.terminal, onTerminal: false,
682
684
  // The panel's groups (views/frame.mjs), the split and the focused group; the panel stands while
683
685
  // any tab is open. `tabs` is the focused group's strip: each tab in order, the shown one marked,
@@ -9,7 +9,7 @@
9
9
  // removed, and nothing here decides what a failed read means or which view a deployment is in.
10
10
  // Selection is an identity (the shared `instanceId`), never an index, so it survives every read;
11
11
  // the rows it moves among are the model's, in drawn order.
12
- import { ACTIONS, LEADER_KEYS, backKeyLabel, bindings } from "./actions.mjs";
12
+ import { ACTIONS, LEADER_KEYS, backKeyLabel, bindings, chordKeys } from "./actions.mjs";
13
13
  import { collapseKey, displayLine, instanceActs, instanceId, outcomeWords, pendingEntry, spawnProblem } from "./client.mjs";
14
14
  import { defaultDetachKey } from "./config.mjs";
15
15
  import { BUTTON_ORDER, SPAWN_WORDS, SPLIT_WORDS, TAB_WORDS, actDecision, capabilitiesHeight, capabilitiesOf, capabilityUsersOf, disclosure, openDecision, paletteItems, preflightLine, returnedLine, roster, soulNames, soulOfAgent, soulsOf, spawnChoices, spawnChoicesKey, spawnLine, spawnPickerItems, spawnReady, spawnRing, spawnSelector, spawnedRow, switcher, switcherHeight, LIST_WORDS } from "./model.mjs";
@@ -81,6 +81,9 @@ const NO_CAPABILITIES = Object.freeze({ wanted: false, held: new Map(), selected
81
81
  * `platform`'s default, config.mjs defaultDetachKey), and `leaderKey` the key id it is read as
82
82
  * where the TUI reads keys (term/through.mjs backKeyId).
83
83
  * `leader`: `{ read, waiting }` from the leader's read on, or null (see `leading`).
84
+ * `keyboard`: the flags the terminal confirmed for the kitty keyboard protocol (lib/main.mjs, the
85
+ * event `{ keyboard }`), or null while it has not; `chords`: the chords of `platform`, key id ->
86
+ * `does` (actions.mjs chordKeys), read only while `keyboard` is not null (see `leading`).
84
87
  * `palette`: the palette while it is open (see `paletteOpened`), or null. `recent`: the ids of
85
88
  * the instances opened in this run, the latest first.
86
89
  * `act`: the confirmation open in the act view (see `actOpened`), or null; `acted` counts the
@@ -100,7 +103,7 @@ const NO_CAPABILITIES = Object.freeze({ wanted: false, held: new Map(), selected
100
103
  * agentsRoot, agent, reads, words }`, until its row is opened or two reads did not show it;
101
104
  * `previews` the number of the last preview read asked in the run, so that an answer to a prompt
102
105
  * already closed is never taken by the next one. */
103
- export function initialState({ deployment = null, cli, home, entry = null, actions = ACTIONS, ascii = false, platform, detachKey = defaultDetachKey(platform) }) {
106
+ export function initialState({ deployment = null, cli, home, entry = null, actions = ACTIONS, ascii = false, platform = process.platform, detachKey = defaultDetachKey(platform) }) {
104
107
  return Object.freeze({
105
108
  view: deployment === null ? "switcher" : "instances", back: deployment === null ? "switcher" : "instances",
106
109
  ctxs: Object.freeze(deployment === null ? [] : [deployment]), open: deployment,
@@ -111,7 +114,7 @@ export function initialState({ deployment = null, cli, home, entry = null, actio
111
114
  switcher: NO_SWITCHER,
112
115
  listed: NO_LIST,
113
116
  helpTop: 0, actions, ascii, detachKey, opening: null, terminal: null, outcome: null, act: null, acted: 0, starting: new Map(), retiring: new Set(),
114
- leaderKey: backKeyId(detachKey), leader: null, palette: null, recent: Object.freeze([]), souls: NO_SOULS, capabilities: NO_CAPABILITIES,
117
+ leaderKey: backKeyId(detachKey), leader: null, keyboard: null, chords: chordKeys(platform === "darwin", actions), palette: null, recent: Object.freeze([]), souls: NO_SOULS, capabilities: NO_CAPABILITIES,
115
118
  spawn: null, spawning: null, spawnCheck: null, arriving: null, previews: 0, tabs: Object.freeze([]), split: null, group: 0, aside: null,
116
119
  notice: null,
117
120
  });
@@ -1027,6 +1030,11 @@ function leading(state, event, keymap) {
1027
1030
  if (l !== null && l.waiting && !sameRead(l, event)) return twice(next(state, { leader: leaderAt(event.read, false) }));
1028
1031
  return { state: next(state, { leader: leaderAt(event.read, event.rest !== true) }), effect: null };
1029
1032
  }
1033
+ // A chord typed in a terminal (term/through.mjs): the leader then its key, at once.
1034
+ if (event.chord !== undefined) {
1035
+ if (state.keyboard === null || state.terminal?.focus !== "terminal") return { state, effect: null };
1036
+ return led(l === null ? state : next(state, { leader: null }), event.chord, event, keymap);
1037
+ }
1030
1038
  if (typeof event.key !== "string" && !("paste" in event)) return { pass: state };
1031
1039
  if (l !== null && sameRead(l, event)) return { state: l.waiting ? next(state, { leader: leaderAt(l.read, false) }) : state, effect: null };
1032
1040
  if (l !== null && l.waiting) {
@@ -1037,6 +1045,11 @@ function leading(state, event, keymap) {
1037
1045
  }
1038
1046
  const plain = l === null ? state : next(state, { leader: null });
1039
1047
  if (event.key === state.leaderKey) return { state: next(plain, { leader: leaderAt(event.read, true) }), effect: null };
1048
+ // THE CHORDS (docs/tui.md, "Chords"): while the terminal confirms the kitty keyboard protocol, a
1049
+ // chord does what the leader then its key does, from whatever was open. While the leader waits it
1050
+ // is a key not in the leader's table (above): it cancels the leader and is dropped.
1051
+ const chord = state.keyboard === null || typeof event.key !== "string" ? undefined : state.chords.get(event.key);
1052
+ if (chord !== undefined) return led(plain, chord, event, keymap);
1040
1053
  return { pass: plain };
1041
1054
  }
1042
1055
 
@@ -1247,6 +1260,8 @@ function reduced(state, event, keymap) {
1247
1260
  if (lead.pass === undefined) return lead;
1248
1261
  state = lead.pass;
1249
1262
  const stay = { state, effect: null };
1263
+ // The terminal confirmed the kitty keyboard protocol (lib/main.mjs): the chords are read from now on.
1264
+ if (event.keyboard !== undefined) return { state: next(state, { keyboard: event.keyboard }), effect: null };
1250
1265
  if (event.acted !== undefined) return acted(state, event.acted);
1251
1266
  if (event.prepared !== undefined) return prepared(state, event.prepared);
1252
1267
  if (event.given !== undefined) return state.opening?.phase === "preflight" ? { state: next(state, { opening: null }), effect: null } : stay;