@awebai/oats 0.57.1 → 0.59.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 (61) hide show
  1. package/bin/oats.mjs +24 -11
  2. package/docs/configuration.md +2 -1
  3. package/docs/desktop-cli-api.md +105 -17
  4. package/docs/desktop.md +30 -3
  5. package/docs/execution-targets.md +15 -0
  6. package/docs/implementation.md +2 -0
  7. package/docs/integrations.md +2 -2
  8. package/docs/knowledge.md +4 -4
  9. package/docs/official-catalog.md +4 -4
  10. package/docs/packages.md +14 -14
  11. package/docs/release-notes/v0.58.0.md +107 -0
  12. package/docs/release-notes/v0.59.0.md +288 -0
  13. package/docs/servers.md +4 -1
  14. package/docs/souls-and-instances.md +30 -0
  15. package/docs/tui.md +653 -117
  16. package/docs/workspaces.md +2 -2
  17. package/lib/core.mjs +227 -46
  18. package/lib/read-ahead-worker.mjs +119 -0
  19. package/lib/read-ahead.mjs +115 -0
  20. package/lib/retire-state.mjs +33 -0
  21. package/lib/servers.mjs +9 -1
  22. package/lib/session-input.mjs +14 -4
  23. package/package-catalog.json +3 -3
  24. package/package.json +1 -1
  25. package/packages/client/cli-locator.mjs +2 -2
  26. package/packages/client/deployment-data.mjs +4 -0
  27. package/packages/client/deployment-panel.mjs +3 -0
  28. package/packages/client/instance-acts.mjs +23 -8
  29. package/packages/client/instance-presentation.mjs +3 -2
  30. package/packages/client/instance-tree.mjs +84 -39
  31. package/packages/client/lifecycle-confirmation.mjs +9 -3
  32. package/packages/client/panel-views.mjs +1 -1
  33. package/packages/client/remote-roster.mjs +4 -1
  34. package/packages/client/retire-in-flight.mjs +65 -0
  35. package/packages/client/retire-state.mjs +30 -0
  36. package/packages/client/spawn-apply-cli.mjs +8 -2
  37. package/packages/client/spawn-apply.mjs +20 -7
  38. package/packages/client/spawn-preview-cli.mjs +2 -1
  39. package/packages/client/spawn-preview.mjs +30 -18
  40. package/packages/record/lib/directory-identity.mjs +14 -0
  41. package/packages/record/lib/native-history.mjs +6 -5
  42. package/packages/tui/README.md +23 -10
  43. package/packages/tui/lib/actions.mjs +63 -5
  44. package/packages/tui/lib/client.mjs +12 -1
  45. package/packages/tui/lib/config.mjs +7 -2
  46. package/packages/tui/lib/main.mjs +315 -82
  47. package/packages/tui/lib/model.mjs +523 -56
  48. package/packages/tui/lib/panel.mjs +519 -144
  49. package/packages/tui/lib/read.mjs +52 -26
  50. package/packages/tui/lib/store.mjs +908 -65
  51. package/packages/tui/lib/term/keys.mjs +9 -2
  52. package/packages/tui/lib/term/text.mjs +4 -0
  53. package/packages/tui/lib/term/through.mjs +12 -1
  54. package/packages/tui/lib/views/frame.mjs +394 -95
  55. package/packages/tui/lib/views/help.mjs +54 -13
  56. package/packages/tui/lib/views/instances.mjs +43 -25
  57. package/packages/tui/lib/views/palette.mjs +61 -0
  58. package/packages/tui/lib/views/souls.mjs +268 -0
  59. package/packages/tui/lib/views/spawn.mjs +299 -0
  60. package/packages/tui/lib/views/split.mjs +29 -0
  61. package/skills/oats-getting-started/SKILL.md +2 -2
@@ -9,17 +9,29 @@
9
9
  // removed, and nothing here decides what a failed read means or which view a deployment is in.
10
10
  // Selection is an identity (the shared `instanceId`), never an index, so it survives every read;
11
11
  // the rows it moves among are the model's, in drawn order.
12
- import { ACTIONS, bindings } from "./actions.mjs";
13
- import { collapseKey, displayLine, instanceActs, instanceId, pendingEntry } from "./client.mjs";
12
+ import { ACTIONS, LEADER_KEYS, bindings } from "./actions.mjs";
13
+ import { collapseKey, displayLine, instanceActs, instanceId, outcomeWords, pendingEntry, spawnProblem } from "./client.mjs";
14
14
  import { DETACH_KEY } from "./config.mjs";
15
- import { BUTTON_ORDER, NOT_BUILT, actDecision, disclosure, openDecision, preflightLine, returnedLine, roster, switcher } from "./model.mjs";
15
+ import { BUTTON_ORDER, SPAWN_WORDS, SPLIT_WORDS, TAB_WORDS, actDecision, disclosure, openDecision, paletteItems, preflightLine, returnedLine, roster, soulNames, soulOfAgent, soulsOf, spawnChoices, spawnChoicesKey, spawnLine, spawnPickerItems, spawnReady, spawnRing, spawnSelector, spawnedRow, switcher } from "./model.mjs";
16
+ import { backKeyId } from "./term/through.mjs";
16
17
  import { windowOf } from "./views/scroll.mjs";
18
+ import { SPLIT_MIN, splitFits } from "./views/split.mjs";
17
19
 
18
20
  /** The longest filter, in UTF-16 units. */
19
21
  export const QUERY_LIMIT = 200;
20
22
  const GRAPHEMES = new Intl.Segmenter(undefined, { granularity: "grapheme" });
21
23
  const LINE_END = /\r\n|[\n\r\u2028\u2029]/;
24
+ /** The instance list's filter: the text typed after `/`, or (`soul`, only while it is set) the
25
+ * exact filter of one soul's instances that the Souls view's `i` sets, `{ name, names }` (the
26
+ * names an instance's soul may carry: lib/model.mjs soulNames). Never both: `/` replaces the soul
27
+ * filter, and Esc clears it. */
22
28
  const NO_FILTER = Object.freeze({ editing: false, query: "" });
29
+ /** The Souls view's own (docs/tui.md, "The Souls view"): whether its catalog was ever wanted (the
30
+ * view opened once: a run that never opens it never reads one), what the loop holds of each
31
+ * workspace's catalog (`held`: id -> `{ entry, reading }`, the shared catalog's projected entry
32
+ * and whether a read of it is in flight), and the selection (a soul's name), the scroll, the focus
33
+ * and the filter of the view, kept when it is left and found again, for the run. */
34
+ const NO_SOULS = Object.freeze({ wanted: false, held: new Map(), selected: null, top: 0, loose: false, focus: "list", detailTop: 0, filter: Object.freeze({ editing: false, query: "" }) });
23
35
 
