@awebai/oats 0.52.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 (98) hide show
  1. package/README.md +2 -1
  2. package/bin/oats.mjs +304 -92
  3. package/docs/capabilities.md +66 -4
  4. package/docs/configuration.md +66 -3
  5. package/docs/desktop-cli-api.md +673 -58
  6. package/docs/desktop-instance-start.md +25 -12
  7. package/docs/execution-targets.md +1 -0
  8. package/docs/implementation.md +175 -11
  9. package/docs/integrations.md +6 -3
  10. package/docs/knowledge.md +2 -2
  11. package/docs/macos-test-runs.md +246 -0
  12. package/docs/official-catalog.md +5 -5
  13. package/docs/packages.md +14 -14
  14. package/docs/release-lane.md +210 -6
  15. package/docs/release-notes/v0.53.0.md +1274 -0
  16. package/docs/schedules.md +7 -1
  17. package/docs/souls-and-instances.md +237 -15
  18. package/docs/tui.md +453 -21
  19. package/docs/upgrading.md +298 -0
  20. package/docs/workspaces.md +3 -3
  21. package/lib/automations.mjs +22 -22
  22. package/lib/claim.mjs +93 -4
  23. package/lib/config-data.mjs +4 -1
  24. package/lib/core.mjs +569 -121
  25. package/lib/instance-events.mjs +19 -1
  26. package/lib/instance-git.mjs +39 -3
  27. package/lib/instance-inspect.mjs +5 -6
  28. package/lib/instance-lifecycle.mjs +145 -18
  29. package/lib/instance-resolution.mjs +59 -6
  30. package/lib/launch-preference.mjs +226 -15
  31. package/lib/local-edit.mjs +118 -0
  32. package/lib/packages.mjs +13 -4
  33. package/lib/pi-bridge.mjs +308 -0
  34. package/lib/refused-text.mjs +11 -0
  35. package/lib/remote.mjs +190 -25
  36. package/lib/resolve.mjs +2 -1
  37. package/lib/retained-after-retire.mjs +2 -2
  38. package/lib/retire-output.mjs +12 -1
  39. package/lib/schedule-host.mjs +6 -35
  40. package/lib/shell-word.mjs +13 -0
  41. package/lib/soul-launch-verbs.mjs +153 -0
  42. package/lib/stable-node.mjs +62 -0
  43. package/lib/teams-verbs.mjs +18 -46
  44. package/lib/workspace.mjs +49 -19
  45. package/package-catalog.json +4 -4
  46. package/package.json +2 -1
  47. package/packages/client/attach-exit.mjs +25 -0
  48. package/packages/client/cli-adapter.mjs +16 -3
  49. package/packages/client/cli-locator.mjs +2 -2
  50. package/packages/client/deployment-contract.mjs +4 -0
  51. package/packages/client/deployment-facts.mjs +71 -10
  52. package/packages/client/deployment-panel.mjs +49 -11
  53. package/packages/client/deployment-read-cli.mjs +7 -3
  54. package/packages/client/display-text.mjs +8 -2
  55. package/packages/client/instance-acts.mjs +46 -10
  56. package/packages/client/instance-events-contract.mjs +4 -2
  57. package/packages/client/instance-presentation.mjs +66 -2
  58. package/packages/client/instance-tree.mjs +23 -14
  59. package/packages/client/kernel-lines.mjs +31 -0
  60. package/packages/client/kernel-made.mjs +23 -0
  61. package/packages/client/launch-prompt-outcome.mjs +51 -16
  62. package/packages/client/lifecycle-contract.mjs +45 -4
  63. package/packages/client/liveness.mjs +14 -1
  64. package/packages/client/own-codes.mjs +31 -0
  65. package/packages/client/panel-views.mjs +18 -11
  66. package/packages/client/readiness-contract.mjs +3 -1
  67. package/packages/client/remote-address.mjs +34 -9
  68. package/packages/client/remote-identity-memory.mjs +94 -0
  69. package/packages/client/remote-roster.mjs +92 -6
  70. package/packages/client/session-attach.mjs +175 -0
  71. package/packages/client/spawn-apply-contract.mjs +16 -4
  72. package/packages/client/spawn-messages.mjs +26 -3
  73. package/packages/client/spawn-preview-cli.mjs +8 -2
  74. package/packages/client/spawn-preview-contract.mjs +5 -1
  75. package/packages/client/terminal-exec.mjs +21 -0
  76. package/packages/client/workspace-choices.mjs +95 -0
  77. package/packages/client/workspace-views.mjs +39 -3
  78. package/packages/record/README.md +21 -0
  79. package/packages/record/bin/setup.mjs +108 -15
  80. package/packages/tui/README.md +30 -12
  81. package/packages/tui/lib/actions.mjs +16 -1
  82. package/packages/tui/lib/client.mjs +32 -1
  83. package/packages/tui/lib/config.mjs +151 -0
  84. package/packages/tui/lib/main.mjs +117 -46
  85. package/packages/tui/lib/model.mjs +392 -0
  86. package/packages/tui/lib/read.mjs +473 -0
  87. package/packages/tui/lib/store.mjs +364 -0
  88. package/packages/tui/lib/term/keys.mjs +44 -0
  89. package/packages/tui/lib/term/screen.mjs +16 -4
  90. package/packages/tui/lib/term/text.mjs +60 -0
  91. package/packages/tui/lib/term/tty.mjs +13 -3
  92. package/packages/tui/lib/views/detail.mjs +46 -0
  93. package/packages/tui/lib/views/frame.mjs +230 -36
  94. package/packages/tui/lib/views/help.mjs +125 -13
  95. package/packages/tui/lib/views/instances.mjs +137 -0
  96. package/packages/tui/lib/views/scroll.mjs +19 -0
  97. package/packages/tui/lib/views/switcher.mjs +97 -0
  98. package/skills/oats-getting-started/SKILL.md +2 -2
