@awebai/oats 0.52.0 → 0.54.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 (100) hide show
  1. package/README.md +2 -1
  2. package/bin/oats.mjs +314 -92
  3. package/docs/capabilities.md +66 -4
  4. package/docs/configuration.md +66 -3
  5. package/docs/design/2026-09-23-workspace-module-contracts.md +3 -0
  6. package/docs/desktop-cli-api.md +696 -60
  7. package/docs/desktop-instance-start.md +25 -12
  8. package/docs/execution-targets.md +1 -0
  9. package/docs/implementation.md +184 -12
  10. package/docs/integrations.md +6 -3
  11. package/docs/knowledge.md +2 -2
  12. package/docs/macos-test-runs.md +246 -0
  13. package/docs/official-catalog.md +5 -5
  14. package/docs/packages.md +14 -14
  15. package/docs/release-lane.md +210 -6
  16. package/docs/release-notes/v0.53.0.md +1288 -0
  17. package/docs/release-notes/v0.54.0.md +142 -0
  18. package/docs/schedules.md +7 -1
  19. package/docs/souls-and-instances.md +239 -16
  20. package/docs/tui.md +453 -21
  21. package/docs/upgrading.md +310 -0
  22. package/docs/workspaces.md +123 -3
  23. package/lib/automations.mjs +22 -22
  24. package/lib/claim.mjs +93 -4
  25. package/lib/config-data.mjs +4 -1
  26. package/lib/core.mjs +569 -121
  27. package/lib/instance-events.mjs +19 -1
  28. package/lib/instance-git.mjs +39 -3
  29. package/lib/instance-inspect.mjs +5 -6
  30. package/lib/instance-lifecycle.mjs +145 -18
  31. package/lib/instance-resolution.mjs +59 -6
  32. package/lib/launch-preference.mjs +226 -15
  33. package/lib/local-edit.mjs +118 -0
  34. package/lib/packages.mjs +18 -5
  35. package/lib/pi-bridge.mjs +308 -0
  36. package/lib/refused-text.mjs +11 -0
  37. package/lib/remote.mjs +404 -60
  38. package/lib/resolve.mjs +2 -1
  39. package/lib/retained-after-retire.mjs +2 -2
  40. package/lib/retire-output.mjs +12 -1
  41. package/lib/schedule-host.mjs +6 -35
  42. package/lib/shell-word.mjs +13 -0
  43. package/lib/soul-launch-verbs.mjs +153 -0
  44. package/lib/stable-node.mjs +62 -0
  45. package/lib/teams-verbs.mjs +18 -46
  46. package/lib/workspace.mjs +75 -27
  47. package/package-catalog.json +4 -4
  48. package/package.json +2 -1
  49. package/packages/client/attach-exit.mjs +25 -0
  50. package/packages/client/cli-adapter.mjs +16 -3
  51. package/packages/client/cli-locator.mjs +2 -2
  52. package/packages/client/deployment-contract.mjs +4 -0
  53. package/packages/client/deployment-facts.mjs +71 -10
  54. package/packages/client/deployment-panel.mjs +49 -11
  55. package/packages/client/deployment-read-cli.mjs +7 -3
  56. package/packages/client/display-text.mjs +8 -2
  57. package/packages/client/instance-acts.mjs +46 -10
  58. package/packages/client/instance-events-contract.mjs +4 -2
  59. package/packages/client/instance-presentation.mjs +66 -2
  60. package/packages/client/instance-tree.mjs +23 -14
  61. package/packages/client/kernel-lines.mjs +31 -0
  62. package/packages/client/kernel-made.mjs +23 -0
  63. package/packages/client/launch-prompt-outcome.mjs +51 -16
  64. package/packages/client/lifecycle-contract.mjs +45 -4
  65. package/packages/client/liveness.mjs +14 -1
  66. package/packages/client/own-codes.mjs +31 -0
  67. package/packages/client/panel-views.mjs +18 -11
  68. package/packages/client/readiness-contract.mjs +3 -1
  69. package/packages/client/remote-address.mjs +34 -9
  70. package/packages/client/remote-identity-memory.mjs +94 -0
  71. package/packages/client/remote-roster.mjs +92 -6
  72. package/packages/client/session-attach.mjs +175 -0
  73. package/packages/client/spawn-apply-contract.mjs +16 -4
  74. package/packages/client/spawn-messages.mjs +26 -3
  75. package/packages/client/spawn-preview-cli.mjs +8 -2
  76. package/packages/client/spawn-preview-contract.mjs +5 -1
  77. package/packages/client/terminal-exec.mjs +21 -0
  78. package/packages/client/workspace-choices.mjs +95 -0
  79. package/packages/client/workspace-views.mjs +39 -3
  80. package/packages/record/README.md +21 -0
  81. package/packages/record/bin/setup.mjs +108 -15
  82. package/packages/tui/README.md +30 -12
  83. package/packages/tui/lib/actions.mjs +16 -1
  84. package/packages/tui/lib/client.mjs +32 -1
  85. package/packages/tui/lib/config.mjs +151 -0
  86. package/packages/tui/lib/main.mjs +117 -46
  87. package/packages/tui/lib/model.mjs +392 -0
  88. package/packages/tui/lib/read.mjs +473 -0
  89. package/packages/tui/lib/store.mjs +364 -0
  90. package/packages/tui/lib/term/keys.mjs +44 -0
  91. package/packages/tui/lib/term/screen.mjs +16 -4
  92. package/packages/tui/lib/term/text.mjs +60 -0
  93. package/packages/tui/lib/term/tty.mjs +13 -3
  94. package/packages/tui/lib/views/detail.mjs +46 -0
  95. package/packages/tui/lib/views/frame.mjs +230 -36
  96. package/packages/tui/lib/views/help.mjs +125 -13
  97. package/packages/tui/lib/views/instances.mjs +137 -0
  98. package/packages/tui/lib/views/scroll.mjs +19 -0
  99. package/packages/tui/lib/views/switcher.mjs +97 -0
  100. package/skills/oats-getting-started/SKILL.md +8 -2