24
36
  /** The state before the first answer. `deployment` is the one `oats tui` was started in or was
25
37
  * told of, with its shared pending entry (lib/main.mjs makes it); null for a run started outside
@@ -38,21 +50,42 @@ const NO_FILTER = Object.freeze({ editing: false, query: "" });
38
50
  * `opening`: the agent of another machine whose terminal is being opened, or null:
39
51
  * `{ id, phase: "preflight", name, machine, routed }` while that machine is asked whether its
40
52
  * session is there; `name`, `machine` and `routed` are the row's as it was when Enter was
41
- * pressed, for the line after. `terminal`: the open terminal, or null (one at a time):
42
- * `{ id, name, machine, routed, focus, zoom, status }`, `id` the row's instanceId and the next
43
- * three the row's as it was when it was opened; `focus` "terminal" while what is typed goes to
44
- * the agent and "list" while the TUI reads keys; `zoom` true while it has the whole body (only
45
- * with the terminal's focus); `status` "starting" until the panel has its window, then "open".
53
+ * pressed, for the line after. `tabs`: the terminals open in the panel (docs/tui.md, "Tabs"),
54
+ * in the strips' order (each group's tabs in this order), at most TAB_LIMIT across both groups:
55
+ * each `{ id, name, machine, routed, status, activity, group }`, `id` the row's instanceId and the
56
+ * next three the row's as it was when it was opened, `status` "starting" until the panel has its
57
+ * window, then "open", `activity` true while it is hidden and its agent wrote since it was last
58
+ * shown, `group` 0 or 1 (docs/tui.md, "Splits"). `split`: null, or "right" or "down" while the
59
+ * panel is split in two groups; `group` the focused group (where an open goes); `aside` the other
60
+ * group's shown tab's id, or null (no split, or that group empty). `terminal`: the focused group's
61
+ * SHOWN tab, or null when no tab is open or the focused group is empty:
62
+ * `{ id, name, machine, routed, group, focus, zoom, status }`, its tab's fields with `focus`
63
+ * "terminal" while what is typed goes to the agent and "list" while the TUI reads keys, and `zoom`
64
+ * true while it has the whole body (only with the terminal's focus).
46
65
  * `outcome`: the line after an open (the model's `{ said, under }`), shown above the panes until
47
66
  * the next key bound to an action, or null.
48
- * `detachKey`: tui.json's `open.detachKey`, the back key: it takes the focus from the terminal.
67
+ * `detachKey`: tui.json's `open.detachKey`, the leader (docs/tui.md, "The leader"), and
68
+ * `leaderKey` the key id it is read as where the TUI reads keys (term/through.mjs backKeyId).
69
+ * `leader`: `{ read, waiting }` from the leader's read on, or null (see `leading`).
70
+ * `palette`: the palette while it is open (see `paletteOpened`), or null. `recent`: the ids of
71
+ * the instances opened in this run, the latest first.
49
72
  * `act`: the confirmation open in the act view (see `actOpened`), or null; `acted` counts the
50
73
  * confirmations opened in this run, so an answer for one that was closed is told apart.
51
74
  * `starting`: id -> `{ verb, since }` of this run's starts and restarts whose child is still
52
75
  * alive, whether or not the TUI still waits for its answer (the loop says when one is spawned and
53
76
  * when it closes): no act opens on such a row.
54
- * The roster is made from none of `opening`, `terminal`, `outcome`, `act`, `acted` and `starting`
55
- * (lib/model.mjs MADE_FROM). */
77
+ * `retiring`: the instanceIds of the rows whose retire this run sent and has not read since
78
+ * (#1247), as lib/main.mjs's tracker says them (`{ retiring }`): they read as retiring. The roster
79
+ * is made from it (lib/model.mjs MADE_FROM), and from none of `opening`, `terminal`, `outcome`,
80
+ * `act`, `acted`, `starting`, `leader`, `palette` and `recent`.
81
+ * A SPAWN (docs/tui.md, "Spawning an agent"; see `spawnAsked`): `spawn` the prompt while it is
82
+ * open, or null; `spawning` the one spawn under way, `{ name, soul, workspace, phase, prompt }`
83
+ * (`phase` "submitting", "spawning" or "checking"; `prompt` the prompt as it was pressed, to come
84
+ * back to), or null; `spawnCheck` `{ name }` while a check of an outcome not known is offered
85
+ * (`C`), or null; `arriving` the instance a spawn created, `{ workspace, instance, home,
86
+ * agentsRoot, agent, reads, words }`, until its row is opened or two reads did not show it;
87
+ * `previews` the number of the last preview read asked in the run, so that an answer to a prompt
88
+ * already closed is never taken by the next one. */
56
89
  export function initialState({ deployment = null, cli, home, entry = null, actions = ACTIONS, ascii = false, detachKey = DETACH_KEY }) {
57
90
  return Object.freeze({
58
91
  view: deployment === null ? "switcher" : "instances", back: deployment === null ? "switcher" : "instances",
@@ -63,7 +96,9 @@ export function initialState({ deployment = null, cli, home, entry = null, actio
63
96
  selected: null, collapsed: new Set(), filter: NO_FILTER, focus: "list", top: 0, loose: false, detailTop: 0, places: new Map(), unread: new Map(),
64
97
  switcher: Object.freeze({ editing: false, query: "", selected: null, top: 0, loose: false, line: null, refused: null }),
65
98
  offered: Object.freeze({ offered: Object.freeze([]), limited: false }),
66
- helpTop: 0, actions, ascii, detachKey, opening: null, terminal: null, outcome: null, act: null, acted: 0, starting: new Map(),
99
+ helpTop: 0, actions, ascii, detachKey, opening: null, terminal: null, outcome: null, act: null, acted: 0, starting: new Map(), retiring: new Set(),
100
+ leaderKey: backKeyId(detachKey), leader: null, palette: null, recent: Object.freeze([]), souls: NO_SOULS,
101
+ spawn: null, spawning: null, spawnCheck: null, arriving: null, previews: 0, tabs: Object.freeze([]), split: null, group: 0, aside: null,
67
102
  });
68
103
  }
69
104
 
@@ -161,7 +196,11 @@ function took(state, { id, entry, number }) {
161
196
  if (observed && unread.has(id)) { unread = new Map(unread); unread.delete(id); }
162
197
  else if (!observed && held?.deployment?.status === "observed") unread = new Map(unread).set(id, new Set((Array.isArray(held.instances) ? held.instances : []).map(instanceId)));
163
198
  const taken = next(state, { entries: new Map(state.entries).set(id, entry), numbers: new Map(state.numbers).set(id, number), unread });
164
- return observed ? settled(state, taken) : { state: taken, effect: null };
199
+ if (!observed) return { state: taken, effect: null };
200
+ const step = settled(state, taken);
201
+ if (step.state.arriving?.workspace !== id) return step;
202
+ const then = arrived(step.state);
203
+ return { state: then.state, effect: both(step.effect, then.effect) };
165
204
  }
166
205
 
167
206
  /** The roster of other machines after one outcome, as the shared rule made it (lib/read.mjs),
@@ -214,6 +253,11 @@ const FIELDS = Object.freeze({
214
253
  put: (state, query) => queried(state, query),
215
254
  close: (state, query) => next(queried(state, query), { filter: Object.freeze({ editing: false, query }) }),
216
255
  }),
256
+ souls: Object.freeze({
257
+ query: (state) => state.souls.filter.query,
258
+ put: (state, query) => (query === state.souls.filter.query ? state : soulsWith(state, { filter: Object.freeze({ ...state.souls.filter, query }), top: 0, loose: false, detailTop: 0 })),
259
+ close: (state, query) => soulsWith(state, { filter: Object.freeze({ editing: false, query }), top: 0, loose: false }),
260
+ }),
217
261
  switcher: Object.freeze({
218
262
  query: (state) => state.switcher.query,
219
263
  put: (state, query) => (query === state.switcher.query ? state : next(state, { switcher: Object.freeze({ ...state.switcher, query, top: 0, loose: false }) })),
@@ -221,7 +265,9 @@ const FIELDS = Object.freeze({
221
265
  }),
222
266
  });
223
267
  /** The filter field that is open now, or null. */
224
- const fieldOf = (state) => (state.view === "instances" && state.filter.editing ? FIELDS.instances : state.view === "switcher" && state.switcher.editing ? FIELDS.switcher : null);
268
+ const fieldOf = (state) => (state.view === "instances" && state.filter.editing ? FIELDS.instances
269
+ : state.view === "switcher" && state.switcher.editing ? FIELDS.switcher
270
+ : state.view === "souls" && state.souls.filter.editing ? FIELDS.souls : null);
225
271
 
226
272
  /** A key while a filter field is open. A key that is text is text, whatever the action table
227
273
  * says, so `q` and `j` can be typed; Backspace removes one grapheme, Enter keeps the filter and
@@ -239,6 +285,67 @@ function edited(state, field, event, action) {
239
285
  return { state, effect: null };
240
286
  }
241
287
 
288
+ /** The Souls view's own state with what changes of it. */
289
+ const soulsWith = (state, changes) => next(state, { souls: Object.freeze({ ...state.souls, ...changes }) });
290
+
291
+ /** The Souls view shown (docs/tui.md, "The Souls view"): from now on its catalog is wanted, and
292
+ * the loop settles it for the open workspace (`souls: "settle"`), which reads it only when nothing
293
+ * is held for the workspace as it is now (the shared catalog's key). */
294
+ function soulsShown(state) {
295
+ // Come back to from another view, it shows its list: what was selected and filtered stays.
296
+ const shown = state.view === "souls" ? state : next(state, { view: "souls", back: "souls", souls: Object.freeze({ ...state.souls, focus: "list" }) });
297
+ return { state: soulsWith(shown, { wanted: true }), effect: { souls: "settle" } };
298
+ }
299
+
300
+ /** What the loop holds of a workspace's catalog, told: `{ id, entry, reading }` (the shared
301
+ * catalog's projected entry, or null, and whether a read is in flight). Only a served workspace's
302
+ * is kept. */
303
+ function soulsHeard(state, { id, entry, reading }) {
304
+ if (!state.ctxs.includes(id)) return { state, effect: null };
305
+ const held = soulsWith(state, { held: new Map(state.souls.held).set(id, Object.freeze({ entry: entry ?? null, reading: reading === true })) });
306
+ // A prompt that waits for this catalog to know its soul (N, before the Souls view was ever read).
307
+ return held.spawn?.workspace === id && held.spawn.step === "preview" && held.spawn.soul === null ? soulFound(held) : { state: held, effect: null };
308
+ }
309
+
310
+ /** The Instances view with the instances of soul `row` alone: the exact soul filter, shown where a
311
+ * kept filter stands; Esc clears it and `/` replaces it. */
312
+ function soulInstances(state, row) {
313
+ const filter = Object.freeze({ editing: false, query: "", soul: Object.freeze({ name: row.name, names: Object.freeze(soulNames(row)) }) });
314
+ return { state: rehomed(roster(state), next(state, { view: "instances", back: "instances", focus: "list", filter, top: 0, loose: false })), effect: null };
315
+ }
316
+
317
+ /** A key in the Souls view (docs/tui.md, "The Souls view"). The list's keys move among the souls
318
+ * the filter keeps, or scroll the detail while it has the focus; Enter gives the detail the focus,
319
+ * and from the detail does what `i` does, the selected soul's instances in the Instances view; `/`
320
+ * opens the view's own filter field; `r` reads the catalog again (`souls: "reread"`, which starts
321
+ * nothing while a read is in flight); Esc closes the detail, then clears a kept filter, then goes
322
+ * back to the instances (to the switcher when no workspace is open), as `1` does. */
323
+ function inSouls(state, action, event, page, scrolled) {
324
+ const stay = { state, effect: null }, v = state.souls;
325
+ const s = soulsOf(state), at = s.selected ? s.rows.indexOf(s.selected) : -1;
326
+ const back = () => ({ state: state.open === null ? toSwitcher(next(state, { back: "switcher" })) : next(state, { view: "instances", back: "instances" }), effect: null });
327
+ switch (action) {
328
+ case "instances": return back();
329
+ case "close":
330
+ if (v.focus === "detail") return { state: soulsWith(state, { focus: "list" }), effect: null };
331
+ if (v.filter.query !== "") return { state: soulsWith(state, { filter: Object.freeze({ editing: false, query: "" }), top: 0, loose: false }), effect: null };
332
+ return back();
333
+ case "filter": return s.local ? { state: soulsWith(state, { focus: "list", filter: Object.freeze({ ...v.filter, editing: true }) }), effect: null } : stay;
334
+ case "refresh": return s.local ? { state, effect: { souls: "reread" } } : stay;
335
+ case "open": return at < 0 ? stay : v.focus === "detail" ? soulInstances(state, s.selected) : { state: soulsWith(state, { focus: "detail" }), effect: null };
336
+ case "detail": return at < 0 ? stay : { state: soulsWith(state, { focus: v.focus === "detail" ? "list" : "detail" }), effect: null };
337
+ case "soul-instances": return at < 0 ? stay : soulInstances(state, s.selected);
338
+ case "up": case "down": case "top": case "bottom": case "page-up": case "page-down": {
339
+ if (v.focus === "detail") return { state: soulsWith(state, { detailTop: scrolled(v.detailTop) }), effect: null };
340
+ if (!s.rows.length) return stay;
341
+ const to = Math.min(Math.max(0, at < 0 ? 0 : moved(action, at, s.rows.length, page)), s.rows.length - 1);
342
+ const name = s.rows[to].name;
343
+ return { state: soulsWith(state, { selected: name, loose: false, detailTop: name === s.selected?.name ? v.detailTop : 0 }), effect: null };
344
+ }
345
+ default: return stay;
346
+ }
347
+ }
348
+
242
349
  const MOVES = Object.freeze(["up", "down", "top", "bottom", "page-up", "page-down"]);
243
350
  /** Where a movement key takes a position `from` among `count` rows, a page being `page` rows. */
244
351
  function moved(action, from, count, page) {
@@ -299,7 +406,8 @@ function switched(state, action, page) {
299
406
  * and `room` the rows the other scrolling pane holds and shows, as the last frame drew them: the
300
407
  * store keeps no size); a paste, `{ paste: <text> }`; or what the loop read:
301
408
  * `{ id, entry, number }` (a served deployment's entry), `{ roster: { remote, memory, notes, at } }`
302
- * (one outcome of the roster read), `{ collecting }`, `{ offered: { offered, limited } }` (the
409
+ * (one outcome of the roster read), `{ collecting }`, `{ retiring: <Set of instanceIds> }` (this
410
+ * run's retires in flight now), `{ offered: { offered, limited } }` (the
303
411
  * deployments of `~/Agents` not served), `{ admitted: <deployment>, at }` and `{ refused: <path> }`
304
412
  * (what a picked folder turned out to be).
305
413
  * Opening an agent gives five more: `{ prepared: { id, error? } }` (the preflight of another
@@ -308,7 +416,8 @@ function switched(state, action, page) {
308
416
  * viewer's window), `{ returned: { id, status, stderr, asked, refused } }` (the viewer ended: what
309
417
  * its pane wrote of its exit status and stderr, whether it was closed because the TUI asked, and
310
418
  * the panel's refusal when it started none: model.mjs returnedLine) and
311
- * `{ back: true }` (the back key was typed in the terminal).
419
+ * `{ back: true, read, rest }` (the leader was typed in the terminal, in that read of input;
420
+ * `rest`: more bytes came after it in the same read).
312
421
  * An effect is something only the loop can do: "quit", "suspend", "redraw", or an object with
313
422
  * any of `refresh: { live }` (read now), `offer: true` (list `~/Agents` again),
314
423
  * `admit: <path>` (ask whether a picked folder is a deployment), `close: <id>` (close the open
@@ -319,7 +428,13 @@ function switched(state, action, page) {
319
428
  * nothing (a stray back key is no key at all) leaves it. */
320
429
  export function reduce(state, event, keymap = bindings(state.actions)) {
321
430
  if (state.outcome !== null && typeof event.key === "string" && keymap.has(event.key)) state = next(state, { outcome: null });
322
- const step = reduced(state, event, keymap);
431
+ let step = reduced(state, event, keymap);
432
+ // The tabs are the open workspace's: whatever opened another (or left it, gone), they all close,
433
+ // and the split with them.
434
+ if (step.state.open !== state.open && (step.state.tabs.length || step.state.split !== null)) {
435
+ const ids = step.state.tabs.map((tab) => tab.id);
436
+ step = { state: next(step.state, { tabs: Object.freeze([]), terminal: null, ...NO_SPLIT }), effect: ids.length ? both(step.effect, { close: ids }) : step.effect };
437
+ }
323
438
  // The terminal has the focus only while the list of instances is shown: anything that shows
324
439
  // another view (a workspace gone, which shows the switcher) gives the focus back to the list.
325
440
  const t = step.state.terminal;
@@ -332,10 +447,110 @@ export function reduce(state, event, keymap = bindings(state.actions)) {
332
447
  return under ? { ...step, state: next(step.state, { focus: "list", filter: Object.freeze({ ...step.state.filter, editing: false }) }) } : step;
333
448
  }
334
449
 
335
- /** The terminal of an open decision (the model's openDecision), starting, with the focus. */
336
- const startingTerminal = ({ id, name, machine, routed }) => Object.freeze({ id, name, machine, routed, focus: "terminal", zoom: false, status: "starting" });
337
- /** The open terminal with what changes of it. */
450
+ /** The shown terminal with what changes of it: its focus and zoom (a change of its status goes
451
+ * through tabWith, which keeps its tab in step). */
338
452
  const terminalWith = (state, changes) => next(state, { terminal: Object.freeze({ ...state.terminal, ...changes }) });
453
+ /** Tab `id` with what changes of it, and the shown terminal with it when it is that tab. */
454
+ function tabWith(state, id, changes) {
455
+ const tabs = Object.freeze(state.tabs.map((tab) => (tab.id === id ? Object.freeze({ ...tab, ...changes }) : tab)));
456
+ const { activity, ...shared } = changes;
457
+ return next(state, { tabs, ...(state.terminal?.id === id ? { terminal: Object.freeze({ ...state.terminal, ...shared }) } : {}) });
458
+ }
459
+ /** No split: one group, focused. */
460
+ const NO_SPLIT = Object.freeze({ split: null, group: 0, aside: null });
461
+ /** Group `g`'s tabs, in the strip's order. */
462
+ const inGroup = (state, g) => state.tabs.filter((tab) => tab.group === g);
463
+ /** Group `g`'s shown tab's id: the focused group's is the terminal's, the other's `aside`. */
464
+ const shownOf = (state, g) => (g === state.group ? state.terminal?.id ?? null : state.aside);
465
+ /** The cap's line: every tab is taken, and how to free one (the leader's close). */
466
+ const fullLine = (state) => Object.freeze({ said: TAB_WORDS.full(TAB_LIMIT, state.detachKey), under: Object.freeze([]) });
467
+
468
+ /** A new tab for an open decision (the model's openDecision), starting, in the focused group:
469
+ * placed after its shown one (last, with none shown: an empty group's first) and shown, with the
470
+ * focus. */
471
+ function tabOpened(state, { id, name, machine, routed }) {
472
+ const group = state.group, tab = Object.freeze({ id, name, machine, routed, status: "starting", activity: false, group });
473
+ const at = state.terminal === null ? state.tabs.length : state.tabs.findIndex((each) => each.id === state.terminal.id) + 1;
474
+ const tabs = Object.freeze([...state.tabs.slice(0, at), tab, ...state.tabs.slice(at)]);
475
+ return next(state, { tabs, terminal: Object.freeze({ id, name, machine, routed, group, focus: "terminal", zoom: false, status: "starting" }) });
476
+ }
477
+
478
+ /** Tab `id` shown (docs/tui.md, "Tabs"), with `focus` and `zoom` (the shown one's, by default),
479
+ * in its group, which is the focused one from then on (docs/tui.md, "Splits"):
480
+ * its activity mark goes, it is the most recent for the palette, its instance's row is selected
481
+ * and revealed (a filter that hides it is cleared, a collapsed parent opened), and the focus stays
482
+ * where it was. The loop is told to show it unless it is the one shown already. */
483
+ function showTab(state, id, { focus = state.terminal?.focus ?? "list", zoom = state.terminal?.zoom ?? false } = {}) {
484
+ const tab = state.tabs.find((each) => each.id === id);
485
+ if (!tab) return { state, effect: null };
486
+ const { activity, ...fields } = tab;
487
+ const before = state.terminal?.id ?? null;
488
+ // A tab of the other group: that group is focused now, and the one left keeps its shown tab.
489
+ const across = tab.group !== state.group ? { group: tab.group, aside: before } : {};
490
+ const shown = next(state, {
491
+ tabs: Object.freeze(state.tabs.map((each) => (each.id === id && each.activity ? Object.freeze({ ...each, activity: false }) : each))),
492
+ terminal: Object.freeze({ ...fields, focus, zoom: focus === "terminal" && zoom }),
493
+ recent: recentWith(state, id),
494
+ ...across,
495
+ });
496
+ return { state: revealed(shown, id), effect: before === id ? null : { show: id } };
497
+ }
498
+
499
+ /** The row of instance `id` selected and on view in the list (Settled 5 of T2): a text filter
500
+ * that hides it is cleared, and a collapsed instance above it is opened. The focus is not moved,
501
+ * and nothing is selected when the row is not in the roster at all (it went away). */
502
+ function revealed(state, id) {
503
+ if (state.view !== "instances" || state.open === null) return state;
504
+ let s = state;
505
+ if (!roster(s).index.has(id) && (s.filter.query !== "" || s.filter.soul)) s = rehomed(roster(s), next(s, { filter: NO_FILTER, top: 0, loose: false }));
506
+ if (!roster(s).index.has(id) && s.collapsed.size) {
507
+ // The collapsed instances that hide it: each one alone would.
508
+ const hiding = [...s.collapsed].filter((key) => !roster(next(s, { collapsed: new Set([key]) })).index.has(id));
509
+ if (hiding.length) { const collapsed = new Set(s.collapsed); for (const key of hiding) collapsed.delete(key); s = next(s, { collapsed }); }
510
+ }
511
+ return roster(s).index.has(id) ? next(s, { selected: id, loose: false, detailTop: id === s.selected ? s.detailTop : 0 }) : s;
512
+ }
513
+
514
+ /** The shown tab closed by the person (`c` in the list, the leader then `w`): its viewer ends
515
+ * (the agent keeps running), the tab to its right is shown, else the one to its left, with the
516
+ * focus `focus` and the zoom `zoom` (the closed one's), within its group; a group's last one
517
+ * closed removes the group (ungrouped), and the last one of all gives the right side back to the
518
+ * detail and the focus to the list. */
519
+ function shownClosed(state, focus, zoom = state.terminal?.zoom ?? false) {
520
+ const t = state.terminal;
521
+ if (t === null) return { state, effect: null };
522
+ const mine = inGroup(state, state.group), at = mine.findIndex((tab) => tab.id === t.id);
523
+ const rest = mine.filter((tab) => tab.id !== t.id), neighbour = rest[at] ?? rest[at - 1] ?? null;
524
+ const closed = next(state, { tabs: Object.freeze(state.tabs.filter((tab) => tab.id !== t.id)), terminal: null });
525
+ // The group's last tab: the group goes, and the other takes the panel (or none is left).
526
+ const step = neighbour !== null ? showTab(closed, neighbour.id, { focus, zoom })
527
+ : state.split !== null ? ungrouped(closed, state.group, focus)
528
+ : { state: next(closed, { focus: "list" }), effect: null };
529
+ return { state: step.state, effect: both({ close: [t.id] }, step.effect) };
530
+ }
531
+
532
+ /** Group `g` of a split, empty now, removed (docs/tui.md, "Splits"): the other group takes the
533
+ * whole panel, as group 0, and is focused, its shown tab with the focus `focus`. When it is empty
534
+ * too nothing is left, and the panel closes. */
535
+ function ungrouped(state, g, focus) {
536
+ const left = shownOf(state, 1 - g);
537
+ const tabs = Object.freeze(state.tabs.map((tab) => (tab.group === 0 ? tab : Object.freeze({ ...tab, group: 0 }))));
538
+ const one = next(state, { tabs, terminal: null, ...NO_SPLIT });
539
+ if (left === null) return { state: next(one, { focus: "list" }), effect: null };
540
+ return showTab(one, left, { focus, zoom: false });
541
+ }
542
+
543
+ /** The tab before or after the shown one (`step` -1 or 1) in the focused group shown, without
544
+ * wrapping and never into the other group: at either end
545
+ * nothing moves, nor while a tab is still starting (it is the shown one until the panel has its
546
+ * window). The focus stays where it was, and so does the zoom. */
547
+ function tabStepped(state, step, { focus = state.terminal?.focus ?? "list", zoom = state.terminal?.zoom ?? false } = {}) {
548
+ const t = state.terminal;
549
+ if (t === null || state.tabs.some((tab) => tab.status === "starting")) return { state, effect: null };
550
+ const mine = inGroup(state, state.group), at = mine.findIndex((tab) => tab.id === t.id) + step;
551
+ if (at < 0 || at >= mine.length) return { state, effect: null };
552
+ return showTab(state, mine[at].id, { focus, zoom });
553
+ }
339
554
 
340
555
  /** The preflight of another machine's agent ended. Given up meanwhile (Esc, a suspend, a second
341
556
  * open): dropped. Failed: the line that says so, unless it is the person's own giving up. Else
@@ -345,60 +560,157 @@ function prepared(state, { id, error }) {
345
560
  if (opening === null || opening.id !== id || opening.phase !== "preflight") return { state, effect: null };
346
561
  if (error !== undefined) return { state: next(state, { opening: null, outcome: preflightLine(opening, error) }), effect: null };
347
562
  if (!roster(state).instances.some((row) => instanceId(row) === id)) return { state: next(state, { opening: null }), effect: null };
348
- return { state: next(state, { opening: null, terminal: startingTerminal(opening) }), effect: { panel: id } };
563
+ return { state: tabOpened(next(state, { opening: null }), opening), effect: { panel: id } };
349
564
  }
350
565
 
351
- /** The viewer of the open terminal ended: the right side is the detail's again, the focus the
352
- * list's, the line says what happened (nothing, when the person closed it), and the instances are
353
- * read again at once. It is never opened again on its own: Enter opens it. An end of a terminal
354
- * that is no longer the open one (closed by the person, then reported) changes nothing. */
566
+ /** The viewer of a tab ended by itself: its tab closes, the line says what happened, naming its
567
+ * instance (nothing when it ended cleanly), and the instances are read again at once. The shown
568
+ * one's end shows the tab to its right, else the one to its left, with the focus in the list
569
+ * (Settled 6 of T2); the last one's gives the right side back to the detail. The other group's
570
+ * shown one's end shows its neighbour there; a group's last one's removes the group (Settled 5 of
571
+ * T3). A hidden one's end changes neither the shown tab nor the focus. A tab is never opened again on its own: Enter opens
572
+ * it. The end of a tab the person closed (no longer a tab, then reported) changes nothing. */
355
573
  function returned(state, { id, status, stderr, asked = false, refused = null }) {
356
- const t = state.terminal;
357
- if (t === null || t.id !== id) return { state, effect: null };
358
- return { state: next(state, { terminal: null, outcome: returnedLine(t, status, stderr, { asked, refused }) }), effect: { refresh: { live: true } } };
574
+ const tab = state.tabs.find((each) => each.id === id);
575
+ if (!tab) return { state, effect: null };
576
+ const line = returnedLine(tab, status, stderr, { asked, refused });
577
+ const mine = inGroup(state, tab.group), at = mine.findIndex((each) => each.id === id);
578
+ const rest = mine.filter((each) => each.id !== id), neighbour = rest[at] ?? rest[at - 1] ?? null;
579
+ const tabs = Object.freeze(state.tabs.filter((each) => each.id !== id));
580
+ const read = { refresh: { live: true } };
581
+ const focused = state.terminal?.id === id, aside = state.aside === id;
582
+ if (!focused && !aside) return { state: next(state, { tabs, ...(line ? { outcome: line } : {}) }), effect: read };
583
+ // The other group's shown tab: its neighbour is shown there, and nothing else moves.
584
+ if (aside && neighbour !== null) {
585
+ const shown = Object.freeze(tabs.map((each) => (each.id === neighbour.id && each.activity ? Object.freeze({ ...each, activity: false }) : each)));
586
+ return { state: next(state, { tabs: shown, aside: neighbour.id, ...(line ? { outcome: line } : {}) }), effect: read };
587
+ }
588
+ const closed = next(state, { tabs, ...(focused ? { terminal: null } : { aside: null }), outcome: line });
589
+ // A group's last tab ended: the group goes, the other takes the panel, the list the focus (Settled 5 of T3).
590
+ if (neighbour === null && state.split !== null) {
591
+ const step = ungrouped(next(closed, { focus: "list" }), tab.group, "list");
592
+ return { state: step.state, effect: both(read, step.effect) };
593
+ }
594
+ if (neighbour === null) return { state: closed, effect: read };
595
+ // The list takes the focus, from the detail too (Settled 6 of T2), so the neighbour is drawn.
596
+ const step = showTab(next(closed, { focus: "list" }), neighbour.id, { focus: "list" });
597
+ return { state: step.state, effect: both(read, step.effect) };
359
598
  }
360
599
 
361
- /** Enter in the list of instances: on the row whose terminal is open, the focus goes to it; on
362
- * another, the selected agent's terminal is opened (the open one is closed first: one at a time),
363
- * or the line says why not. Nothing while another machine is asked first. */
364
- function openAgent(state, r, at) {
365
- if (state.opening !== null || at < 0) return { state, effect: null };
366
- const row = r.items[at].row, t = state.terminal;
367
- if (t !== null && t.id === instanceId(row)) return { state: terminalWith(state, { focus: "terminal", zoom: false }), effect: null };
600
+ /** Enter in the list of instances (or a row of the palette, the leader's Up and Down, a spawn's
601
+ * arrival): an instance open as a tab shows that tab, with the focus in it; another is opened as
602
+ * a new tab after the shown one, shown, with the focus (docs/tui.md, "Tabs"), or the line says why
603
+ * not. At the cap nothing closes on its own: the line says so. One open at a time (Settled 3 of
604
+ * T2): nothing while another machine is asked first or a tab is still starting, and a preflight
605
+ * holds its tab's place in the cap. Every open counts for the palette's recency (`recent`), as
606
+ * every tab shown does (showTab). */
607
+ function openAgent(state, row) {
608
+ if (state.opening !== null) return { state, effect: null };
609
+ const id = instanceId(row);
610
+ // A tab still starting is the one shown until the panel has its window (one open at a time).
611
+ const starting = state.tabs.some((tab) => tab.status === "starting");
612
+ if (state.tabs.some((tab) => tab.id === id)) {
613
+ if (starting && state.terminal?.id !== id) return { state, effect: null };
614
+ const step = showTab(state, id, { focus: "terminal", zoom: false });
615
+ return { state: step.state, effect: step.effect };
616
+ }
617
+ if (starting) return { state, effect: null };
368
618
  const decision = openDecision(state, row, instanceActs(row));
369
619
  if (!decision.open) return { state: next(state, { outcome: decision.said }), effect: null };
370
- const close = t === null ? {} : { close: t.id };
620
+ if (state.tabs.length >= TAB_LIMIT) return { state: next(state, { outcome: fullLine(state) }), effect: null };
621
+ state = next(state, { recent: recentWith(state, decision.id) });
371
622
  if (decision.routed) {
372
623
  const opening = Object.freeze({ id: decision.id, phase: "preflight", name: decision.name, machine: decision.machine, routed: true });
373
- return { state: next(state, { opening, terminal: null, outcome: null }), effect: { ...close, open: decision } };
624
+ return { state: next(state, { opening, outcome: null }), effect: { open: decision } };
374
625
  }
375
- return { state: next(state, { terminal: startingTerminal(decision), outcome: null }), effect: { ...close, open: decision } };
626
+ return { state: next(tabOpened(state, decision), { outcome: null }), effect: { open: decision } };
376
627
  }
377
628
 
378
- /** The keys of the open terminal from the list: zoom gives it the focus and the whole body, and
379
- * close ends its viewer (the agent keeps running) and gives the right side back to the detail. */
380
- function terminalKey(state, action) {
629
+ /** The keys of the shown terminal from the list: zoom gives it the focus and the whole body, and
630
+ * close ends its viewer (the agent keeps running) and shows its neighbour, the focus `focus`. */
631
+ function terminalKey(state, action, focus = "list", zoom = false) {
381
632
  const t = state.terminal;
382
633
  if (t === null) return { state, effect: null };
383
634
  if (action === "zoom") return { state: terminalWith(state, { focus: "terminal", zoom: true }), effect: null };
384
- return { state: next(state, { terminal: null }), effect: { close: t.id } };
635
+ return shownClosed(state, focus, zoom);
636
+ }
637
+
638
+ /** THE SPLIT'S KEYS (docs/tui.md, "Splits"). Why `does` would do nothing now: `true` for nothing
639
+ * at all (no tab, a tab starting, a key that does not apply), the line that says why (a split
640
+ * there is no room for, a second split), or null when it acts. `room` is the panel's size as the
641
+ * Instances view gives it with the terminal's focus (`{ cols, rows }`, its strip row counted:
642
+ * views/frame.mjs panelPlace), measured when the key is read; a room not known admits no split. Asked
643
+ * before anything is settled, so that a key that does nothing moves no focus. */
644
+ export function splitRefused(state, does, room, inTerminal = false) {
645
+ if (state.tabs.length === 0 || state.tabs.some((tab) => tab.status === "starting") || state.opening !== null) return true;
646
+ switch (does) {
647
+ case "split-right": case "split-down": {
648
+ const dir = does === "split-right" ? "right" : "down";
649
+ if (state.split !== null) return Object.freeze({ said: SPLIT_WORDS.twice(), under: Object.freeze([]) });
650
+ return splitFits(dir, room) ? null : Object.freeze({ said: SPLIT_WORDS.small(dir, SPLIT_MIN), under: Object.freeze([]) });
651
+ }
652
+ // One group: only from the list, to its terminal.
653
+ case "group-next": return state.split === null && (inTerminal || state.terminal === null) ? true : null;
654
+ case "tab-move": return state.split === null || state.terminal === null ? true : null;
655
+ case "group-close": return state.split === null || state.terminal !== null ? true : null;
656
+ default: return true;
657
+ }
658
+ }
659
+ /** A key of the split that acts (splitRefused said null), from the Instances view, `inTerminal`
660
+ * when it came from the terminal's focus:
661
+ * split-right, split-down: the tabs stay in the first group (left or top), and the second, empty,
662
+ * is the focused one; the keys are the list's (Settled 2 of T3), so Enter on a row opens there;
663
+ * group-next: to the other group's shown terminal, with the focus (to the empty group: focused,
664
+ * the keys the list's); from the list, to the focused group's terminal, or with that group
665
+ * empty to the other's;
666
+ * tab-move: the focused group's shown tab to the other group, after its shown tab, shown there
667
+ * with the focus; the group it leaves shows its neighbour, or stays, empty;
668
+ * group-close: the empty focused group goes; the other takes the panel and is focused, and the
669
+ * keys stay the list's (Settled 8 of T3). */
670
+ function splitKey(state, does, inTerminal) {
671
+ const t = state.terminal, other = 1 - state.group;
672
+ switch (does) {
673
+ case "split-right": case "split-down":
674
+ return { state: next(state, { split: does === "split-right" ? "right" : "down", group: 1, aside: t?.id ?? null, terminal: null, focus: "list" }), effect: null };
675
+ case "group-next": {
676
+ if (state.split === null || (!inTerminal && t !== null)) return { state: terminalWith(state, { focus: "terminal" }), effect: null };
677
+ const there = shownOf(state, other);
678
+ if (there !== null) return showTab(state, there, { focus: "terminal", zoom: false });
679
+ return { state: next(state, { group: other, aside: t?.id ?? null, terminal: null, focus: "list" }), effect: null };
680
+ }
681
+ case "tab-move": {
682
+ const mine = inGroup(state, state.group), at = mine.findIndex((tab) => tab.id === t.id);
683
+ const rest = mine.filter((tab) => tab.id !== t.id), neighbour = rest[at] ?? rest[at - 1] ?? null;
684
+ const without = state.tabs.filter((tab) => tab.id !== t.id);
685
+ const place = state.aside === null ? without.length : without.findIndex((tab) => tab.id === state.aside) + 1;
686
+ const moved = Object.freeze({ ...state.tabs.find((tab) => tab.id === t.id), group: other, activity: false });
687
+ const tabs = Object.freeze([...without.slice(0, place), moved, ...without.slice(place)].map((tab) => (tab.id === neighbour?.id && tab.activity ? Object.freeze({ ...tab, activity: false }) : tab)));
688
+ const { activity, ...fields } = moved;
689
+ const s = next(state, { tabs, group: other, aside: neighbour?.id ?? null, terminal: Object.freeze({ ...fields, focus: "terminal", zoom: false }) });
690
+ return { state: revealed(s, t.id), effect: { show: t.id } };
691
+ }
692
+ case "group-close": return ungrouped(state, state.group, "list");
693
+ default: return { state, effect: null };
694
+ }
385
695
  }
386
696
 
387
697
  /** The keys of the act view that are not the action table's: the focus moves with these and with
388
698
  * no printable key, so nothing typed or pasted as text reaches a button. */
389
699
  const FOCUS_KEYS = Object.freeze({ left: -1, "shift+tab": -1, right: 1, tab: 1 });
390
700
 
391
- /** An act key in the list of instances: the confirmation it opens, or the line that says why not
392
- * (lib/model.mjs actDecision, over the row's instanceActs answer read now). A stop or a retire
393
- * asks the loop for the shared confirmation (`act`), which reads the plan; a start or a restart
394
- * opens the TUI's own confirmation, and nothing is asked of the loop until it is pressed. The
395
- * focus starts on the first button, Cancel. Nothing while an open is under way. */
396
- function actOn(state, r, at, verb) {
397
- if (state.opening !== null || at < 0) return { state, effect: null };
398
- const row = r.items[at].row, decision = actDecision(state, row, instanceActs(row), verb);
701
+ /** An act key on `row` (the selected one; the open terminal's from the terminal's focus): the
702
+ * confirmation it opens, or the line that says why not (lib/model.mjs actDecision, over the row's
703
+ * instanceActs answer read now). A stop or a retire asks the loop for the shared confirmation
704
+ * (`act`), which reads the plan; a start or a restart opens the TUI's own confirmation, and
705
+ * nothing is asked of the loop until it is pressed. The focus starts on the first button,
706
+ * Cancel. Nothing while an open is under way. `after`: "terminal" when the confirmation was
707
+ * asked for from the terminal's focus, which it gives back when it closes. */
708
+ function actOn(state, row, verb, after = null) {
709
+ if (state.opening !== null) return { state, effect: null };
710
+ const decision = actDecision(state, row, instanceActs(row), verb);
399
711
  if (!decision.open) return { state: next(state, { outcome: decision.said }), effect: null };
400
712
  const n = state.acted + 1;
401
- const base = { n, kind: decision.kind, verb, id: decision.id, name: decision.name, machine: decision.machine, home: decision.home, focus: "close", movedIn: null, top: 0 };
713
+ const base = { n, kind: decision.kind, verb, id: decision.id, name: decision.name, machine: decision.machine, home: decision.home, focus: "close", movedIn: null, top: 0, after };
402
714
  const act = decision.kind === "start"
403
715
  ? Object.freeze({ ...base, phase: "review", offers: Object.freeze(["close", "apply"]), answer: null })
404
716
  : Object.freeze({ ...base, phase: "reading", offers: Object.freeze(["close"]), outcome: null, notice: null, running: null, view: null, plan: null });
@@ -406,8 +718,13 @@ function actOn(state, r, at, verb) {
406
718
  }
407
719
 
408
720
  /** The confirmation closed by the person (Esc, or its Cancel or Close pressed): the view goes, and
409
- * the loop is told; a plan read, an apply or a start it sent goes on. */
410
- const actClosed = (state) => ({ state: next(state, { view: "instances", back: "instances", act: null }), effect: { dismiss: state.act.n } });
721
+ * the loop is told; a plan read, an apply or a start it sent goes on. One asked for from the
722
+ * terminal's focus gives it back, while that terminal is still the open one. */
723
+ function actClosed(state) {
724
+ const shut = next(state, { view: "instances", back: "instances", act: null }), t = shut.terminal;
725
+ const back = state.act.after === "terminal" && t !== null && t.id === state.act.id ? terminalWith(shut, { focus: "terminal", zoom: false }) : shut;
726
+ return { state: back, effect: { dismiss: state.act.n } };
727
+ }
411
728
 
412
729
  /** A key in the act view. Left/Right and Tab/Shift+Tab move the focus among the buttons, Enter
413
730
  * presses the one that has it, Esc closes, Space sets the plan's choice, the movement keys scroll
@@ -479,25 +796,269 @@ function acted(state, event) {
479
796
  return { state, effect: null };
480
797
  }
481
798
 
799
+ /** The instances the palette's recency keeps. */
800
+ const RECENT_KEPT = 50;
801
+ /** The actions of the split (docs/tui.md, "Splits"). */
802
+ const SPLIT_KEYS = Object.freeze(["split-right", "split-down", "group-next", "tab-move", "group-close"]);
803
+ /** The palette's recency with `id` the most recent: an open, and a tab shown. */
804
+ const recentWith = (state, id) => Object.freeze([id, ...state.recent.filter((each) => each !== id)].slice(0, RECENT_KEPT));
805
+ /** How many terminals the panel holds open at once (lib/panel.mjs MAX_TERMINALS, which a test
806
+ * holds this to). */
807
+ export const TAB_LIMIT = 4;
808
+ const leaderAt = (read, waiting) => Object.freeze({ read: Number.isInteger(read) ? read : null, waiting });
809
+ /** Whether an event came in the same read of input as the leader. */
810
+ const sameRead = (leader, event) => leader.read !== null && event.read === leader.read;
811
+ /** Two effects as one: the dismissal of a confirmation the leader closed, and what it then ran. */
812
+ const both = (a, b) => (a === null ? b : b === null ? a : typeof b === "string" ? b : { ...a, ...b });
813
+
814
+ /** THE LEADER (docs/tui.md, "The leader"): tui.json's open.detachKey, read as `leaderKey` where the
815
+ * TUI reads keys and as `{ back }` from the bytes typed into a terminal (term/through.mjs). It
816
+ * waits, with no timeout, for the key of LEADER's table that follows it IN A LATER READ, so a
817
+ * paste can never run a command: what comes in the leader's own read cancels it and is dropped.
818
+ * The key that follows is one key: the rest of its read is dropped too. A key not in the table
819
+ * cancels the leader and is dropped. Answers the step, or `{ pass }`: the state the event goes on
820
+ * in, when it is not the leader's. */
821
+ function leading(state, event, keymap) {
822
+ const l = state.leader;
823
+ // The leader typed in a terminal: the rest of that read is never the agent's (lib/main.mjs), and
824
+ // when there was a rest (`rest`), it cancelled the leader.
825
+ if (event.back !== undefined) return { state: state.terminal?.focus === "terminal" ? next(state, { leader: leaderAt(event.read, event.rest !== true) }) : state, effect: null };
826
+ if (typeof event.key !== "string" && !("paste" in event)) return { pass: state };
827
+ if (l !== null && sameRead(l, event)) return { state: l.waiting ? next(state, { leader: leaderAt(l.read, false) }) : state, effect: null };
828
+ if (l !== null && l.waiting) {
829
+ const after = next(state, { leader: leaderAt(event.read, false) });
830
+ const does = typeof event.key !== "string" ? undefined : event.key === state.leaderKey ? "list" : LEADER_KEYS.get(event.key);
831
+ return does === undefined ? { state: after, effect: null } : led(after, does, event, keymap);
832
+ }
833
+ const plain = l === null ? state : next(state, { leader: null });
834
+ if (event.key === state.leaderKey) return { state: next(plain, { leader: leaderAt(event.read, true) }), effect: null };
835
+ return { pass: plain };
836
+ }
837
+
838
+ /** Whatever has the focus, settled, so the list has it: the palette closed, a confirmation closed
839
+ * (the loop told), the help and the views of this machine left, a filter field kept as Enter keeps
840
+ * it, the terminal and the detail left. -> { state, effect } */
841
+ function toList(state) {
842
+ let s = state, effect = null;
843
+ if (s.palette !== null) s = next(s, { palette: null });
844
+ if (s.spawn !== null) s = next(s, { spawn: null });
845
+ if (s.view === "act" && s.act !== null) { effect = { dismiss: s.act.n }; s = next(s, { view: "instances", back: "instances", act: null }); }
846
+ if (s.view === "help") s = next(s, { view: s.back });
847
+ // The open field is the shown view's: kept before that view is left (the Souls view's too).
848
+ const field = fieldOf(s);
849
+ if (field) s = field.close(s, field.query(s).trim());
850
+ if (s.view === "souls" || s.view === "capabilities") s = s.open === null ? toSwitcher(next(s, { back: "switcher" })) : next(s, { view: "instances", back: "instances" });
851
+ if (s.terminal?.focus === "terminal") s = terminalWith(s, { focus: "list", zoom: false });
852
+ if (s.view === "instances" && s.focus === "detail") s = next(s, { focus: "list" });
853
+ return { state: s, effect };
854
+ }
855
+
856
+ /** As toList, then the Instances view itself: the switcher, while a workspace is open, closed onto
857
+ * it. Where the terminal commands (open, previous, next, zoom, close) and the acts go, from
858
+ * whatever was shown; with no workspace open the switcher stays. -> { state, effect } */
859
+ function toInstances(state) {
860
+ const settled = toList(state), s = settled.state;
861
+ if (s.view !== "switcher" || s.open === null) return settled;
862
+ return { state: next(s, { view: "instances", back: "instances", switcher: Object.freeze({ ...s.switcher, line: null, refused: null }) }), effect: settled.effect };
863
+ }
864
+
865
+ /** What the leader's key does (LEADER's `does`), from wherever the focus was. From the terminal's
866
+ * focus the acts are the open terminal's instance's and give the focus back when their
867
+ * confirmation closes, zoom zooms it in or out, and the palette gives it back when it is closed;
868
+ * Up and Down go from the open terminal's instance. Every other key first gives the focus to
869
+ * the list, then does what its action does there; the terminal's keys and the acts first go to
870
+ * the Instances view, from any view (toInstances). */
871
+ function led(state, does, event, keymap) {
872
+ const stay = { state, effect: null }, t = state.terminal;
873
+ const inTerminal = t?.focus === "terminal" && state.view === "instances";
874
+ if (does === "list") return toList(state);
875
+ if (does === "palette") return { state: paletteOpened(state, event, inTerminal ? "terminal" : "list"), effect: null };
876
+ if (does === "zoom" || does === "close-terminal") {
877
+ if (t === null) return stay;
878
+ if (does === "zoom" && inTerminal) return { state: terminalWith(state, { zoom: !t.zoom }), effect: null };
879
+ const settledState = toInstances(state);
880
+ if (settledState.state.view !== "instances") return stay;
881
+ // A close from the terminal's focus gives that focus, and the zoom, to the tab shown next
882
+ // (Settled 6 of T2): both are taken before settling, which gives the list the focus.
883
+ const step = terminalKey(settledState.state, does, inTerminal ? "terminal" : "list", inTerminal && t.zoom);
884
+ return { state: step.state, effect: both(settledState.effect, step.effect) };
885
+ }
886
+ // The tabs, from any focus: the one shown next keeps the focus and the zoom it had.
887
+ if (does === "tab-previous" || does === "tab-next") {
888
+ // At either end, or while a tab starts, nothing at all: not even the settling, which would
889
+ // take the focus from the terminal.
890
+ if (tabStepped(state, does === "tab-previous" ? -1 : 1).effect === null) return stay;
891
+ const settledState = toInstances(state);
892
+ if (settledState.state.view !== "instances") return stay;
893
+ const step = tabStepped(settledState.state, does === "tab-previous" ? -1 : 1, { focus: inTerminal ? "terminal" : "list", zoom: inTerminal && t.zoom });
894
+ return { state: step.state, effect: both(settledState.effect, step.effect) };
895
+ }
896
+ // The split's keys, from any focus: nothing at all when they do not apply (splitRefused).
897
+ if (SPLIT_KEYS.includes(does)) {
898
+ const refused = splitRefused(state, does, event.panel, inTerminal);
899
+ if (refused === true) return stay;
900
+ if (refused !== null) return { state: next(state, { outcome: refused }), effect: null };
901
+ const settledState = toInstances(state);
902
+ if (settledState.state.view !== "instances") return stay;
903
+ const step = splitKey(settledState.state, does, inTerminal);
904
+ return { state: step.state, effect: both(settledState.effect, step.effect) };
905
+ }
906
+ if (does === "previous" || does === "next") return stepped(state, does === "previous" ? -1 : 1, event);
907
+ // Another of the open terminal's soul, from its focus; from anywhere else, of the selection's.
908
+ // The Souls view's selected soul is named before the list is shown, which leaves that view.
909
+ if (does === "spawn" || does === "spawn-another") {
910
+ const target = spawnTarget(state, inTerminal ? t.id : state.selected);
911
+ const settledState = toList(state);
912
+ const step = spawnAsked(settledState.state, event, does, target);
913
+ return { state: step.state, effect: both(settledState.effect, step.effect) };
914
+ }
915
+ if (does === "stop" || does === "retire" || does === "start" || does === "restart") {
916
+ const id = inTerminal ? t.id : state.selected;
917
+ const row = id === null ? null : roster(state).instances.find((each) => instanceId(each) === id) ?? null;
918
+ if (row === null || state.open === null) return stay;
919
+ const settledState = toInstances(state);
920
+ const step = actOn(settledState.state, row, does, inTerminal ? "terminal" : null);
921
+ return { state: step.state, effect: both(settledState.effect, step.effect) };
922
+ }
923
+ const settledState = toList(state);
924
+ const { key, text, ...rest } = event;
925
+ const step = reduced(settledState.state, { ...rest, action: does }, keymap);
926
+ return { state: step.state, effect: both(settledState.effect, step.effect) };
927
+ }
928
+
929
+ /** The leader's Up and Down: the instance before or after the open terminal's (or the selection's,
930
+ * with none open) in the list as it is drawn, passing over the rows that cannot be opened, is
931
+ * selected and opened with the focus in it, in the Instances view from whatever was shown (a
932
+ * confirmation is closed, the loop told). At either end of the list nothing moves, and nothing
933
+ * is left. */
934
+ function stepped(state, step, event) {
935
+ const stay = { state, effect: null };
936
+ if (state.opening !== null || state.open === null) return stay;
937
+ const settled = toInstances(state), s = settled.state;
938
+ if (s.view !== "instances") return stay;
939
+ const page = Math.max(1, Number.isInteger(event.page) ? event.page : 1);
940
+ const r = roster(s, undefined, Number.isInteger(event.cols) ? event.cols : undefined);
941
+ const from = indexOf(r, s.terminal !== null && r.index.has(s.terminal.id) ? s.terminal.id : s.selected);
942
+ if (from < 0) return stay;
943
+ for (let i = from + step; i >= 0 && i < r.items.length; i += step) {
944
+ const item = r.items[i];
945
+ if (!isRow(item) || !openDecision(s, item.row, instanceActs(item.row)).open) continue;
946
+ const opened = openAgent(selectAt(s, r, i, page, step), item.row);
947
+ return { state: opened.state, effect: both(settled.effect, opened.effect) };
948
+ }
949
+ return stay;
950
+ }
951
+
952
+ /** THE PALETTE (docs/tui.md, "The palette"), opened: one input over the rows lib/model.mjs
953
+ * paletteItems lists. `read` is the read of input that opened it: a press of Enter in that same
954
+ * read runs nothing (a paste cannot open it and run a row). `from`: "terminal" when it was opened
955
+ * from the terminal's focus, which closing it gives back. While it is open the TUI reads keys,
956
+ * so the terminal does not have the focus. */
957
+ function paletteOpened(state, event, from) {
958
+ const palette = Object.freeze({ query: "", selected: null, top: 0, read: Number.isInteger(event.read) ? event.read : null, from });
959
+ const t = state.terminal;
960
+ return next(state, { palette, ...(t?.focus === "terminal" ? { terminal: Object.freeze({ ...t, focus: "list", zoom: false }) } : {}) });
961
+ }
962
+ /** The palette closed: the focus goes back to the terminal it came from, while that is open. */
963
+ function paletteClosed(state) {
964
+ const shut = next(state, { palette: null }), t = shut.terminal;
965
+ return state.palette.from === "terminal" && t !== null && shut.view === "instances" ? terminalWith(shut, { focus: "terminal" }) : shut;
966
+ }
967
+ /** The keys that move the palette's selection: named keys only, so every letter is the query's. */
968
+ const PALETTE_MOVES = Object.freeze({ up: "up", down: "down", pageup: "page-up", pagedown: "page-down" });
969
+ /** A key or a paste while the palette is open. Text and a paste's first line go to the query,
970
+ * Backspace takes a grapheme off it, Up and Down (and PageUp, PageDown) move among its rows,
971
+ * Enter runs the selected row, Esc (or its own key again) closes it; quit, suspend and redraw keep
972
+ * their actions. Every other key does nothing. */
973
+ function inPalette(state, event, keymap) {
974
+ const p = state.palette, stay = { state, effect: null };
975
+ const put = (changes) => next(state, { palette: Object.freeze({ ...p, ...changes }) });
976
+ const query = (text) => (text === p.query ? stay : { state: put({ query: text, selected: null, top: 0 }), effect: null });
977
+ if ("paste" in event) return typeof event.paste === "string" ? query(typed(p.query, event.paste.split(LINE_END)[0])) : stay;
978
+ if (typeof event.text === "string") return query(typed(p.query, event.text, { key: true }));
979
+ const action = keymap.get(event.key);
980
+ if (event.key === "backspace") return query([...GRAPHEMES.segment(p.query)].map((g) => g.segment).slice(0, -1).join(""));
981
+ if (event.key === "escape" || action === "close" || action === "palette") return { state: paletteClosed(state), effect: null };
982
+ if (action === "quit" || action === "suspend" || action === "redraw") return { state, effect: action };
983
+ const list = paletteItems(state);
984
+ const keys = list.items.map((item) => item.key);
985
+ if (Object.hasOwn(PALETTE_MOVES, event.key)) {
986
+ if (!keys.length) return stay;
987
+ const page = Math.max(1, (Number.isInteger(event.page) ? event.page : 1) - 1);
988
+ const from = Math.max(0, keys.indexOf(list.selected));
989
+ const to = Math.min(Math.max(0, moved(PALETTE_MOVES[event.key], from, keys.length, page)), keys.length - 1);
990
+ return { state: put({ selected: keys[to] }), effect: null };
991
+ }
992
+ if (event.key !== "enter") return stay;
993
+ if (p.read !== null && event.read === p.read) return stay;
994
+ const item = list.items.find((each) => each.key === list.selected);
995
+ return item ? ranFromPalette(state, item, event, keymap) : stay;
996
+ }
997
+ /** A palette row run, what was open under the palette settled first as the leader settles it (a
998
+ * filter field kept, a confirmation closed, the loop told): an instance is opened (its terminal
999
+ * swapped into the panel) and an act opens its confirmation on the palette's instance, both in
1000
+ * the Instances view whatever was shown (toInstances); a view or a command does what its action
1001
+ * does from the list (toList). */
1002
+ function ranFromPalette(state, item, event, keymap) {
1003
+ const from = state.palette.from;
1004
+ const settled = item.kind === "instance" || item.kind === "act" ? toInstances(state) : toList(state), shut = settled.state;
1005
+ const then = (step) => ({ state: step.state, effect: both(settled.effect, step.effect) });
1006
+ // A soul: the Souls view, with it selected. A kept filter of the view that hides it is cleared:
1007
+ // the soul chosen is the one shown, and the one `i` acts on.
1008
+ if (item.kind === "soul") {
1009
+ const step = soulsShown(shut), chosen = soulsWith(step.state, { selected: item.name, loose: false, detailTop: 0 });
1010
+ const shown = soulsOf(chosen).selected?.name === item.name ? chosen : soulsWith(chosen, { filter: Object.freeze({ editing: false, query: "" }), top: 0 });
1011
+ return then({ state: shown, effect: step.effect });
1012
+ }
1013
+ if (item.kind === "instance" || item.kind === "act") {
1014
+ const row = shut.view === "instances" ? roster(shut).instances.find((each) => instanceId(each) === item.id) : undefined;
1015
+ if (!row) return settled;
1016
+ if (item.does === "spawn-another") return then(spawnAsked(shut, event, item.does, { id: item.id }));
1017
+ if (item.kind === "act") return then(actOn(shut, row, item.does, from === "terminal" ? "terminal" : null));
1018
+ const r = roster(shut, undefined, Number.isInteger(event.cols) ? event.cols : undefined);
1019
+ const page = Math.max(1, Number.isInteger(event.page) ? event.page : 1);
1020
+ const at = indexOf(r, item.id);
1021
+ return then(openAgent(at < 0 ? shut : selectAt(shut, r, at, page), row));
1022
+ }
1023
+ const { key, text, ...rest } = event;
1024
+ return then(reduced(shut, { ...rest, action: item.does }, keymap));
1025
+ }
1026
+
482
1027
  function reduced(state, event, keymap) {
1028
+ const lead = leading(state, event, keymap);
1029
+ if (lead.pass === undefined) return lead;
1030
+ state = lead.pass;
483
1031
  const stay = { state, effect: null };
484
1032
  if (event.acted !== undefined) return acted(state, event.acted);
485
1033
  if (event.prepared !== undefined) return prepared(state, event.prepared);
486
1034
  if (event.given !== undefined) return state.opening?.phase === "preflight" ? { state: next(state, { opening: null }), effect: null } : stay;
487
1035
  if (event.returned !== undefined) return returned(state, event.returned);
488
- if (event.shown !== undefined) return state.terminal?.id === event.shown.id ? { state: terminalWith(state, { status: "open" }), effect: null } : stay;
489
- if (event.back !== undefined) return state.terminal?.focus === "terminal" ? { state: terminalWith(state, { focus: "list", zoom: false }), effect: null } : stay;
1036
+ if (event.shown !== undefined) return state.tabs.some((tab) => tab.id === event.shown.id) ? { state: tabWith(state, event.shown.id, { status: "open" }), effect: null } : stay;
1037
+ // A hidden tab's agent wrote (the panel says so once per hidden spell): its mark.
1038
+ if (event.activity !== undefined) return state.terminal?.id !== event.activity.id && state.tabs.some((tab) => tab.id === event.activity.id && !tab.activity) ? { state: tabWith(state, event.activity.id, { activity: true }), effect: null } : stay;
490
1039
  if (event.entry !== undefined) return took(state, event);
491
1040
  if (event.roster !== undefined) return heard(state, event.roster);
492
1041
  if (event.collecting !== undefined) return { state: event.collecting === state.collecting ? state : next(state, { collecting: event.collecting === true }), effect: null };
1042
+ // The rows stay where they are: only what they read changes.
1043
+ if (event.retiring !== undefined) return { state: next(state, { retiring: new Set(event.retiring) }), effect: null };
493
1044
  if (event.offered !== undefined) return { state: next(state, { offered: Object.freeze({ offered: Object.freeze([...event.offered.offered]), limited: event.offered.limited === true }) }), effect: null };
494
1045
  if (event.admitted !== undefined) return { state: admitted(state, event), effect: { refresh: { live: true } } };
495
1046
  if (event.refused !== undefined) return { state: next(state, { switcher: Object.freeze({ ...state.switcher, refused: event.refused }) }), effect: null };
496
- const field = fieldOf(state);
1047
+ if (event.souls !== undefined) return soulsHeard(state, event.souls);
1048
+ if (event.spawnRead !== undefined) return spawnRead(state, event.spawnRead);
1049
+ if (event.spawnDrawn !== undefined) return spawnDrawn(state, event.spawnDrawn);
1050
+ if (event.spawnProgress !== undefined) return { state: state.spawning?.phase === "submitting" ? next(state, { spawning: Object.freeze({ ...state.spawning, phase: "spawning" }) }) : state, effect: null };
1051
+ if (event.spawnDone !== undefined) return spawnDone(state, event.spawnDone);
1052
+ // An action the leader or the palette runs comes as `{ action }`, with no key: whatever field or
1053
+ // confirmation was open has been settled first.
1054
+ const given = event.action !== undefined;
1055
+ if (!given && state.palette !== null) return inPalette(state, event, keymap);
1056
+ if (!given && state.spawn !== null) return inSpawn(state, event, keymap);
1057
+ const field = given ? null : fieldOf(state);
497
1058
  // A paste goes only into an open filter field: its first line. Anywhere else it is dropped whole.
498
1059
  if ("paste" in event) return field && typeof event.paste === "string" ? { state: field.put(state, typed(field.query(state), event.paste.split(LINE_END)[0])), effect: null } : stay;
499
- if (typeof event.key !== "string") return stay;
500
- const action = keymap.get(event.key);
1060
+ if (typeof event.key !== "string" && !given) return stay;
1061
+ const action = given ? event.action : keymap.get(event.key);
501
1062
  if (field) return edited(state, field, event, action);
502
1063
  if (state.view === "act" && state.act !== null) return inAct(state, event, action);
503
1064
  const page = Math.max(1, Number.isInteger(event.page) ? event.page : 1);
@@ -512,11 +1073,25 @@ function reduced(state, event, keymap) {
512
1073
  switch (action) {
513
1074
  case "quit": case "suspend": case "redraw": return { state, effect: action };
514
1075
  // In the switcher the folders of ~/Agents are listed again too.
515
- case "refresh": return { state, effect: { refresh: { live: true }, ...((state.view === "help" ? state.back : state.view) === "switcher" ? { offer: true } : {}) } };
1076
+ // In the Souls view it reads the souls again, and nothing else.
1077
+ case "refresh": return state.view === "souls" ? inSouls(state, action, event, page, scrolled) : { state, effect: { refresh: { live: true }, ...((state.view === "help" ? state.back : state.view) === "switcher" ? { offer: true } : {}) } };
516
1078
  case "help": return { state: next(state, state.view === "help" ? { view: state.back } : { view: "help", back: state.view, helpTop: 0 }), effect: null };
517
1079
  case "workspaces": return state.view === "switcher" ? stay : { state: toSwitcher(next(state, { back: "switcher" })), effect: { offer: true } };
1080
+ case "palette": return { state: paletteOpened(state, event, "list"), effect: null };
1081
+ // Souls and Capabilities are views of this machine, whatever workspace is open, or none.
1082
+ case "souls": return soulsShown(state);
1083
+ case "capabilities": return { state: state.view === action ? state : next(state, { view: action, back: action }), effect: null };
1084
+ // A spawn starts from the list of instances or the Souls view (the leader reaches them from anywhere).
1085
+ case "spawn": case "spawn-another": return state.view === "instances" || state.view === "souls" ? spawnAsked(state, event, action, spawnTarget(state)) : stay;
1086
+ case "spawn-check": return spawnChecked(state);
518
1087
  default:
519
1088
  }
1089
+ if (state.view === "souls") return inSouls(state, action, event, page, scrolled);
1090
+ if (state.view === "capabilities") {
1091
+ // Esc and 1 go back to the instances, or to the switcher when no workspace is open.
1092
+ if (action !== "close" && action !== "instances") return stay;
1093
+ return { state: state.open === null ? toSwitcher(next(state, { back: "switcher" })) : next(state, { view: "instances", back: "instances" }), effect: null };
1094
+ }
520
1095
  if (state.view === "help") {
521
1096
  if (action === "close") return { state: next(state, { view: state.back }), effect: null };
522
1097
  if (action === "instances") return state.open === null ? stay : { state: next(state, { view: "instances", back: "instances" }), effect: null };
@@ -527,18 +1102,22 @@ function reduced(state, event, keymap) {
527
1102
  if (action === "close") {
528
1103
  // In this order: an open under way (another machine is asked first), a kept filter, the detail.
529
1104
  if (state.opening?.phase === "preflight") return { state: next(state, { opening: null }), effect: { abandon: true } };
530
- if (state.filter.query !== "") return { state: queried(state, ""), effect: null };
1105
+ if (state.filter.query !== "" || state.filter.soul) return { state: rehomed(roster(state), next(state, { filter: NO_FILTER, top: 0, loose: false })), effect: null };
531
1106
  return state.focus === "detail" ? { state: next(state, { focus: "list" }), effect: null } : stay;
532
1107
  }
533
1108
  const r = roster(state, undefined, Number.isInteger(event.cols) ? event.cols : undefined);
534
1109
  const at = indexOf(r, state.selected);
535
1110
  switch (action) {
536
- case "filter": return { state: next(state, { focus: "list", filter: Object.freeze({ ...state.filter, editing: true }) }), effect: null };
537
- case "open": return openAgent(state, r, at);
1111
+ // A soul filter gives way to the text one.
1112
+ case "filter": return { state: rehomed(roster(state), next(state, { focus: "list", filter: Object.freeze({ editing: true, query: state.filter.query }) })), effect: null };
1113
+ case "open": return at < 0 ? stay : openAgent(state, r.items[at].row);
538
1114
  case "zoom": case "close-terminal": return terminalKey(state, action);
539
- // The views not built yet: the line says what to run instead.
540
- case "souls": case "capabilities": return { state: next(state, { outcome: NOT_BUILT[action] }), effect: null };
541
- case "stop": case "retire": case "start": case "restart": return actOn(state, r, at, action);
1115
+ case "tab-previous": case "tab-next": return tabStepped(state, action === "tab-previous" ? -1 : 1);
1116
+ case "split-right": case "split-down": case "group-next": case "tab-move": case "group-close": {
1117
+ const refused = splitRefused(state, action, event.panel);
1118
+ return refused === true ? { state, effect: null } : refused !== null ? { state: next(state, { outcome: refused }), effect: null } : splitKey(state, action, false);
1119
+ }
1120
+ case "stop": case "retire": case "start": case "restart": return at < 0 ? stay : actOn(state, r.items[at].row, action);
542
1121
  case "detail": return at < 0 ? stay : { state: next(state, { focus: state.focus === "detail" ? "list" : "detail" }), effect: null };
543
1122
  case "up": case "down": case "top": case "bottom": case "page-up": case "page-down": {
544
1123
  if (state.focus === "detail") return { state: next(state, { detailTop: scrolled(state.detailTop) }), effect: null };
@@ -570,3 +1149,267 @@ function reduced(state, event, keymap) {
570
1149
  default: return stay;
571
1150
  }
572
1151
  }
1152
+
1153
+ // ── SPAWNING (docs/tui.md, "Spawning an agent"; Spec 6-spawn) ───────────────────────────────────
1154
+
1155
+ /** The longest name the name field takes: the kernel's instance-name limit (spawn-preview-contract
1156
+ * INSTANCE_NAME_MAX). The preview says when the soul's name and the dash leave less room. */
1157
+ const NAME_LIMIT = 64;
1158
+ /** What the name field takes as typed: the characters an instance name is made of. */
1159
+ const NAME_TEXT = /^[A-Za-z0-9-]+$/;
1160
+ /** The prompt with what changes of it. */
1161
+ const spawnWith = (state, changes) => next(state, { spawn: Object.freeze({ ...state.spawn, ...changes }) });
1162
+ /** A line of its own, and nothing else. */
1163
+ const said = (state, parts) => ({ state: next(state, { outcome: { said: parts, under: [] } }), effect: null });
1164
+ const remoteRow = (row) => typeof row?.server === "string" && row.server !== "";
1165
+ /** The parent a prompt can offer ("child of"): the selected instance of this workspace when it
1166
+ * opened, as the shared relation anchors it. */
1167
+ const anchorOf = (row) => (row && !remoteRow(row) ? Object.freeze({ id: instanceId(row), instance: row.instance, agent: row.agent, agentsRoot: row.agentsRoot }) : null);
1168
+
1169
+ /** What n and N are of, named in the view they were pressed in: the Souls view's selected soul
1170
+ * (`{ souls: row|null }`), else instance `id` (the selection's, or the open terminal's). */
1171
+ function spawnTarget(state, id = state.selected) {
1172
+ if ((state.view === "help" ? state.back : state.view) === "souls") return { souls: soulsOf(state).selected };
1173
+ return { id };
1174
+ }
1175
+
1176
+ /** n, N, the leader's n and N, and the palette's two rows (docs/tui.md, "Spawning an agent").
1177
+ * One spawn at a time: while one is under way the line says so and nothing opens. Only this
1178
+ * machine's workspace is offered: on another machine's workspace or row the line says so.
1179
+ * n opens the soul picker, and N the preview of the soul of instance `target.id` (the selection's,
1180
+ * or the open terminal's from its focus); from the Souls view (`target.souls`) both start from
1181
+ * its selected soul, at the preview. The catalog is wanted from now on (settled for the open
1182
+ * workspace, as the Souls view settles it). `read`: the read of input the prompt opened in, whose
1183
+ * Enter does nothing. */
1184
+ function spawnAsked(state, event, verb, target) {
1185
+ const stay = { state, effect: null };
1186
+ if (state.open === null) return stay;
1187
+ if (state.spawning !== null) return said(state, SPAWN_WORDS.busy(state.spawning.name));
1188
+ if (!state.ctxs.includes(state.open)) return said(state, SPAWN_WORDS.remote());
1189
+ const fromSouls = Object.hasOwn(target, "souls"), id = fromSouls ? null : target.id;
1190
+ const row = state.view === "instances" && id !== null ? roster(state).instances.find((each) => instanceId(each) === id) ?? null : null;
1191
+ // Settled 9: on another machine's row, neither n nor N opens anything of this one.
1192
+ if (row !== null && remoteRow(row)) return said(state, SPAWN_WORDS.remote());
1193
+ let soul = null, wanted = null;
1194
+ if (fromSouls) {
1195
+ if (target.souls) soul = Object.freeze({ name: target.souls.name, agentsRoot: target.souls.agentsRoot });
1196
+ } else if (verb === "spawn-another") {
1197
+ if (row === null) return stay;
1198
+ wanted = row.agent;
1199
+ }
1200
+ const preview = soul !== null || wanted !== null;
1201
+ const prompt = Object.freeze({
1202
+ workspace: state.open, step: preview ? "preview" : "picker", read: Number.isInteger(event.read) ? event.read : null,
1203
+ back: preview && (verb === "spawn-another" || fromSouls) ? "list" : "picker",
1204
+ query: "", selected: null, soul, wanted, anchor: anchorOf(row),
1205
+ name: "", nameRead: "", child: false, focus: "spawn", folds: Object.freeze([]), top: 0,
1206
+ n: 0, asked: null, status: preview ? "souls" : null, data: null, reason: null, shownIn: null, readKey: null, problem: null,
1207
+ });
1208
+ const opened = soulsWith(next(state, { spawn: prompt, outcome: null }), { wanted: true });
1209
+ const step = preview ? (soul ? previewAsked(opened) : soulFound(opened)) : { state: opened, effect: null };
1210
+ return { state: step.state, effect: both({ souls: "settle" }, step.effect) };
1211
+ }
1212
+
1213
+ /** A preview read asked of the loop (`spawnPreview`), numbered in the run (`previews`), not in the
1214
+ * prompt: only the answer to the last one is taken, and never one asked by a prompt closed since.
1215
+ * What was on screen stays while it is read, as stale, and Spawn is not armed until the answer
1216
+ * is drawn (`spawnDrawn`). */
1217
+ function previewAsked(state) {
1218
+ const p = state.spawn, n = state.previews + 1;
1219
+ const request = { action: "preview", selector: spawnSelector(p), choices: spawnChoices(p) };
1220
+ return { state: spawnWith(next(state, { previews: n }), { n, asked: spawnChoicesKey(p), nameRead: p.name, status: "reading", shownIn: null }), effect: { spawnPreview: { n, workspace: p.workspace, request } } };
1221
+ }
1222
+
1223
+ /** N's soul, found in the workspace's catalog once it is held: the preview is read for it. A
1224
+ * catalog that does not list it says so, and there is nothing to read or to spawn. */
1225
+ function soulFound(state) {
1226
+ const p = state.spawn, found = soulOfAgent(state, p.workspace, p.wanted);
1227
+ if (found) return previewAsked(spawnWith(state, { soul: Object.freeze({ name: found.name, agentsRoot: found.agentsRoot }) }));
1228
+ const held = state.souls.held.get(p.workspace)?.entry ?? null;
1229
+ if (!Array.isArray(held?.souls)) return { state, effect: null }; // still read
1230
+ return { state: spawnWith(state, { status: "failed", reason: null, problem: { said: SPAWN_WORDS.noSoul(p.wanted), under: [] } }), effect: null };
1231
+ }
1232
+
1233
+ /** The preview's answer (`{ n, answer }`): taken only for the last read asked. One the workspace
1234
+ * moved under is read again at once, as its shared words say. An answer taken is not yet seen:
1235
+ * Spawn is armed only once a frame that shows it ready is written (`spawnDrawn`). */
1236
+ function spawnRead(state, { n, answer }) {
1237
+ const p = state.spawn;
1238
+ if (p === null || p.step !== "preview" || p.n !== n) return { state, effect: null };
1239
+ if (answer?.status === "available") return { state: spawnWith(state, { status: "shown", data: answer.data, reason: null, readKey: p.asked, shownIn: null }), effect: null };
1240
+ if (answer?.reason?.code === "E_TARGET_CHANGED") return previewAsked(state);
1241
+ return { state: spawnWith(state, { status: "failed", reason: answer?.reason ?? null, readKey: null }), effect: null };
1242
+ }
1243
+
1244
+ /** A frame was written that shows preview `n` ready, its Spawn button on the screen
1245
+ * (`{ n, read }`, `read` the number of the last read of input before that frame): the paste guard
1246
+ * (inSpawn) takes Enter on Spawn only from a later read. Kept from the first such frame. */
1247
+ function spawnDrawn(state, { n, read }) {
1248
+ const p = state.spawn;
1249
+ if (p === null || p.step !== "preview" || p.n !== n || p.shownIn !== null || !spawnReady(p) || !Number.isInteger(read)) return { state, effect: null };
1250
+ return { state: spawnWith(state, { shownIn: read }), effect: null };
1251
+ }
1252
+
1253
+ /** The name field's text left as it is now: when it is not what the preview was read with, the
1254
+ * preview is read again. A changed choice puts away what an earlier spawn's outcome said. */
1255
+ function nameKept(state) {
1256
+ const p = state.spawn;
1257
+ if (p.name === p.nameRead) return { state, effect: null };
1258
+ return previewAsked(spawnWith(state, { nameRead: p.name, problem: null }));
1259
+ }
1260
+
1261
+ /** A key or a paste while the prompt is open.
1262
+ * THE PICKER, as the palette: text and a paste's first line go to the query, Backspace takes a
1263
+ * grapheme off it, Up and Down (PageUp, PageDown) move, Enter picks the selected soul (one whose
1264
+ * spawn would be refused is not picked), Esc closes the prompt.
1265
+ * THE PREVIEW (Settled 1): one focus ring, Spawn, the name, child of, each fold; Tab and Shift+Tab
1266
+ * move along it. Enter does what the focus says: spawns, keeps the name and reads the preview
1267
+ * again, toggles the parent, opens or closes a fold. On the name, text and a paste's first line
1268
+ * are the name's (the characters of an instance name only), and Esc puts back the name the
1269
+ * preview was read with; Esc elsewhere gives the focus to Spawn, and on Spawn backs out (to the
1270
+ * picker, or to the list for N and from the Souls view). The movement keys scroll it.
1271
+ * quit, suspend and redraw keep their actions where no text is typed.
1272
+ * THE PASTE GUARD (Settled 2): Enter in the read of input the prompt opened in does nothing, and
1273
+ * Enter on Spawn spawns only the preview read for the choices on screen, from a read of input
1274
+ * later than the one in which that answer landed: a pasted `n…⏎⏎` stops at the preview. */
1275
+ function inSpawn(state, event, keymap) {
1276
+ const p = state.spawn, stay = { state, effect: null };
1277
+ const action = typeof event.key === "string" ? keymap.get(event.key) : undefined;
1278
+ const sameRead = p.read !== null && event.read === p.read;
1279
+ if (p.step === "picker") {
1280
+ const query = (text) => (text === p.query ? stay : { state: spawnWith(state, { query: text, selected: null }), effect: null });
1281
+ if ("paste" in event) return typeof event.paste === "string" ? query(typed(p.query, event.paste.split(LINE_END)[0])) : stay;
1282
+ if (typeof event.text === "string") return query(typed(p.query, event.text, { key: true }));
1283
+ if (event.key === "backspace") return query([...GRAPHEMES.segment(p.query)].map((g) => g.segment).slice(0, -1).join(""));
1284
+ if (event.key === "escape" || action === "close") return { state: next(state, { spawn: null }), effect: null };
1285
+ if (action === "quit" || action === "suspend" || action === "redraw") return { state, effect: action };
1286
+ const list = spawnPickerItems(state), names = list.items.map((item) => item.name);
1287
+ if (Object.hasOwn(PALETTE_MOVES, event.key)) {
1288
+ if (!names.length) return stay;
1289
+ const page = Math.max(1, (Number.isInteger(event.page) ? event.page : 1) - 2);
1290
+ const from = Math.max(0, names.indexOf(list.selected));
1291
+ return { state: spawnWith(state, { selected: names[Math.min(Math.max(0, moved(PALETTE_MOVES[event.key], from, names.length, page)), names.length - 1)] }), effect: null };
1292
+ }
1293
+ if (event.key !== "enter" || sameRead) return stay;
1294
+ const item = list.items.find((each) => each.name === list.selected);
1295
+ if (!item || item.refused) return stay;
1296
+ return previewAsked(spawnWith(state, { step: "preview", selected: item.name, soul: Object.freeze({ name: item.row.name, agentsRoot: item.row.agentsRoot }), focus: "spawn", folds: Object.freeze([]), top: 0, data: null, reason: null, shownIn: null, readKey: null, problem: null }));
1297
+ }
1298
+ const ring = spawnRing(p);
1299
+ const focus = ring.includes(p.focus) ? p.focus : "spawn";
1300
+ const moveFocus = (by) => { const to = ring[(ring.indexOf(focus) + by + ring.length) % ring.length]; return to === focus ? state : spawnWith(state, { focus: to }); };
1301
+ if (focus === "name") {
1302
+ const name = (text) => (text === p.name ? stay : { state: spawnWith(state, { name: text }), effect: null });
1303
+ const fits = (text) => text !== "" && NAME_TEXT.test(text) && p.name.length + text.length <= NAME_LIMIT;
1304
+ if ("paste" in event) { const line = typeof event.paste === "string" ? event.paste.split(LINE_END)[0] : ""; return fits(line) ? name(p.name + line) : stay; }
1305
+ if (typeof event.text === "string") return fits(event.text) ? name(p.name + event.text) : stay;
1306
+ if (event.key === "backspace") return name(p.name.slice(0, -1));
1307
+ if (action === "quit" || action === "suspend" || action === "redraw") return { state, effect: action };
1308
+ if (event.key === "escape") return { state: spawnWith(state, { name: p.nameRead, focus: "spawn" }), effect: null };
1309
+ if (event.key === "enter") return nameKept(spawnWith(state, { focus: "spawn" }));
1310
+ if (event.key === "tab" || event.key === "shift+tab") return nameKept(moveFocus(event.key === "tab" ? 1 : -1));
1311
+ return stay;
1312
+ }
1313
+ if ("paste" in event) return stay;
1314
+ if (event.key === "tab" || event.key === "shift+tab") return { state: moveFocus(event.key === "tab" ? 1 : -1), effect: null };
1315
+ if (event.key === "escape" || action === "close") {
1316
+ if (focus !== "spawn") return { state: spawnWith(state, { focus: "spawn" }), effect: null };
1317
+ return { state: p.back === "picker" ? spawnWith(state, { step: "picker", problem: null, status: null, data: null, readKey: null }) : next(state, { spawn: null }), effect: null };
1318
+ }
1319
+ if (action === "quit" || action === "suspend" || action === "redraw") return { state, effect: action };
1320
+ if (MOVES.includes(action)) {
1321
+ const count = event.extent ?? 0, height = event.room ?? 1;
1322
+ const from = windowOf({ top: p.top, count, height }).top;
1323
+ return { state: spawnWith(state, { top: windowOf({ top: moved(action, from, count, height), count, height }).top }), effect: null };
1324
+ }
1325
+ if (event.key !== "enter" || sameRead) return stay;
1326
+ if (focus === "child") return previewAsked(spawnWith(state, { child: !p.child, problem: null }));
1327
+ if (focus.startsWith("fold:")) {
1328
+ const key = focus.slice("fold:".length);
1329
+ return { state: spawnWith(state, { folds: Object.freeze(p.folds.includes(key) ? p.folds.filter((each) => each !== key) : [...p.folds, key]) }), effect: null };
1330
+ }
1331
+ if (p.status === "failed") return p.soul === null ? stay : previewAsked(state);
1332
+ if (!spawnReady(p) || p.shownIn === null || !Number.isInteger(event.read) || event.read <= p.shownIn) return stay;
1333
+ return spawnPressed(state);
1334
+ }
1335
+
1336
+ /** Enter on Spawn, the preview ready: the prompt closes, and the loop is asked to spawn it
1337
+ * (`spawn`): the prepare body the TUI builds (Settled 4), and the decision on screen, which is
1338
+ * the only one applied. The line says what is under way until its outcome. */
1339
+ function spawnPressed(state) {
1340
+ const p = state.spawn, selector = spawnSelector(p), choices = spawnChoices(p);
1341
+ // The kernel's name for it (a purpose typed is put after the soul's name), for the lines that follow.
1342
+ const name = p.data.instance || p.name || p.soul.name;
1343
+ const spawning = Object.freeze({ name, soul: p.soul.name, workspace: p.workspace, phase: "submitting", prompt: p });
1344
+ const spawn = { workspace: p.workspace, selector, input: { action: "prepare", selector, choices, task: "" }, decision: structuredClone(p.data.decision), name };
1345
+ return { state: next(state, { spawn: null, spawning, spawnCheck: null, outcome: null }), effect: { spawn } };
1346
+ }
1347
+
1348
+ /** C, while a check of an outcome not known is offered: the loop reads its result once
1349
+ * (`spawnCheck`); an unknown result applies the same reference again, never a new one. */
1350
+ function spawnChecked(state) {
1351
+ const c = state.spawnCheck;
1352
+ if (c === null || state.spawning !== null) return { state, effect: null };
1353
+ return { state: next(state, { spawnCheck: null, spawning: Object.freeze({ name: c.name, soul: c.soul, workspace: c.workspace, phase: "checking", prompt: c.prompt }), outcome: null }), effect: { spawnCheck: true } };
1354
+ }
1355
+
1356
+ /** Whether the person is busy elsewhere: an outcome then says what to do, and nothing opens over
1357
+ * what they are doing. */
1358
+ const free = (state) => state.palette === null && state.spawn === null && state.act === null && state.opening === null && (state.view === "instances" || state.view === "souls");
1359
+
1360
+ /** A spawn's outcome (`{ kind, view, reason, instance, home }`, the shared transaction's, with the
1361
+ * instance it is of), as Done 5 says each:
1362
+ * created, complete and launched: the instances are read at once, and the new row is waited
1363
+ * for (`arriving`, see `arrived`); its terminal opens with the focus;
1364
+ * created otherwise: the shared words, and nothing opens;
1365
+ * unknown, pending-expired, cleanup-owed: the shared words; a check is offered where they name one;
1366
+ * drifted, refused, rolled-back, never-submitted: the shared words, and the preview again (read
1367
+ * again, with the choices as they were), unless the person is busy elsewhere. */
1368
+ function spawnDone(state, { kind, view = null, reason = null, instance = null, home = null }) {
1369
+ const s = state.spawning;
1370
+ if (s === null) return { state, effect: null };
1371
+ const name = instance ?? s.name, settled = next(state, { spawning: null });
1372
+ const words = kind === "unknown" || kind === "refused" ? spawnProblem(reason, "spawn") : outcomeWords(kind, view, name);
1373
+ const line = spawnLine(words, name, state.actions);
1374
+ const refresh = { refresh: { live: true } };
1375
+ if (kind === "created") {
1376
+ const launched = view?.status === "complete" && view.receipt?.launched !== false;
1377
+ const arriving = launched ? Object.freeze({ workspace: s.workspace, instance: name, home, agentsRoot: s.prompt.soul.agentsRoot, agent: view.receipt?.agent ?? s.soul, reads: 0, words }) : null;
1378
+ return { state: next(settled, { arriving, outcome: launched ? null : line }), effect: refresh };
1379
+ }
1380
+ if (["unknown", "pending-expired", "cleanup-owed"].includes(kind)) {
1381
+ const spawnCheck = words?.next === "check-result" ? Object.freeze({ name, soul: s.soul, workspace: s.workspace, prompt: s.prompt }) : null;
1382
+ return { state: next(settled, { spawnCheck, outcome: line }), effect: refresh };
1383
+ }
1384
+ if (!free(settled) || !settled.ctxs.includes(s.workspace) || settled.open !== s.workspace) return { state: next(settled, { outcome: line }), effect: refresh };
1385
+ const back = next(settled, { spawn: Object.freeze({ ...s.prompt, read: null, focus: "spawn", problem: line, data: null, readKey: null, shownIn: null }) });
1386
+ const step = previewAsked(back);
1387
+ return { state: step.state, effect: both(refresh, step.effect) };
1388
+ }
1389
+
1390
+ /** A read of the workspace a spawn created an instance in (Settled 5): when its row is there and
1391
+ * can be opened, it is selected and its terminal opened with the focus, in the Instances view, as
1392
+ * the palette's open does (a filter that hides it is cleared). Not yet, after two reads: the line
1393
+ * says so. The person busy elsewhere, or another workspace open: the line says it was created. */
1394
+ function arrived(state) {
1395
+ const a = state.arriving, row = spawnedRow(state, a);
1396
+ if (row && openDecision(state, row, instanceActs(row)).open) {
1397
+ const done = next(state, { arriving: null });
1398
+ if (!free(done) || done.open !== a.workspace) return { state: next(done, { outcome: spawnLine({ ...a.words, next: a.words?.next ?? "open-from-list" }, a.instance, state.actions) }), effect: null };
1399
+ const settledState = toInstances(done), id = instanceId(row);
1400
+ // Every tab taken (Settled 7 of T2): the created line, then the cap's; nothing opens.
1401
+ if (!done.tabs.some((tab) => tab.id === id) && done.tabs.length >= TAB_LIMIT) {
1402
+ const created = spawnLine({ ...a.words, next: null }, a.instance, state.actions), full = fullLine(done);
1403
+ const said = created?.said.length ? [...created.said, { own: " " }, ...full.said] : full.said;
1404
+ return { state: next(done, { outcome: Object.freeze({ said: Object.freeze(said), under: created?.under ?? [] }) }), effect: null };
1405
+ }
1406
+ let s = settledState.state;
1407
+ if (!roster(s).index.has(id)) s = rehomed(roster(s), next(s, { filter: NO_FILTER, top: 0, loose: false }));
1408
+ const shown = roster(s).instances.find((each) => instanceId(each) === id) ?? row;
1409
+ const step = openAgent(next(s, { selected: id, loose: false, detailTop: 0 }), shown);
1410
+ return { state: step.state, effect: both(settledState.effect, step.effect) };
1411
+ }
1412
+ const reads = a.reads + 1;
1413
+ if (reads < 2) return { state: next(state, { arriving: Object.freeze({ ...a, reads }) }), effect: null };
1414
+ return { state: next(state, { arriving: null, outcome: spawnLine(outcomeWords("not-yet-visible", null, a.instance), a.instance, state.actions) }), effect: null };
1415
+ }