@@ -9,9 +9,11 @@
9
9
  // unit on Linux (printed instructions elsewhere);
10
10
  // 3. then runs the first capture pass (the expensive one) unless --dry-run.
11
11
  //
12
- // Everything is derived from the running install: node = process.execPath,
13
- // scripts resolved relative to this file, so it works from a global npm
14
- // install, npx, or a repo checkout alike.
12
+ // Everything is derived from the running install: scripts resolved relative
13
+ // to this file, so it works from a global npm install, npx, or a repo
14
+ // checkout alike. The node written into the hooks and the service is the one
15
+ // handed in (OATS_NODE_BIN, which `oats setup` sets to a path that survives
16
+ // an upgrade of Node), else process.execPath: see recordedNode().
15
17
  //
16
18
  // --owner <name> stream owner (default: LocalHostName on macOS, hostname)
17
19
  // --no-hooks skip step 1
@@ -21,7 +23,7 @@
21
23
  import { execFileSync, spawnSync } from "node:child_process";
22
24
  import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
23
25
  import { homedir, hostname, platform } from "node:os";
24
- import { dirname, join } from "node:path";
26
+ import { dirname, isAbsolute, join } from "node:path";
25
27
  import { fileURLToPath } from "node:url";
26
28
 
27
29
  // Config files deserve the same crash safety as the store's objects:
@@ -32,10 +34,90 @@ function writeFileAtomic(path, content) {
32
34
  renameSync(tmp, path);
33
35
  }
34
36
 
37
+ // The node written into what outlives this process: the hooks and the
38
+ // service. `oats setup` hands in the kernel's answer for a node that survives
39
+ // an upgrade of Node, as OATS_NODE_BIN; this package has no such rule of its
40
+ // own, so run alone it records the node it runs under. What runs at once (the
41
+ // first capture pass) runs under process.execPath whatever is recorded.
42
+ function recordedNode(env = process.env) {
43
+ const handed = env.OATS_NODE_BIN;
44
+ return typeof handed === "string" && isAbsolute(handed) ? handed : process.execPath;
45
+ }
46
+
35
47
  const HERE = dirname(fileURLToPath(import.meta.url));
36
- const NODE = process.execPath;
48
+ const NODE = recordedNode();
37
49
  const CAPTURE = join(HERE, "capture.mjs");
38
50
 