@@ -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
+ }
@@ -1,90 +1,160 @@
1
- // `oats tui` (preview): the loop. State, a pure reduce(state, event), render, write.
2
- // This version draws the frame, answers help and quit, and reads nothing from the kernel:
3
- // what it delivers is the terminal layer the views will stand on (docs/tui.md).
4
- import { ACTIONS, bindings } from "./actions.mjs";
5
- import { displayLine } from "./client.mjs";
1
+ // `oats tui` (preview): the loop. Events from the keyboard and from the reader go through one
2
+ // pure reduce(state, event); what only the loop can do comes back as an effect; the frame is
3
+ // drawn from the state. This version shows a workspace's instances, on this machine and on the
4
+ // machines registered here, and follows them; it changes nothing (docs/tui.md).
5
+ import { homedir } from "node:os";
6
+ import { resolve } from "node:path";
7
+ import { bindings } from "./actions.mjs";
8
+ import { displayLine, pendingEntry } from "./client.mjs";
9
+ import { loadConfig } from "./config.mjs";
10
+ import { model, roster } from "./model.mjs";
11
+ import { admitDeployment, createReader, findDeployment, leaveInstance, offeredDeployments, probeKernel } from "./read.mjs";
12
+ import { initialState, reduce } from "./store.mjs";
6
13
  import { createKeyParser, keyId } from "./term/keys.mjs";
7
14
  import { createScreen, glyphs } from "./term/screen.mjs";
8
15
  import { colorEnabled } from "./term/style.mjs";
9
16
  import { createGuard, isTerminal } from "./term/tty.mjs";
10
- import { frame } from "./views/frame.mjs";
17
+ import { frame, layout } from "./views/frame.mjs";
11
18
 
12
- export const USAGE = "oats tui [--ascii]";
19
+ export const USAGE = "oats tui [--dir <path>] [--ascii]";
13
20
  const HELP = `Usage:
14
21
  ${USAGE}
15
22
 
16
- The OATS terminal client (preview): a full-screen view of a deployment's agents.
17
- This version draws the frame only. Keys: ? help, q quit. docs/tui.md has the rest.
23
+ The OATS terminal client (preview): a full-screen view of a workspace's instances,
24
+ on this machine and on the machines registered here. It follows them and changes
25
+ nothing. Keys: ? help, w workspaces, q quit.
26
+ docs/tui.md has the rest.
18
27
 
19
- --ascii draw rules and marks in ASCII, whatever the locale
28
+ --dir <path> the deployment, or a directory inside one (default: where you are)
29
+ --ascii draw rules and marks in ASCII, whatever the locale
20
30
  `;
