@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
@@ -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);
@@ -0,0 +1,392 @@
1
+ // From the store's state to what is drawn: the roster in its order, the rows of the pane and the
2
+ // facts of the selected instance. Pure, and without a cell position: the views place it.
3
+ //
4
+ // Everything that groups, orders, hides or names an instance is asked of the shared home
5
+ // (client.mjs), the same functions the Desktop draws from: this module calls them and flattens
6
+ // their answers, and holds no rule of its own about which group a row is in or what state it is
7
+ // in. What it adds is the TUI's: the window, the clock times, and which fact stands on which line.
8
+ import {
9
+ TERMS, panelData, displayLine, DETAIL_WITHHELD, originLead, instanceId, instanceVisibleInTree, waitingRollup, collapseKey, filterInstanceTree,
10
+ hasInstanceChildren, heldHome, rosterSections, deploymentState, rowStale, primaryDeployment, isMultiDeployment, runtimeState, runtimeCounts,
11
+ waitingClaim, waitingLabel, waitedText, waitingClock, waitingBelowText, instanceActs,
12
+ identityMemory, viewModel, workspaceChoices, workspaceChoiceRows, choiceMatches, UNMATCHED_SECTION, shortPath,
13
+ } from "./client.mjs";
14
+ import { shownLines } from "./term/text.mjs";
15
+ import { textWidth } from "./term/width.mjs";
16
+ import { windowOf } from "./views/scroll.mjs";
17
+
18
+ /** The widest the state column of the list may be, in cells. */
19
+ export const WORD_MAX = 20;
20
+ /** The most rows one sentence takes inside the list (a deployment's note, a reason). */
21
+ const SENTENCE_ROWS = 4;
22
+ /** The cells a sentence inside the list is set in from the pane's left edge. */
23
+ export const SENTENCE_INDENT = 3;
24
+ /** The width the list is flattened for when nobody says: only the rows that can be selected are
25
+ * read from such an answer, and they are the same at every width. */
26
+ const ANY_WIDTH = 80;
27
+
28
+ /** What the shared home reads of a client (panel-views.mjs `held`), built here and nowhere else.
29
+ * `snapshot.byWs` holds this machine's entries only: a machine's panel is made by the shared
30
+ * home itself from `remoteGroups`, stamped with `at`. So `at` is the time of the last roster
31
+ * outcome the store took (`rosterAt`): a machine's rows are what it reported then. Before any
32
+ * outcome there is no machine to stamp, and the time of the call stands in. */
33
+ export function heldOf(state, at) {
34
+ return {
35
+ ctxs: state.ctxs, snapshot: { byWs: state.entries }, remoteGroups: state.remote.remoteGroups,
36
+ remembered: identityMemory({ memory: state.memory, notes: state.notes }),
37
+ rosterAnswered: state.remote.rosterAnswered, rosterFailure: state.remote.rosterFailure, cli: state.cli,
38
+ observing: new Set(), remoteCollecting: state.collecting, home: state.home, at: state.rosterAt ?? at,
39
+ };
40
+ }
41
+
42
+ /** The panel of the view that holds `state.open`: the composition the Desktop's own panel is
43
+ * served from (panel-views.mjs `panelData`), so nothing of it is put together by hand here.
44
+ * Null while nothing is open (a run started outside a deployment, before a pick). */
45
+ export function panelOf(state, at) {
46
+ return state.open === null ? null : panelData(heldOf(state, at), state.open, TERMS);
47
+ }
48
+
49
+ const text = (value) => typeof value === "string" && value !== "";
50
+ const pad = (n) => String(n).padStart(2, "0");
51
+ /** An ISO time as a local clock time, `14:03:27`, or null. */
52
+ export function clockTime(iso) {
53
+ const at = new Date(iso);
54
+ return text(iso) && Number.isFinite(at.getTime()) ? `${pad(at.getHours())}:${pad(at.getMinutes())}:${pad(at.getSeconds())}` : null;
55
+ }
56
+
57
+ /** A row's state in a word: the one the kernel or the collector reported on the row, else the
58
+ * shared word for what is known of it (running, stopped, unknown). A row kept from a machine
59
+ * that was not reached (the shared home marks it) still carries the word of its last report,
60
+ * which is not its state now: it gets the shared word, so nothing reads as stopped, or as
61
+ * running, that is only not reached. */
62
+ const stateWord = (row) => (text(row.runtimeState) && row.serverUnreached !== true ? row.runtimeState : runtimeState(row));
63
+ /** What a list row shows at its right edge: a held home's state, the harness of a running
64
+ * instance, else its state. */
65
+ function wordOf(row) {
66
+ const held = heldHome(row);
67
+ if (held) return held.state;
68
+ return row.running === true && text(row.harness) ? row.harness : stateWord(row);
69
+ }
70
+ /** Which mark a row carries: the shared word, `held` for a home the kernel holds, and `shell`
71
+ * for a stopped instance whose terminal still has a shell in it. */
72
+ function markOf(row) {
73
+ if (heldHome(row)) return "held";
74
+ const word = runtimeState(row);
75
+ return word === "stopped" && row.runtimeState === "shell" ? "shell" : word;
76
+ }
77
+
78
+ /** The group of instances that are related to no other, as the shared grouping names it. */
79
+ const SINGLES = "independent";
80
+
81
+ /** Everything of a state that does not depend on a width: the panel, the rows as the shared
82
+ * grouping orders them, the headings, and what stands after the sections. */
83
+ function build(state, at) {
84
+ const panel = panelOf(state, at);
85
+ // No view holds what was open (a machine that is no longer listed): the store shows the
86
+ // switcher for it; nothing is drawn from this answer.
87
+ const gone = panel !== null && !panel.workspace;
88
+ const instances = panel?.instances ?? [], deployments = panel?.deployments ?? [];
89
+ const multi = isMultiDeployment(deployments);
90
+ const query = state.filter.query, filtering = query.trim() !== "";
91
+ // The section (deployment) each row is drawn in, read from the shared split itself: the
92
+ // sections of all rows. A collapse hides, and rolls up, only rows of its own section, as in the
93
+ // Desktop: a parent's name can resolve to a row of another deployment of the view.
94
+ const sectionOf = new Map();
95
+ for (const part of rosterSections(instances, instances, deployments, TERMS)) for (const group of part.groups) for (const cluster of group.clusters) for (const row of cluster.instances) sectionOf.set(instanceId(row), part.deployment?.id ?? null);
96
+ const section = (row) => sectionOf.get(instanceId(row)) ?? null;
97
+ const matched = filterInstanceTree(instances, query);
98
+ const visible = matched.filter((i) => instanceVisibleInTree(i, instances, state.collapsed, state.open, filtering, { section }));
99
+ const sections = rosterSections(instances, visible, deployments, TERMS);
100
+ const stale = (row) => rowStale(row, deployments);
101
+
102
+ // The list, top to bottom, before any width. A section that has a label (a view of two or more
103
+ // deployments) starts with its heading and the deployment's note; then the groups in the order
104
+ // given, every cluster's members in order, with one gap before the group of single instances
105
+ // when rows of the section came before it.
106
+ const parts = [], rows = [];
107
+ const heading = (deployment, label, path = null) => {
108
+ const said = deploymentState(deployment), live = said.key === "live";
109
+ return {
110
+ kind: "heading", label, path, state: live ? null : said.text, short: live || !text(deployment.short) ? null : deployment.short,
111
+ // A machine's rows are what it reported at the last roster read.
112
+ readAt: live && deployment.local === false ? clockTime(state.rosterAt) : null,
113
+ };
114
+ };
115
+ for (const part of sections) {
116
+ if (text(part.label)) {
117
+ parts.push(heading(part.deployment, part.label));
118
+ if (text(part.deployment.note)) parts.push({ kind: "sentence", value: part.deployment.note });
119
+ }
120
+ let drawn = 0;
121
+ for (const group of part.groups) {
122
+ if (group.key === SINGLES && drawn) parts.push({ kind: "gap" });
123
+ for (const cluster of group.clusters) for (const row of cluster.instances) {
124
+ const item = { kind: "row", row, id: instanceId(row), depth: Number.isInteger(row.depth) ? row.depth : 0 };
125
+ parts.push(item); rows.push(item); drawn++;
126
+ }
127
+ }
128
+ }
129
+ // A deployment of the view that is not live and has no row is in no section: it is named
130
+ // after them, with its state, and its reason on rows of its own.
131
+ if (multi) for (const deployment of deployments) {
132
+ const said = deploymentState(deployment);
133
+ if (said.key === "live" || sections.some((part) => part.deployment?.id === deployment.id)) continue;
134
+ parts.push(heading(deployment, deployment.machine, deployment.label));
135
+ if (text(said.detail)) parts.push({ kind: "sentence", value: said.detail });
136
+ if (text(deployment.note)) parts.push({ kind: "sentence", value: deployment.note });
137
+ }
138
+ // The roster read failed and no answer has arrived yet: there is no machine to say it.
139
+ // It is about no row above it: an empty row sets it apart when something stands there.
140
+ if (state.remote.rosterFailure !== null) parts.push(...(parts.length ? [{ kind: "gap" }] : []), { kind: "own", words: ROSTER_FAILED }, { kind: "sentence", value: state.remote.rosterFailure });
141
+
142
+ const primary = primaryDeployment(deployments), said = deploymentState(primary);
143
+ // The entry of this machine's deployment, when the view's primary is one: only it is ever
144
+ // pending, withholds homes, or holds nothing after a failed read. A machine's panel has none.
145
+ const status = panel?.deployment?.status ?? null;
146
+ const local = panel !== null && !!panel.deployment;
147
+ const live = primary !== null && said.key === "live";
148
+ const counted = runtimeCounts(instances);
149
+ const waiting = instances.filter((row) => waitingClaim(row, { stale: stale(row) })).length;
150
+ const withheld = Array.isArray(panel?.deployment?.withheld) ? panel.deployment.withheld.length : 0;
151
+ // The machines of the view other than this one, each once, and whether a deployment of this
152
+ // machine is in it: both read from the shared entries (`local`), never decided here.
153
+ const away = [...new Set(deployments.filter((d) => d.local === false && text(d.machine)).map((d) => d.machine))];
154
+ const machines = away.length, here = deployments.some((d) => d.local === true);
155
+ // Whether a list stands under the header: not for a deployment of this machine that was never
156
+ // observed, nor for a machine that is not live and has no row kept. Each has only its reason.
157
+ const observed = panel !== null && !gone && (local ? status === "observed" : live || instances.length > 0);
158
+ return {
159
+ panel, gone, instances, deployments, multi, parts, rows, filtering, stale, section, live, observed,
160
+ below: waitingRollup(instances, state.collapsed, state.open, { filtering, stale, section }),
161
+ status,
162
+ workspace: text(panel?.workspace?.name) ? panel.workspace.name : "",
163
+ machines, here,
164
+ // The one machine of a view that holds no deployment of this machine: nothing else names it,
165
+ // since a view of one deployment has no heading.
166
+ machine: !here && away.length === 1 ? away[0] : null,
167
+ // The counts in the order they are drawn. `shared`: the word is the shared home's.
168
+ counts: [
169
+ ...Object.entries(counted).slice(0, 1).map(([word, n]) => ({ n, word, shared: true })),
170
+ { n: waiting, word: waiting === 1 ? "needs input" : "need input", shared: false },
171
+ ...Object.entries(counted).slice(1).map(([word, n]) => ({ n, word, shared: true })),
172
+ { n: withheld, word: "withheld", shared: false },
173
+ ].filter((count) => count.n > 0),
174
+ // The time of the read the screen shows: the cycle's own (`generatedAt`), never
175
+ // `observedAt`, which is when the kernel last looked at the workspace's remotes and is up
176
+ // to a minute older on a read in the background. Nothing drawn here comes from the remotes.
177
+ // In a view whose primary is a machine it is the time of the last roster read (heldOf).
178
+ readAt: live ? clockTime(panel.generatedAt) : null,
179
+ // A deployment that is not live says so above the list, with why. Before the first answer
180
+ // the list holds the TUI's own line instead: the shared sentence for that moment names an
181
+ // installed CLI, and the TUI runs its own kernel.
182
+ // `since`: an entry kept over a failed read carries the time of its last good read. An
183
+ // unavailable entry carries only the time of the cycle that failed, which is no "since".
184
+ notice: panel === null || gone || primary === null || live || status === "pending" ? null
185
+ : { text: said.text, since: status === "observed" ? clockTime(panel.generatedAt) : null, reason: said.detail },
186
+ // The note of the one deployment of a view that has no headings: above the list.
187
+ note: !multi && text(primary?.note) ? primary.note : null,
188
+ // Why no instance is listed. "none" is a statement about the deployment, so it is made only
189
+ // of one that was read: a machine that is not live and has no row kept is not known to have
190
+ // none (it is not `observed`), and its notice is all there is to say.
191
+ empty: status === "pending" ? "reading" : !observed ? null : !instances.length ? "none" : !rows.length ? "nomatch" : null,
192
+ // As wide as the widest word among all the rows of the list, so the column does not move
193
+ // while the list scrolls.
194
+ wordWidth: Math.min(WORD_MAX, rows.reduce((widest, { row }) => Math.max(widest, textWidth(displayLine(wordOf(row)) ?? "")), 0)),
195
+ };
196
+ }
197
+
198
+ /** The TUI's own line for a roster read that failed before any answer arrived. */
199
+ export const ROSTER_FAILED = "Other machines were not read.";
200
+
201
+ /** The list as rows of the screen for a pane `cols` wide: every part on one row, a sentence on
202
+ * as many as it needs. An item is null (an empty row), an instance (`{ row, id, depth }`, the
203
+ * only kind that can be selected), `{ heading }`, `{ line }` (one row of a sentence, safe text),
204
+ * `{ own }` (the TUI's words) or `{ empty }` (why no instance is listed). `index`: an
205
+ * instance's id to its place. */
206
+ function flatten(base, cols, ascii) {
207
+ const items = [];
208
+ const room = Math.max(1, cols - SENTENCE_INDENT - 1);
209
+ // The line that says why no instance is listed, set apart from what follows it by an empty row.
210
+ if (base.empty) items.push({ empty: base.empty }, ...(base.parts.length ? [null] : []));
211
+ for (const part of base.parts) {
212
+ if (part.kind === "gap") items.push(null);
213
+ else if (part.kind === "row") items.push(part);
214
+ else if (part.kind === "heading") items.push({ heading: part });
215
+ else if (part.kind === "own") items.push({ own: part.words });
216
+ else for (const line of shownLines(part.value, room, SENTENCE_ROWS, { ascii })) items.push({ line });
217
+ }
218
+ return { items, index: new Map(items.flatMap((item, i) => (item?.id !== undefined ? [[item.id, i]] : []))) };
219
+ }
220
+
221
+ /** One answer is kept: a repaint, a resize and a key that changes nothing the roster is made
222
+ * from read it again without asking the shared home again (its grouping walks the whole roster
223
+ * for each row). The state's values are never changed in place, so their identity says whether
224
+ * they changed. The flattening for the last width asked is kept beside it. */
225
+ const MADE_FROM = ["entries", "remote", "memory", "notes", "rosterAt", "collecting", "ctxs", "open", "collapsed", "cli", "home"];
226
+ let kept = null;
227
+ /** The roster of a state: the rows in drawn order and what the header says, for a list pane
228
+ * `cols` wide. Only `items` and `index` depend on the width; `rows`, the instances in drawn
229
+ * order, do not. `at` stamps a machine's panel before any roster outcome was taken, which
230
+ * never shows; it is passed on. */
231
+ export function roster(state, at = new Date(0).toISOString(), cols = ANY_WIDTH) {
232
+ const same = kept && MADE_FROM.every((name) => kept.state[name] === state[name]) && kept.state.filter.query === state.filter.query;
233
+ if (!same) kept = { state, base: build(state, at), flat: null };
234
+ if (!kept.flat || kept.flat.cols !== cols || kept.flat.ascii !== state.ascii) kept.flat = { cols, ascii: state.ascii, ...flatten(kept.base, cols, state.ascii) };
235
+ return { ...kept.base, items: kept.flat.items, index: kept.flat.index };
236
+ }
237
+
238
+ /** Whether a row has instances below it, and whether they are folded away. A filter shows every
239
+ * match whatever is collapsed, and leaves the collapse set as it is. */
240
+ export function disclosure(state, r, item) {
241
+ if (!hasInstanceChildren(r.instances, item.row)) return null;
242
+ return !r.filtering && state.collapsed.has(collapseKey(state.open, item.id)) ? "closed" : "open";
243
+ }
244
+
245
+ function listRow(state, r, item) {
246
+ const fold = disclosure(state, r, item);
247
+ return {
248
+ id: item.id, name: item.row.instance, depth: item.depth, selected: item.id === state.selected,
249
+ disclosure: fold, mark: markOf(item.row), word: wordOf(item.row),
250
+ waiting: waitingClaim(item.row, { stale: r.stale(item.row) }) !== null,
251
+ below: fold === "closed" ? r.below.get(item.id)?.length ?? 0 : 0,
252
+ };
253
+ }
254
+
255
+ /** The facts of one instance, a label and a value per line; a fact that is absent is left out.
256
+ * `form`: `line` (one row), `wrap` (a sentence, on as many rows as it needs), `end` (read from
257
+ * its end: a path). A fact with no label continues the one above it. Every value is text the
258
+ * TUI did not write, or holds some: the view draws all of them through shown(). `now` is the
259
+ * time of the paint, so the waited time is right whenever the screen is drawn. */
260
+ function detailOf(state, r, item, now) {
261
+ const row = item.row, facts = [];
262
+ const add = (label, value, form = "line") => { if (text(value)) facts.push({ label, value, form }); };
263
+ add("soul", row.agent);
264
+ if (r.multi) {
265
+ // Which machine the instance is on, and, when that deployment is not live, the whole
266
+ // sentence that says why: a heading has room for the short reason only.
267
+ add("machine", row.deployment?.machine);
268
+ const of = r.deployments.find((d) => d.id === row.deployment?.id);
269
+ const said = of ? deploymentState(of) : null;
270
+ if (said && said.key !== "live") add("", said.detail, "wrap");
271
+ }
272
+ add("state", heldHome(row)?.state ?? stateWord(row)); // the word of its list row, harness apart
273
+ const acts = instanceActs(row), held = acts.blocked ?? acts.limited;
274
+ // The row's own text stands under its state, in the form that says who made it. Who made it is
275
+ // the shared home's to say, in two ways, and the TUI writes no word and no sentence of its own
276
+ // for either: the row's mark, which originLead turns into the words that go before the text;
277
+ // or a reason of the row that carries no `origin`, which is a sentence the shared home wrote
278
+ // itself, when that sentence is this very text (compared as given). A text with neither is
279
+ // vouched for by nobody: it stands in quotation marks and names no one. A missing mark is
280
+ // never read as "the shared home wrote this".
281
+ // The filter is asked about the text alone, before anything is put around it, so the words in
282
+ // front are never why a text is shown. What it withholds goes to the view as it came, which
283
+ // draws the withheld word and nothing else. (The view asks again about the whole value: words
284
+ // in front never change the answer; a closing quotation mark can, for a text that ends in a
285
+ // secret's name and its sign, and that text is then withheld.)
286
+ const line = displayLine(row.runtimeError);
287
+ if (line === DETAIL_WITHHELD) add("", row.runtimeError, "wrap");
288
+ else if (line !== null) {
289
+ const lead = originLead(row.runtimeErrorOrigin, TERMS);
290
+ const vouched = [acts.blocked, acts.limited, ...acts.acts.map((act) => act.reason)].some((reason) => reason && reason.origin === undefined && reason.sentence === row.runtimeError);
291
+ add("", lead !== null ? `${lead} ${line}` : vouched ? line : `"${line}"`, "wrap");
292
+ }
293
+ // What holds the row, when that is a sentence of the shared home's and not the row's text: a
294
+ // reason with an `origin` is the row's text, and so is one whose sentence is that text. Either
295
+ // stands once, under the state.
296
+ if (held && held.origin === undefined && held.sentence !== row.runtimeError) add("held", held.sentence, "wrap");
297
+ const claim = waitingClaim(row, { stale: r.stale(row) });
298
+ if (claim) {
299
+ add("needs", `${waitingLabel(claim)}, ${waitedText(claim.since, now)}`);
300
+ if (text(claim.message)) add("", `the agent: "${claim.message.trim()}"`, "wrap");
301
+ }
302
+ const under = disclosure(state, r, item) === "closed" ? r.below.get(item.id) : null;
303
+ if (under?.length) add("below", waitingBelowText(under), "wrap");
304
+ add("harness", `${[row.harness, row.model].filter(text).join(", ")}${text(row.model) && text(row.modelFrom) ? ` (${row.modelFrom})` : ""}`);
305
+ add("work", [row.work, row.branch].filter(text).join(", "));
306
+ add("team", row.team);
307
+ add("parent", [row.parentInstance, text(row.siblingInstance) ? `sibling of ${row.siblingInstance}` : null].filter(text).join(", "));
308
+ if (text(row.startedAt)) add("started", waitingClock(row.startedAt, now));
309
+ add("home", row.home, "end");
310
+ return { title: row.instance, facts };
311
+ }
312
+
313
+ /** The heading of the deployments in `~/Agents` that are not served yet: the TUI's own. */
314
+ export const OFFERED_SECTION = "On this machine, not opened";
315
+ export const MORE_FOLDERS = "More folders than are listed here.";
316
+
317
+ /** The switcher's rows for a state, top to bottom: the workspaces this run can show, as the
318
+ * shared home lists and words them; then the ones matched to no workspace under the shared
319
+ * heading; then the deployments of `~/Agents` that are not served, under the TUI's own.
320
+ * An item is `{ heading, shared }`, `{ own }`, or a choice: `{ key, label, place, notLiveText,
321
+ * open, primary }` for a view (`primary` is the deployment Enter opens) and `{ key, label, place,
322
+ * path, refused }` for an offered folder. `keys` are the choices in order; `selected` is the
323
+ * key the selection stands on (the first choice when the state's own is not listed). */
324
+ export function switcher(state, at = new Date(0).toISOString()) {
325
+ const held = heldOf(state, at), views = viewModel(held, TERMS);
326
+ const rows = workspaceChoiceRows(workspaceChoices(held, TERMS, views));
327
+ const query = state.switcher.query;
328
+ const openView = state.open === null ? null : views.views.find((v) => v.id === state.open || v.deployments.includes(state.open))?.id ?? null;
329
+ const choice = (row) => ({
330
+ key: `view\u0000${row.id}`, label: row.label, place: row.place, notLiveText: row.notLiveText, open: row.id === openView,
331
+ primary: views.views.find((v) => v.id === row.id)?.primary ?? null,
332
+ });
333
+ const shown = rows.filter((row) => choiceMatches(row, query));
334
+ const matched = shown.filter((row) => !row.unattached).map(choice), unmatched = shown.filter((row) => row.unattached).map(choice);
335
+ const offered = state.offered.offered
336
+ .map(({ path, name }) => ({ key: `path\u0000${path}`, label: name, place: shortPath(path, { home: state.home }), path, refused: state.switcher.refused === path }))
337
+ .filter((item) => choiceMatches(item, query));
338
+ const items = [
339
+ ...matched,
340
+ ...(unmatched.length ? [{ heading: UNMATCHED_SECTION, shared: true }, ...unmatched] : []),
341
+ ...(offered.length ? [{ heading: OFFERED_SECTION, shared: false }, ...offered] : []),
342
+ ...(state.offered.limited ? [{ own: MORE_FOLDERS }] : []),
343
+ ];
344
+ const keys = items.filter((item) => item.key !== undefined).map((item) => item.key);
345
+ const total = rows.length + state.offered.offered.length;
346
+ return {
347
+ items, keys, selected: keys.includes(state.switcher.selected) ? state.switcher.selected : keys[0] ?? null,
348
+ empty: keys.length ? null : total ? "nomatch" : "none",
349
+ };
350
+ }
351
+
352
+ /** What the views draw for a state. For the Instances view, in a list pane `page` rows tall and
353
+ * `cols` wide: the header's facts, the rows of the window with their marks, and the selected
354
+ * instance's detail. For the switcher, in a pane `page` rows tall: the window of its rows. Only
355
+ * the rows in the pane are worked out. */
356
+ export function model(state, { page, now, at, cols }) {
357
+ const r = roster(state, at, cols);
358
+ const common = {
359
+ view: state.view, focus: state.focus, ascii: state.ascii, actions: state.actions, filter: state.filter,
360
+ 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,
361
+ detailTop: state.detailTop, helpTop: state.helpTop, open: state.open !== null,
362
+ };
363
+ // The view under the help decides what the header says.
364
+ const under = state.view === "help" ? state.back : state.view;
365
+ if (under === "switcher") {
366
+ const s = switcher(state, at);
367
+ const at_ = s.selected === null ? -1 : s.items.findIndex((item) => item.key === s.selected);
368
+ // The line that says what happened to the open workspace stands above the rows and takes one
369
+ // of the pane's: the window is that much shorter, so no choice is hidden for it.
370
+ const win = windowOf({ top: state.switcher.top, count: s.items.length, height: Math.max(1, page - (state.switcher.line ? 1 : 0)), keep: state.switcher.loose ? -1 : at_ });
371
+ return {
372
+ ...common, under, list: [], above: 0, below: 0, wordWidth: 0, detail: null,
373
+ // Nothing of a workspace stands in the header while the switcher is shown.
374
+ workspace: "", machines: 0, here: false, machine: null, counts: [], readAt: null, notice: null, note: null, empty: null, observed: true,
375
+ filter: Object.freeze({ editing: state.switcher.editing, query: state.switcher.query }),
376
+ switcher: {
377
+ rows: s.items.slice(win.top, win.top + win.size).map((item) => (item.key === undefined ? item : { ...item, selected: item.key === s.selected })),
378
+ above: win.above, below: win.below, empty: s.empty, said: state.switcher.line,
379
+ },
380
+ };
381
+ }
382
+ const selected = state.selected === null ? -1 : r.index.get(state.selected) ?? -1;
383
+ // The window holds the selection, unless the list was scrolled away from it on purpose.
384
+ const win = windowOf({ top: state.top, count: r.items.length, height: page, keep: state.loose ? -1 : selected });
385
+ return {
386
+ ...common, under,
387
+ list: r.items.slice(win.top, win.top + win.size).map((item) => (item?.id !== undefined ? { kind: "row", ...listRow(state, r, item) } : item)),
388
+ above: win.above, below: win.below, wordWidth: r.wordWidth,
389
+ detail: selected >= 0 ? detailOf(state, r, r.items[selected], now) : null,
390
+ switcher: null,
391
+ };
392
+ }