51
+ // Each path is written for the reader it has: a shell (the hook's command),
52
+ // systemd (ExecStart) or an XML parser (the plist). A path of plain
53
+ // characters is written bare by all three, so the files of an install that
54
+ // needs no quoting do not change.
55
+ const SHELL_PLAIN = /^[A-Za-z0-9_./:@%+,-]+$/;
56
+ const SYSTEMD_PLAIN = /^[A-Za-z0-9_./:@+,-]+$/;
57
+
58
+ // A shell word: POSIX single quotes, a quote itself as '\''.
59
+ function shellWord(value) {
60
+ return SHELL_PLAIN.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
61
+ }
62
+
63
+ // The words of a command as /bin/sh reads them, for what setup writes: plain
64
+ // characters, single-quoted runs and \' for a quote, adjacent pieces joined
65
+ // into one word, words apart by spaces or tabs. null when the command holds
66
+ // anything else outside quotes (an expansion, an operator, a redirection, a
67
+ // double quote, a newline, which ends a command) or a quote left open: the
68
+ // shell would do more with it than run those words, so it is not read.
69
+ //
70
+ // Any character above U+007F is part of a word too, as an earlier setup
71
+ // wrote it bare in a path (shellWord now quotes it). bash, dash and zsh end
72
+ // a word only at a space, a tab, a newline or an operator, all ASCII, so a
73
+ // command of such words carries nothing a rewrite would lose. POSIX lets a
74
+ // shell end a word at any blank of its locale (U+3000, say): such a shell
75
+ // would see one more argument of the same command, which a rewrite does not
76
+ // lose either, so no character above U+007F is refused.
77
+ function shellWords(command) {
78
+ const words = [];
79
+ let word = null;
80
+ for (let i = 0; i < command.length; ) {
81
+ const c = command[i];
82
+ if (c === " " || c === "\t") {
83
+ if (word !== null) words.push(word);
84
+ word = null;
85
+ i++;
86
+ } else if (c === "'") {
87
+ const end = command.indexOf("'", i + 1);
88
+ if (end < 0) return null;
89
+ word = (word ?? "") + command.slice(i + 1, end);
90
+ i = end + 1;
91
+ } else if (c === "\\" && command[i + 1] === "'") {
92
+ word = (word ?? "") + "'";
93
+ i += 2;
94
+ } else if (SHELL_PLAIN.test(c) || c > "\x7F") {
95
+ word = (word ?? "") + c;
96
+ i++;
97
+ } else return null;
98
+ }
99
+ if (word !== null) words.push(word);
100
+ return words;
101
+ }
102
+
103
+ // A word of a systemd command line: `%` is a specifier (`%%`), a
104
+ // double-quoted string protects spaces, backslash and double quote are
105
+ // escaped. In an argument `${VAR}` is substituted and a literal dollar is
106
+ // `$$`; the executable is not substituted, and `$$` there names another file.
107
+ // (systemd itself starts no executable whose path holds a quote or a
108
+ // backslash, however it is written: its refusal is what setup reports.)
109
+ function systemdWord(value, { argument = false } = {}) {
110
+ if (SYSTEMD_PLAIN.test(value)) return value;
111
+ let v = value.replace(/%/g, "%%").replace(/\\/g, "\\\\").replace(/"/g, '\\"');
112
+ if (argument) v = v.replace(/\$/g, "$$$$");
113
+ return `"${v}"`;
114
+ }
115
+
116
+ // Text of an XML element.
117
+ function xmlText(value) {
118
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
119
+ }
120
+
39
121
  function parseArgs(argv) {
40
122
  const args = {};
41
123
  for (let i = 0; i < argv.length; i++) {
@@ -77,7 +159,7 @@ if (!/^[A-Za-z0-9._-]+$/.test(owner)) {
77
159
  process.exit(2);
78
160
  }
79
161
 
80
- const hookCommand = `${NODE} ${CAPTURE} --owner ${owner} --quiet`;
162
+ const hookCommand = `${shellWord(NODE)} ${shellWord(CAPTURE)} --owner ${owner} --quiet`;
81
163
  const HOOK = { type: "command", command: hookCommand, async: true, timeout: 120 };
82
164
 
83
165
  console.log(`owner: ${owner}`);
@@ -120,10 +202,19 @@ function installHooks() {
120
202
  // whole tokens) keep it from firing on unrelated hooks that merely
121
203
  // mention similar words; when in doubt it errs toward appending a new
122
204
  // group, never toward overwriting someone else's command.
205
+ //
206
+ // The tokens are the command's words as the shell reads them
207
+ // (shellWords), and only a command that reads whole that way can be
208
+ // ours: one that also carries a second command, an operator or a
209
+ // redirection would lose it when rewritten. It reads the quoted form and
210
+ // every command written before paths were quoted, except one with `=`,
211
+ // `~` or another ASCII character outside the plain set left bare in a
212
+ // path, or with a space in one, which was split.
123
213
  const ours = (h) => {
124
214
  if (h?.type !== "command") return false;
125
- const tokens = String(h.command).trim().split(/\s+/);
215
+ const tokens = shellWords(String(h.command));
126
216
  return (
217
+ tokens !== null &&
127
218
  tokens.length >= 2 &&
128
219
  tokens[1].endsWith("/capture.mjs") &&
129
220
  tokens.includes("--owner") &&
@@ -133,6 +224,8 @@ function installHooks() {
133
224
  for (const event of ["Stop", "SessionEnd"]) {
134
225
  const groups = (settings.hooks[event] = settings.hooks[event] ?? []);
135
226
  let found = false;
227
+ // Every hook that is ours gets the current command and none is removed,
228
+ // two in one event included: the shape is not proof of ownership.
136
229
  for (const group of groups) {
137
230
  for (const hook of group.hooks ?? []) {
138
231
  if (!ours(hook)) continue;
@@ -173,8 +266,8 @@ function installServiceDarwin() {
173
266
  <string>${label}</string>
174
267
  <key>ProgramArguments</key>
175
268
  <array>
176
- <string>${NODE}</string>
177
- <string>${CAPTURE}</string>
269
+ <string>${xmlText(NODE)}</string>
270
+ <string>${xmlText(CAPTURE)}</string>
178
271
  <string>--watch</string>
179
272
  <string>--owner</string>
180
273
  <string>${owner}</string>
@@ -186,9 +279,9 @@ function installServiceDarwin() {
186
279
  <key>ThrottleInterval</key>
187
280
  <integer>60</integer>
188
281
  <key>StandardOutPath</key>
189
- <string>${logPath}</string>
282
+ <string>${xmlText(logPath)}</string>
190
283
  <key>StandardErrorPath</key>
191
- <string>${logPath}</string>
284
+ <string>${xmlText(logPath)}</string>
192
285
  </dict>
193
286
  </plist>
194
287
  `;
@@ -211,7 +304,7 @@ function installServiceDarwin() {
211
304
  } else {
212
305
  console.error(
213
306
  `service: wrote ${path} but launchctl bootstrap failed (${(boot.stderr || "").trim()}); ` +
214
- `load it manually: launchctl bootstrap gui/${uid} ${path}`,
307
+ `load it manually: launchctl bootstrap gui/${uid} ${shellWord(path)}`,
215
308
  );
216
309
  }
217
310
  }
@@ -222,7 +315,7 @@ function installServiceLinux() {
222
315
  Description=turn-record capture watcher
223
316
 
224
317
  [Service]
225
- ExecStart=${NODE} ${CAPTURE} --watch --owner ${owner}
318
+ ExecStart=${systemdWord(NODE)} ${systemdWord(CAPTURE, { argument: true })} --watch --owner ${owner}
226
319
  Restart=always
227
320
  RestartSec=60
228
321
 
@@ -262,7 +355,7 @@ function installService() {
262
355
  else {
263
356
  console.log(
264
357
  `service: no service template for ${os}; run this in the background yourself:\n` +
265
- ` ${NODE} ${CAPTURE} --watch --owner ${owner}`,
358
+ ` ${shellWord(NODE)} ${shellWord(CAPTURE)} --watch --owner ${owner}`,
266
359
  );
267
360
  }
268
361
  }
@@ -276,6 +369,6 @@ if (dry) {
276
369
  console.log("dry run: no first capture pass");
277
370
  } else {
278
371
  console.log("running first capture pass (the initial one can take minutes)...");
279
- const pass = spawnSync(NODE, [CAPTURE, "--owner", owner], { stdio: "inherit" });
372
+ const pass = spawnSync(process.execPath, [CAPTURE, "--owner", owner], { stdio: "inherit" });
280
373
  process.exit(pass.status ?? 1);
281
374
  }
@@ -4,12 +4,14 @@
4
4
  for people who work in terminals and on machines with no display. It ships
5
5
  inside `@awebai/oats` and is never published on its own.
6
6
 
7
- **It is a preview.** This version draws the frame, answers `?` (help) and `q`
8
- (quit), and reads nothing from the kernel yet; the views arrive in later
9
- releases. While it is a preview its screens may change without notice.
7
+ **It is a preview.** This version shows a workspace's instances, on this
8
+ machine and on the other machines registered on it, in one list, and follows
9
+ them; it changes nothing. While it is a preview its screens and its
10
+ configuration file may change without notice.
10
11
 
11
- [`docs/tui.md`](../../docs/tui.md) is the reference: how to start it, the keys,
12
- the complete list of what it changes in the terminal and restores, and what it
12
+ [`docs/tui.md`](../../docs/tui.md) is the reference: how to start it, what the
13
+ view shows, the keys and how to change them, what it reads and runs, the
14
+ complete list of what it changes in the terminal and restores, and what it
13
15
  never does.
14
16
 
15
17
  ## For developers
@@ -17,16 +19,20 @@ never does.
17
19
  | path | contents |
18
20
  |---|---|
19
21
  | `bin/tui.mjs` | the entry `bin/oats.mjs` loads: it imports the whole module graph, then runs `main()` |
20
- | `lib/main.mjs` | the loop: state, a pure `reduce(state, event)`, render, write |
21
- | `lib/actions.mjs` | the action table: the reducer and the help both read it |
22
- | `lib/client.mjs` | the one module that imports the shared readers (`packages/client/`) |
22
+ | `lib/main.mjs` | the start (arguments, environment, terminal, `tui.json`, deployment, kernel) and the loop: events through `reduce`, effects out, the frame drawn |
23
+ | `lib/actions.mjs` | the action table and its default keys: the reducer, the footer and the help read the effective one |
24
+ | `lib/config.mjs` | `tui.json`: read once, checked, and the effective action table |
25
+ | `lib/client.mjs` | the one module that imports the shared readers (`packages/client/`), and the client's terms |
26
+ | `lib/read.mjs` | the effects of reading: the deployment, the kernel record, the observer of every deployment opened in the run, the roster of other machines (`oats server roster --json`), the refresh loop, the liveness collector, ending every child, and the two looks at the file system the switcher needs (the entries of `~/Agents`, and whether a picked folder is a deployment) |
27
+ | `lib/store.mjs` | the state and `reduce(state, event)`: pure |
28
+ | `lib/model.mjs` | from the state to the rows and the detail to draw, and to the switcher's rows, by calling the shared readers: pure, no cell position |
23
29
  | `lib/term/keys.mjs` | bytes to key events: a pure parser with an injected clock |
24
30
  | `lib/term/width.mjs` | the cells a grapheme takes |
25
31
  | `lib/term/text.mjs` | safe text, the only thing the screen draws: `lit()` and `shown()` |
26
32
  | `lib/term/style.mjs` | style values: the sixteen ANSI colours and four attributes |
27
33
  | `lib/term/screen.mjs` | the cell buffer and the bytes of a frame |
28
34
  | `lib/term/tty.mjs` | the guard: enter, leave, signals, suspend, resize, one write per frame |
29
- | `lib/views/` | pure functions from state and size to rows of safe text |
35
+ | `lib/views/` | pure functions from the model and a size to rows of spans: the frame, the list, the detail, the switcher, the help |
30
36
 
31
37
  Rules the tests pin (`test/tui-boundary.test.mjs` reads the files):
32
38
 
@@ -36,11 +42,23 @@ Rules the tests pin (`test/tui-boundary.test.mjs` reads the files):
36
42
  one dynamic import where `bin/oats.mjs` dispatches the word.
37
43
  - Only `term/screen.mjs` and `term/tty.mjs` produce an ESC byte. Views are
38
44
  pure: no IO, no clock, no escape bytes.
45
+ - No function of this package decodes a kernel answer, groups or orders
46
+ instances, or decides what a failed read means: `lib/model.mjs` and
47
+ `lib/read.mjs` call the shared readers and pass their answers on. A string
48
+ the shared readers give reaches the screen through `shown()`.
49
+ - The store holds no size and no cell: a key event carries the height of the
50
+ panes as the last frame drew them.
51
+ - Every child process runs in a session of its own and is ended on every way
52
+ out; this version starts only reads.
39
53
  - The screen takes safe text only. Text the TUI did not write goes through
40
54
  `shown()`; `lit()` is for the TUI's own words and refuses anything the
41
55
  display filter would change, a run of spaces included, so a row is spans
42
56
  placed by column, never one padded string.
43
57
 
44
- Tests: `node --test packages/tui/test/*.test.mjs` (no dependency needed), the
45
- root tests `test/tui-*.test.mjs`, and the end-to-end tests in a real tmux on a
46
- private socket (`test/tui-terminal.test.mjs`).
58
+ Tests: `node --test packages/tui/test/*.test.mjs`, the root tests
59
+ `test/tui-*.test.mjs`, and the end-to-end tests in a real tmux on a private
60
+ socket (`test/tui-terminal.test.mjs`). All of them need the root's install
61
+ (`npm ci` at the repository root). The package has no dependency of its own,
62
+ but one of its tests runs the real kernel, which has: "KERNEL_BIN is this
63
+ install's own bin/oats.mjs, and its `version --json` is a record the probe
64
+ accepts" (`packages/tui/test/read.test.mjs`).
@@ -1,7 +1,22 @@
1
1
  // The action table: what the TUI can do and the keys that do it. The reducer and the help view
2
2
  // both read it, so the help cannot name a key the program does not act on. `keys` are key ids
3
- // (term/keys.mjs keyId); they are the part a user's tui.json will replace.
3
+ // (term/keys.mjs keyId); they are the part a user's tui.json replaces (config.mjs), so everything
4
+ // that acts on a key or names one reads the EFFECTIVE table it is handed, never this constant.
4
5
  export const ACTIONS = Object.freeze([
6
+ { id: "up", keys: ["up", "k"], label: "up" },
7
+ { id: "down", keys: ["down", "j"], label: "down" },
8
+ { id: "top", keys: ["g", "home"], label: "first" },
9
+ { id: "bottom", keys: ["G", "end"], label: "last" },
10
+ { id: "page-up", keys: ["pageup"], label: "page up" },
11
+ { id: "page-down", keys: ["pagedown"], label: "page down" },
12
+ { id: "collapse", keys: ["left", "h"], label: "collapse, or go to the parent" },
13
+ { id: "expand", keys: ["right", "l"], label: "expand, or go to the first child" },
14
+ { id: "detail", keys: ["tab"], label: "detail" },
15
+ { id: "filter", keys: ["/"], label: "filter" },
16
+ { id: "refresh", keys: ["r"], label: "refresh" },
17
+ { id: "instances", keys: ["1"], label: "instances" },
18
+ { id: "workspaces", keys: ["w"], label: "workspaces" },
19
+ { id: "open-workspace", keys: ["enter"], label: "open" },
5
20
  { id: "help", keys: ["?"], label: "help" },
6
21
  { id: "close", keys: ["escape"], label: "close" },
7
22
  { id: "quit", keys: ["q", "ctrl+c"], label: "quit" },
@@ -1,4 +1,35 @@
1
1
  // The ONE module of packages/tui/ that imports the shared client home (packages/client/): the rest
2
2
  // of the TUI names no reader path, so what the TUI takes from the shared readers is this list
3
- // (test/tui-boundary.test.mjs pins it). The filter is the Desktop's own, never a copy.
3
+ // (test/tui-boundary.test.mjs pins it). Every function here is the Desktop's own, never a copy:
4
+ // the roster, its order, its words and what a failed read becomes are decided there, once, for
5
+ // both clients. test/client-boundary.test.mjs holds each name to the home's stable surface.
6
+ import { fileURLToPath } from "node:url";
7
+ import { clientTerms } from "../../client/client-terms.mjs";
8
+
4
9
  export { displayLine, DETAIL_WITHHELD } from "../../client/display-text.mjs";
10
+ export { parseProbeStdout, acceptProbe, cliRecord } from "../../client/cli-locator.mjs";
11
+ export { cliDeploymentRead } from "../../client/deployment-read-cli.mjs";
12
+ export { cliRemoteRoster } from "../../client/cli-adapter.mjs";
13
+ export { createDeploymentObserver, mapBounded, MAX_DEPLOYMENT_OBSERVATIONS } from "../../client/deployment-observer.mjs";
14
+ export { createRefreshLoop } from "../../client/refresh-loop.mjs";
15
+ export { rosterRows, livenessInput, livenessAnswers, panelInstances, pendingEntry, failedEntry, observedEntry } from "../../client/deployment-panel.mjs";
16
+ export { panelData, cliReadsRemotes, workspaceChoices, viewModel } from "../../client/panel-views.mjs";
17
+ export { remoteRosterState } from "../../client/remote-roster.mjs";
18
+ export { observeIdentities, identityMemory } from "../../client/remote-identity-memory.mjs";
19
+ export { workspaceChoiceRows, choiceMatches, UNMATCHED_SECTION } from "../../client/workspace-choices.mjs";
20
+ export { shortPath } from "../../client/deployment-label.mjs";
21
+ export { instanceId, instanceVisibleInTree, waitingRollup, collapseKey, filterInstanceTree, hasInstanceChildren, heldHome } from "../../client/instance-tree.mjs";
22
+ export { rosterSections, deploymentState, rowStale, primaryDeployment, isMultiDeployment } from "../../client/roster-sections.mjs";
23
+ export { runtimeState, runtimeCounts, originLead } from "../../client/instance-presentation.mjs";
24
+ export { waitingClaim, waitingLabel, waitedText, waitingClock, waitingBelowText } from "../../client/waiting-on-you.mjs";
25
+ export { instanceActs } from "../../client/instance-acts.mjs";
26
+ export { INSTANCE_VARIABLES } from "../../client/kernel-environment.mjs";
27
+ export { validateWorkspace, deploymentsInside } from "../../client/workspace-admission.mjs";
28
+
29
+ /** The words a shared sentence uses where it names the client that shows it (client-terms.mjs).
30
+ * Made once, here: every shared function that takes `terms` is passed this constant, and refuses
31
+ * anything else. */
32
+ export const TERMS = clientTerms({ name: "oats tui", self: "oats tui", selfInitial: "oats tui", update: "OATS", thisMachine: "This machine" });
33
+
34
+ /** The liveness collector, a program of the shared home: started as a child, never imported. */
35
+ export const COLLECTOR = fileURLToPath(new URL("../../client/liveness-main.mjs", import.meta.url));
@@ -0,0 +1,151 @@
1
+ // The user's key file, tui.json: which keys do what, and whether the screen is drawn in ASCII.
2
+ // Read once at start and never written. A file that is wrong in any way is refused whole, each
3
+ // problem as one line that says what to change: the TUI resolves no conflict and guesses nothing
4
+ // (there is no "last wins"), because a key that silently does something else is worse than a
5
+ // program that does not start. The lines go to a terminal, so nothing taken from the file, and
6
+ // no path, reaches one unless it is plain printable ASCII.
7
+ import { closeSync, openSync, readSync, statSync } from "node:fs";
8
+ import { homedir } from "node:os";
9
+ import { isAbsolute, join } from "node:path";
10
+ import { ACTIONS, bindings, keyLabel } from "./actions.mjs";
11
+ import { displayLine } from "./client.mjs";
12
+ import { isKeyId } from "./term/keys.mjs";
13
+
14
+ /** The largest tui.json that is read, in bytes. A larger file is refused by its size, unread. */
15
+ export const CONFIG_LIMIT = 64 * 1024;
16
+
17
+ const TOO_LARGE = `it is larger than ${CONFIG_LIMIT / 1024} KiB`;
18
+ const NOT_AN_OBJECT = 'it is not one JSON object, like {"keys": {"quit": ["q"]}}';
19
+ const SETTINGS = "the settings are keys and ascii";
20
+ const KEY_IDS = "key ids look like q, ctrl+c, shift+tab, f5, space";
21
+ /** A name from the file is echoed only when it is this: it cannot move a cursor or fill a screen. */
22
+ const PLAIN_NAME = /^[\x21-\x7e]{1,40}$/;
23
+ const PLAIN_PATH = /^[\x20-\x7e]{1,200}$/;
24
+ const ERROR_CODE = /^[A-Z][A-Z0-9_]{0,30}$/;
25
+ /** The most problems that are printed: a file of nothing but mistakes must not fill a terminal. */
26
+ export const MAX_PROBLEMS = 20;
27
+
28
+ const plain = (name) => typeof name === "string" && PLAIN_NAME.test(name);
29
+ /** Whether the footer and the help can name a key: its label is drawn as text from outside (the
30
+ * shared display filter), and a label that filter would change would name another key, or none.
31
+ * Such a key (a bidi override, a combining mark on a space) is refused here, with the file named,
32
+ * where a key the views cannot draw would otherwise be bound and never said. */
33
+ const nameable = (key) => { const label = keyLabel(key); return displayLine(label) === label; };
34
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
35
+ /** Never the text of an error, which may hold anything: its code, when that is a plain one. */
36
+ const unreadable = (error) => { const code = error?.code; return `it cannot be read${typeof code === "string" && ERROR_CODE.test(code) ? ` (${code})` : ""}`; };
37
+
38
+ /** The path of tui.json: `$XDG_CONFIG_HOME/oats/tui.json` when that variable is set, not empty
39
+ * and absolute (the XDG rule: a relative value is ignored), else `<home>/.config/oats/tui.json`. */
40
+ export function configPath(env, home) {
41
+ const xdg = env?.XDG_CONFIG_HOME;
42
+ return join(typeof xdg === "string" && xdg !== "" && isAbsolute(xdg) ? xdg : join(home, ".config"), "oats", "tui.json");
43
+ }
44
+
45
+ /** What tui.json says, checked: `value` is the file already parsed, `defaults` the action table.
46
+ * Pure. Answers `{ ok: true, actions, ascii }` or `{ ok: false, problems }`.
47
+ *
48
+ * `actions` is a frozen table shaped exactly like `defaults` (same order, ids and labels, frozen
49
+ * rows with frozen `keys`) in which the list of each action the file names REPLACES that action's
50
+ * keys; an empty list unbinds it, and an action the file does not name keeps its keys. It is
51
+ * proved with bindings() before it is answered, so no key in it does two things.
52
+ *
53
+ * `problems` are plain ASCII clauses, one per problem, without the line's prefix. A problem with
54
+ * the file's shape is answered alone; the problems inside `keys` are all answered, in the file's
55
+ * order. A key given to two actions is judged with the kept defaults included and names both. An
56
+ * action whose list is refused takes no part in that judgement: what it was meant to hold is not
57
+ * known. The ids of `defaults` are the program's own; one that is not plain is still never echoed. */
58
+ export function effectiveConfig(value, defaults = ACTIONS) {
59
+ if (!isObject(value)) return { ok: false, problems: [NOT_AN_OBJECT] };
60
+ for (const [setting, given] of Object.entries(value)) {
61
+ if (setting === "keys") { if (!isObject(given)) return { ok: false, problems: ['keys must be an object, like {"quit": ["q"]}'] }; }
62
+ else if (setting === "ascii") { if (typeof given !== "boolean") return { ok: false, problems: ["ascii must be true or false"] }; }
63
+ else return { ok: false, problems: [`${plain(setting) ? `unknown setting ${setting}` : "a setting whose name cannot be shown is unknown"}; ${SETTINGS}`] };
64
+ }
65
+
66
+ const ids = new Set(defaults.map((action) => action.id));
67
+ const say = (id) => (plain(id) ? id : "an action whose id cannot be shown");
68
+ const keyOf = (key, id) => (plain(key) ? `the key ${key} of ${say(id)}` : key === "" ? `an empty key of ${say(id)}` : `a key of ${say(id)} that cannot be shown`);
69
+ const lists = Object.hasOwn(value, "keys") ? Object.entries(value.keys) : [];
70
+ const named = new Map(lists.filter(([id]) => ids.has(id)).map(([id]) => [id, []]));
71
+ const problems = [], owner = new Map();
72
+ /** One key, one action: the first to hold a key keeps it, and every later claim is a problem. */
73
+ const claim = (key, id) => {
74
+ if (!owner.has(key)) { owner.set(key, id); return true; }
75
+ const which = plain(key) ? `the key ${key}` : "a key that cannot be shown";
76
+ problems.push(owner.get(key) === id ? `${which} is given to ${say(id)} twice; list it once` : `${which} is given to ${say(owner.get(key))} and to ${say(id)}; a key does one thing`);
77
+ return false;
78
+ };
79
+ // The keys the file leaves alone are held first, so a key the file gives away twice is found
80
+ // where the file gives it. (Two of them clashing is a defect of the table, said the same way.)
81
+ for (const action of defaults) if (!named.has(action.id)) for (const key of action.keys) claim(key, action.id);
82
+ for (const [id, list] of lists) {
83
+ if (!ids.has(id)) {
84
+ problems.push(`${plain(id) ? `unknown action ${id}` : "an action id that cannot be shown is unknown"}; the actions are ${[...ids].filter(plain).join(", ")}`);
85
+ } else if (!Array.isArray(list) || !list.every((key) => typeof key === "string")) {
86
+ problems.push(`${say(id)} must be a list of key ids, like ["q", "ctrl+c"]`);
87
+ } else {
88
+ for (const key of list) {
89
+ if (!isKeyId(key)) problems.push(`${keyOf(key, id)} is not a key id; ${KEY_IDS}`);
90
+ else if (!nameable(key)) problems.push(`${keyOf(key, id)} is a key the help cannot name; give a key whose character can be shown`);
91
+ else if (claim(key, id)) named.get(id).push(key);
92
+ }
93
+ if (id === "quit" && list.length === 0) problems.push("quit has no key; give it one");
94
+ }
95
+ }
96
+ if (problems.length > 0) return { ok: false, problems };
97
+
98
+ const actions = Object.freeze(defaults.map((action) => Object.freeze({ ...action, keys: Object.freeze([...(named.get(action.id) ?? action.keys)]) })));
99
+ try { bindings(actions); } catch { return { ok: false, problems: ["a key is given to two actions; a key does one thing"] }; }
100
+ return { ok: true, actions, ascii: value.ascii === true };
101
+ }
102
+
103
+ /** The file system as loadConfig needs it. `stat` follows symbolic links and answers null for a
104
+ * path that does not exist, which includes a path under something that is not a directory (an
105
+ * XDG_CONFIG_HOME of /dev/null); every other failure is thrown. `read` never takes in more than
106
+ * the limit and one byte, whatever the file became since it was measured. */
107
+ const NODE_IO = Object.freeze({
108
+ stat(path) {
109
+ try {
110
+ const found = statSync(path);
111
+ return { file: found.isFile(), size: found.size };
112
+ } catch (error) {
113
+ if (error?.code === "ENOENT" || error?.code === "ENOTDIR") return null;
114
+ throw error;
115
+ }
116
+ },
117
+ read(path) {
118
+ const fd = openSync(path, "r");
119
+ try {
120
+ const bytes = Buffer.alloc(CONFIG_LIMIT + 1);
121
+ let length = 0, got = 0;
122
+ while (length < bytes.length && (got = readSync(fd, bytes, length, bytes.length - length, null)) > 0) length += got;
123
+ if (length > CONFIG_LIMIT) throw Object.assign(new Error("tui.json grew past the limit while it was read"), { code: "EFBIG" });
124
+ return bytes.toString("utf8", 0, length);
125
+ } finally { closeSync(fd); }
126
+ },
127
+ });
128
+
129
+ /** Read tui.json, once. Answers `{ ok: true, actions, ascii, path }`, or `{ ok: false, lines }`:
130
+ * the complete lines to print (no trailing newline), after which the TUI must not start.
131
+ * No file is the defaults: `actions` is ACTIONS itself and `ascii` is false.
132
+ *
133
+ * `io` is the file system (node:fs when omitted): `io.stat(path)` answers `{ file, size }` after
134
+ * following symbolic links, or null when the path does not exist, and throws for anything else;
135
+ * `io.read(path)` answers the text. The size is checked before `read` is called, so a file over
136
+ * CONFIG_LIMIT, a directory or a FIFO is never opened. A line holds the path only when it is
137
+ * printable ASCII, and never the text of an error: only its code, when it is a plain one. */
138
+ export function loadConfig({ env = process.env, home = homedir(), io = NODE_IO } = {}) {
139
+ const path = configPath(env, home);
140
+ 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);
141
+ 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)`) });
142
+ let found, text, value;
143
+ try { found = io.stat(path); } catch (error) { return refused([unreadable(error)]); }
144
+ if (found === null) return { ok: true, actions: ACTIONS, ascii: false, path };
145
+ if (found.file !== true) return refused(["it is not a regular file"]);
146
+ if (!(typeof found.size === "number" && found.size <= CONFIG_LIMIT)) return refused([TOO_LARGE]); // read only what is known to fit
147
+ try { text = io.read(path); } catch (error) { return refused([error?.code === "EFBIG" ? TOO_LARGE : unreadable(error)]); }
148
+ try { value = JSON.parse(text); } catch { return refused(["it is not valid JSON"]); }
149
+ const checked = effectiveConfig(value);
150
+ return checked.ok ? { ...checked, path } : refused(checked.problems);
151
+ }