21
31
  export const NO_TERMINAL = "oats: `oats tui` needs a terminal on stdin and stdout (E_NO_TERMINAL); `oats status` prints the instances once";
32
+ /** A path is echoed only when it is plain: these lines go to a terminal. */
33
+ const plainPath = (path) => (typeof path === "string" && /^[\x20-\x7e]{1,200}$/.test(path) ? path : "that directory");
34
+ export const noDeployment = (dir) => `oats: no OATS deployment at or above ${plainPath(dir)} (E_NO_DEPLOYMENT); name one with \`oats tui --dir <path>\``;
35
+ export const noKernel = (reason) => `oats: \`oats tui\` could not use its own kernel (E_TUI_KERNEL): ${displayLine(reason) ?? "it gave no reason"}`;
22
36
 
23
- /** The arguments of this version: `--ascii`, `--help`/`-h`. Everything else is refused, `--dir`
24
- * and `--server` included: it reads no deployment yet. */
37
+ /** The arguments: `--ascii`, `--help`/`-h`, `--dir <path>` and `--dir=<path>`. Everything else is
38
+ * refused, `--server` included: a run names no machine, it reads every one registered here. */
25
39
  export function parseArgs(argv) {
26
- const options = { ascii: false, help: false };
27
- for (const arg of argv) {
40
+ const options = { ascii: false, help: false, dir: null };
41
+ // The argument is echoed only when it is plain: this line goes to a terminal.
42
+ const refused = (arg) => ({ error: `oats: \`oats tui\` takes no argument ${/^[\x21-\x7e]{1,40}$/.test(arg) ? arg : "like that one"} (E_BAD_ARGS); usage: ${USAGE}` });
43
+ for (let i = 0; i < argv.length; i++) {
44
+ const arg = argv[i];
28
45
  if (arg === "--ascii") options.ascii = true;
29
46
  else if (arg === "--help" || arg === "-h") options.help = true;
30
- // The argument is echoed only when it is plain: this line goes to a terminal.
31
- else return { error: `oats: \`oats tui\` takes no argument ${/^[\x21-\x7e]{1,40}$/.test(arg) ? arg : "like that one"} (E_BAD_ARGS); usage: ${USAGE}` };
47
+ else if (arg === "--dir" && typeof argv[i + 1] === "string" && argv[i + 1] !== "") options.dir = argv[++i];
48
+ else if (arg.startsWith("--dir=") && arg.length > "--dir=".length) options.dir = arg.slice("--dir=".length);
49
+ else if (arg === "--dir" || arg === "--dir=") return { error: `oats: \`oats tui --dir\` takes a path (E_BAD_ARGS); usage: ${USAGE}` };
50
+ else return refused(arg);
32
51
  }
33
52
  return { options };
34
53
  }
35
54
 
36
- export const initialState = ({ ascii = false, actions = ACTIONS } = {}) => Object.freeze({ view: "frame", ascii, actions });
37
-
38
- /** (state, event) -> { state, effect }. Pure. An event is `{ key: <key id> }` or `{ paste }`;
39
- * an effect is something only the loop can do: "quit", "suspend", "redraw", or null.
40
- * A paste is dropped whole: nothing in it is a key. */
41
- export function reduce(state, event, keymap = bindings(state.actions)) {
42
- const stay = { state, effect: null };
43
- if (typeof event.key !== "string") return stay;
44
- switch (keymap.get(event.key)) {
45
- case "help": return { state: Object.freeze({ ...state, view: state.view === "help" ? "frame" : "help" }), effect: null };
46
- case "close": return state.view === "help" ? { state: Object.freeze({ ...state, view: "frame" }), effect: null } : stay;
47
- case "quit": return { state, effect: "quit" };
48
- case "suspend": return { state, effect: "suspend" };
49
- case "redraw": return { state, effect: "redraw" };
50
- default: return stay;
51
- }
52
- }
53
-
54
55
  /** An error as lines fit for a terminal: its stack, each line through the display filter. */
55
56
  function errorLines(error) {
56
57
  const text = error instanceof Error ? error.stack || error.message : String(error);
57
58
  return String(text).split("\n", 12).map((line) => displayLine(line)).filter(Boolean);
58
59
  }
59
60
 
60
- /** Run. Resolves with the exit status; never calls process.exit, so what was written drains. */
61
- export async function main({ argv, stdin, stdout, stderr, env, proc = process, now = Date.now, setTimer = setTimeout, clearTimer = clearTimeout }) {
61
+ /** What the loop does outside the terminal, each replaceable by a test. */
62
+ const EFFECTS = Object.freeze({ loadConfig, findDeployment, probeKernel, createReader, offeredDeployments, admitDeployment });
63
+
64
+ /** Run. Resolves with the exit status; never calls process.exit, so what was written drains.
65
+ * Before the alternate screen, in this order, each failure one line on stderr and status 1:
66
+ * the arguments; the instance variables removed from the environment (a TUI started in an
67
+ * agent's pane must read the deployment it was asked about, and so must every child it starts);
68
+ * the terminal; the user's tui.json; the deployment; the kernel it shipped with. */
69
+ export async function main({ argv, stdin, stdout, stderr, env, proc = process, now = Date.now, setTimer = setTimeout, clearTimer = clearTimeout, cwd = () => process.cwd(), home = homedir(), effects = EFFECTS }) {
62
70
  const { options, error } = parseArgs(argv);
63
71
  if (error) { stderr.write(`${error}\n`); return 1; }
64
72
  if (options.help) { stdout.write(HELP); return 0; }
73
+ leaveInstance(env);
65
74
  if (!isTerminal({ stdin, stdout, env })) { stderr.write(`${NO_TERMINAL}\n`); return 1; }
75
+ const config = effects.loadConfig({ env, home });
76
+ if (!config.ok) { stderr.write(config.lines.map((line) => `${line}\n`).join("")); return 1; }
77
+ const found = effects.findDeployment(resolve(cwd(), options.dir ?? "."));
78
+ // Outside every deployment, and with none named: the switcher, when ~/Agents holds a deployment
79
+ // to offer. A `--dir` that is in no deployment is refused as it is: what was asked for is not there.
80
+ const offered = found.ok || options.dir !== null ? null : effects.offeredDeployments(home, []);
81
+ if (!found.ok && !offered?.offered.length) { stderr.write(`${noDeployment(found.dir)}\n`); return 1; }
82
+ // The kernel is asked once: an upgrade under a running TUI is met by starting it again.
83
+ const probe = await effects.probeKernel({ env });
84
+ if (!probe.ok) { stderr.write(`${noKernel(probe.reason)}\n`); return 1; }
66
85
 
67
- const look = glyphs(env, { ascii: options.ascii });
86
+ const clock = () => new Date(now()).toISOString();
87
+ const look = glyphs(env, { ascii: options.ascii || config.ascii });
68
88
  const screen = createScreen({ ...look, color: colorEnabled(env) });
69
89
  const parser = createKeyParser({ now });
70
- let state = initialState({ ascii: look.ascii });
90
+ 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 });
71
91
  const keymap = bindings(state.actions);
72
- let full = true, escTimer = null;
92
+ if (offered) state = reduce(state, { offered }, keymap).state;
93
+ // What the last frame drew, for the store: how tall the list pane is and how far the other
94
+ // pane scrolls. The store holds no size of its own.
95
+ let drawn = { page: 1, extent: 0, room: 1, cols: 1 };
96
+ let full = true, escTimer = null, ended = false;
73
97
 
98
+ // What the reader reads for, it asks of the state at that moment: the served deployments, the
99
+ // entry a failed read keeps, and the roster and the memory the next outcome is made from.
100
+ const reader = effects.createReader({
101
+ cli: probe.cli, env, clock, now,
102
+ getServed: () => state.ctxs,
103
+ getEntry: (id) => state.entries.get(id) ?? null,
104
+ getRoster: () => ({ remote: state.remote, memory: state.memory, notes: state.notes }),
105
+ onEntry: heard, onRoster: heard,
106
+ });
107
+ /** What the reader gave, into the state, and the screen after it. */
108
+ function heard(event) { if (!ended) guard.attempt(() => { if (!took(reduce(state, event, keymap))) guard.draw(); }); }
109
+ /** One step of the reducer taken: the state, then what only the loop can do. True once the
110
+ * TUI is leaving. Listing ~/Agents and asking whether a picked folder is a deployment read the
111
+ * file system (lib/read.mjs); what they find is an event of its own. */
112
+ function took(step) {
113
+ state = step.state;
114
+ const effect = step.effect;
115
+ if (effect === "quit") { guard.finish(0); return true; }
116
+ if (effect === "suspend") guard.suspend();
117
+ if (effect === "redraw") guard.reassert(); // the modes again, then the whole screen
118
+ if (effect === null || typeof effect !== "object") return false;
119
+ if (effect.offer) took(reduce(state, { offered: effects.offeredDeployments(home, state.ctxs) }, keymap));
120
+ if (effect.admit !== undefined) {
121
+ const admitted = effects.admitDeployment(effect.admit);
122
+ took(reduce(state, admitted.ok ? { admitted: admitted.deployment, at: clock() } : { refused: effect.admit }, keymap));
123
+ }
124
+ if (effect.refresh) refresh(effect.refresh);
125
+ return false;
126
+ }
74
127
  const guard = createGuard({
75
128
  stdin, stdout, proc, setTimer, clearTimer,
76
- frame() { const bytes = screen.render(frame(state, guard.size()), guard.size(), { full }); full = false; return bytes; },
77
- onInput(bytes) { act(parser.feed(bytes)); watchEscape(); },
129
+ frame() {
130
+ const size = guard.size(), at = clock();
131
+ // The layout first: the model's window is as tall, and its sentences as wide, as the list
132
+ // pane it gives. The switcher takes the whole body and has no notice of a deployment.
133
+ const r = (state.view === "help" ? state.back : state.view) === "switcher" ? { notice: null, note: null, observed: true } : roster(state, at);
134
+ const g = layout(r.notice, size, { observed: r.observed, note: r.note, ascii: state.ascii });
135
+ const made = frame(model(state, { page: g.page, now: now(), at, cols: g.listCols }), size);
136
+ drawn = { page: made.page, extent: made.extent, room: made.room, cols: g.listCols };
137
+ const bytes = screen.render(made.rows, size, { full });
138
+ full = false;
139
+ return bytes;
140
+ },
141
+ onInput(bytes) { reader.touch(); act(parser.feed(bytes)); watchEscape(); },
78
142
  onResize() { full = true; guard.draw(); },
79
143
  onRedraw() { full = true; guard.draw(); },
144
+ // A cycle in flight when the process stops is no evidence about the deployment (lib/read.mjs):
145
+ // it is dropped before the stop, and again after a stop nobody here asked for; the return
146
+ // reads at once.
147
+ onStop() { dropReads(); },
148
+ onResume(asked) { if (!asked) dropReads(); refresh({ live: true }); },
149
+ onEnd() { ended = true; reader.stop(); },
80
150
  });
151
+ function refresh(how) { Promise.resolve(reader.request(how)).catch(() => {}); }
152
+ /** Every read in flight is void (lib/read.mjs), the roster's with them: the reader says nothing
153
+ * for a void read, so the state is told here that none is in flight. */
154
+ function dropReads() { reader.voidInFlight(); state = reduce(state, { collecting: false }, keymap).state; }
81
155
  function act(events) {
82
156
  for (const event of events) {
83
- const next = reduce(state, "paste" in event ? { paste: true } : { key: keyId(event) }, keymap);
84
- state = next.state;
85
- if (next.effect === "quit") return guard.finish(0);
86
- if (next.effect === "suspend") guard.suspend();
87
- if (next.effect === "redraw") guard.reassert(); // the modes again, then the whole screen
157
+ if (took(reduce(state, "paste" in event ? { paste: event.paste } : { key: keyId(event), ...(typeof event.text === "string" && !event.alt ? { text: event.text } : {}), ...drawn }, keymap))) return;
88
158
  }
89
159
  guard.draw();
90
160
  }
@@ -96,6 +166,7 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
96
166
  }
97
167
 
98
168
  guard.start();
169
+ guard.attempt(() => { if (!ended) Promise.resolve(reader.start()).catch(() => {}); });
99
170
  guard.attempt(() => guard.draw());
100
171
  const end = await guard.done;
101
172
  if (escTimer !== null) clearTimer(escTimer);