@awebai/oats 0.58.0 → 0.60.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 (63) hide show
  1. package/bin/oats.mjs +1 -1
  2. package/docs/desktop-cli-api.md +80 -8
  3. package/docs/desktop.md +30 -3
  4. package/docs/execution-targets.md +18 -2
  5. package/docs/implementation.md +3 -0
  6. package/docs/integrations.md +2 -2
  7. package/docs/knowledge.md +4 -4
  8. package/docs/official-catalog.md +4 -4
  9. package/docs/packages.md +14 -14
  10. package/docs/release-notes/v0.59.0.md +288 -0
  11. package/docs/release-notes/v0.60.0.md +104 -0
  12. package/docs/servers.md +4 -1
  13. package/docs/souls-and-instances.md +21 -0
  14. package/docs/tui.md +753 -119
  15. package/docs/workspaces.md +2 -2
  16. package/lib/core.mjs +258 -57
  17. package/lib/read-ahead-worker.mjs +119 -0
  18. package/lib/read-ahead.mjs +115 -0
  19. package/lib/retire-state.mjs +33 -0
  20. package/lib/servers.mjs +9 -1
  21. package/lib/session-input.mjs +53 -26
  22. package/package-catalog.json +3 -3
  23. package/package.json +1 -1
  24. package/packages/client/capability-catalog.mjs +93 -0
  25. package/packages/client/capability-facts.mjs +59 -0
  26. package/packages/client/capability-rows.mjs +121 -0
  27. package/packages/client/catalog-messages.mjs +12 -0
  28. package/packages/client/cli-locator.mjs +2 -2
  29. package/packages/client/deployment-data.mjs +4 -0
  30. package/packages/client/deployment-panel.mjs +3 -0
  31. package/packages/client/instance-acts.mjs +23 -8
  32. package/packages/client/instance-presentation.mjs +3 -2
  33. package/packages/client/instance-tree.mjs +84 -39
  34. package/packages/client/lifecycle-confirmation.mjs +9 -3
  35. package/packages/client/remote-roster.mjs +4 -1
  36. package/packages/client/retire-in-flight.mjs +65 -0
  37. package/packages/client/retire-state.mjs +30 -0
  38. package/packages/client/soul-catalog.mjs +8 -0
  39. package/packages/client/soul-facts.mjs +7 -0
  40. package/packages/client/spawn-apply.mjs +13 -4
  41. package/packages/client/spawn-messages.mjs +8 -0
  42. package/packages/client/subsequence-score.mjs +15 -0
  43. package/packages/tui/README.md +23 -10
  44. package/packages/tui/lib/actions.mjs +63 -5
  45. package/packages/tui/lib/client.mjs +17 -1
  46. package/packages/tui/lib/config.mjs +7 -2
  47. package/packages/tui/lib/main.mjs +364 -82
  48. package/packages/tui/lib/model.mjs +614 -57
  49. package/packages/tui/lib/panel.mjs +436 -125
  50. package/packages/tui/lib/read.mjs +52 -26
  51. package/packages/tui/lib/store.mjs +1025 -65
  52. package/packages/tui/lib/term/keys.mjs +9 -2
  53. package/packages/tui/lib/term/text.mjs +4 -0
  54. package/packages/tui/lib/term/through.mjs +12 -1
  55. package/packages/tui/lib/views/capabilities.mjs +239 -0
  56. package/packages/tui/lib/views/frame.mjs +433 -99
  57. package/packages/tui/lib/views/help.mjs +61 -15
  58. package/packages/tui/lib/views/instances.mjs +43 -25
  59. package/packages/tui/lib/views/palette.mjs +66 -0
  60. package/packages/tui/lib/views/souls.mjs +270 -0
  61. package/packages/tui/lib/views/spawn.mjs +301 -0
  62. package/packages/tui/lib/views/split.mjs +29 -0
  63. package/skills/oats-getting-started/SKILL.md +2 -2
@@ -9,17 +9,36 @@
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, capabilitiesHeight, capabilitiesOf, capabilityUsersOf, 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: "" }) });
35
+ /** The Capabilities view's own (docs/tui.md, "The Capabilities view"; Spec 7), as the Souls view's:
36
+ * whether its catalog was ever wanted, what the loop holds of each workspace's (`held`), and the
37
+ * selection (a capability's key, lib/model.mjs capabilityKey), the list's scroll (`top`, `loose` as
38
+ * the switcher's), the focus, the filter, and in the detail its scroll (`detailTop`, the row it was
39
+ * last drawn from) and the mark on a soul of "Used by" (`mark`, an index of the listed souls;
40
+ * `detailLoose` while the detail was scrolled away from it on purpose). Kept for the run. */
41
+ const NO_CAPABILITIES = Object.freeze({ wanted: false, held: new Map(), selected: null, top: 0, loose: false, focus: "list", detailTop: 0, detailLoose: false, mark: 0, filter: Object.freeze({ editing: false, query: "" }) });
23
42
 
24
43
  /** The state before the first answer. `deployment` is the one `oats tui` was started in or was
25
44
  * told of, with its shared pending entry (lib/main.mjs makes it); null for a run started outside
@@ -38,21 +57,42 @@ const NO_FILTER = Object.freeze({ editing: false, query: "" });
38
57
  * `opening`: the agent of another machine whose terminal is being opened, or null:
39
58
  * `{ id, phase: "preflight", name, machine, routed }` while that machine is asked whether its
40
59
  * 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".
60
+ * pressed, for the line after. `tabs`: the terminals open in the panel (docs/tui.md, "Tabs"),
61
+ * in the strips' order (each group's tabs in this order), at most TAB_LIMIT across both groups:
62
+ * each `{ id, name, machine, routed, status, activity, group }`, `id` the row's instanceId and the
63
+ * next three the row's as it was when it was opened, `status` "starting" until the panel has its
64
+ * window, then "open", `activity` true while it is hidden and its agent wrote since it was last
65
+ * shown, `group` 0 or 1 (docs/tui.md, "Splits"). `split`: null, or "right" or "down" while the
66
+ * panel is split in two groups; `group` the focused group (where an open goes); `aside` the other
67
+ * group's shown tab's id, or null (no split, or that group empty). `terminal`: the focused group's
68
+ * SHOWN tab, or null when no tab is open or the focused group is empty:
69
+ * `{ id, name, machine, routed, group, focus, zoom, status }`, its tab's fields with `focus`
70
+ * "terminal" while what is typed goes to the agent and "list" while the TUI reads keys, and `zoom`
71
+ * true while it has the whole body (only with the terminal's focus).
46
72
  * `outcome`: the line after an open (the model's `{ said, under }`), shown above the panes until
47
73
  * 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.
74
+ * `detachKey`: tui.json's `open.detachKey`, the leader (docs/tui.md, "The leader"), and
75
+ * `leaderKey` the key id it is read as where the TUI reads keys (term/through.mjs backKeyId).
76
+ * `leader`: `{ read, waiting }` from the leader's read on, or null (see `leading`).
77
+ * `palette`: the palette while it is open (see `paletteOpened`), or null. `recent`: the ids of
78
+ * the instances opened in this run, the latest first.
49
79
  * `act`: the confirmation open in the act view (see `actOpened`), or null; `acted` counts the
50
80
  * confirmations opened in this run, so an answer for one that was closed is told apart.
51
81
  * `starting`: id -> `{ verb, since }` of this run's starts and restarts whose child is still
52
82
  * alive, whether or not the TUI still waits for its answer (the loop says when one is spawned and
53
83
  * 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). */
84
+ * `retiring`: the instanceIds of the rows whose retire this run sent and has not read since
85
+ * (#1247), as lib/main.mjs's tracker says them (`{ retiring }`): they read as retiring. The roster
86
+ * is made from it (lib/model.mjs MADE_FROM), and from none of `opening`, `terminal`, `outcome`,
87
+ * `act`, `acted`, `starting`, `leader`, `palette` and `recent`.
88
+ * A SPAWN (docs/tui.md, "Spawning an agent"; see `spawnAsked`): `spawn` the prompt while it is
89
+ * open, or null; `spawning` the one spawn under way, `{ name, soul, workspace, phase, prompt }`
90
+ * (`phase` "submitting", "spawning" or "checking"; `prompt` the prompt as it was pressed, to come
91
+ * back to), or null; `spawnCheck` `{ name }` while a check of an outcome not known is offered
92
+ * (`C`), or null; `arriving` the instance a spawn created, `{ workspace, instance, home,
93
+ * agentsRoot, agent, reads, words }`, until its row is opened or two reads did not show it;
94
+ * `previews` the number of the last preview read asked in the run, so that an answer to a prompt
95
+ * already closed is never taken by the next one. */
56
96
  export function initialState({ deployment = null, cli, home, entry = null, actions = ACTIONS, ascii = false, detachKey = DETACH_KEY }) {
57
97
  return Object.freeze({
58
98
  view: deployment === null ? "switcher" : "instances", back: deployment === null ? "switcher" : "instances",
@@ -63,7 +103,9 @@ export function initialState({ deployment = null, cli, home, entry = null, actio
63
103
  selected: null, collapsed: new Set(), filter: NO_FILTER, focus: "list", top: 0, loose: false, detailTop: 0, places: new Map(), unread: new Map(),
64
104
  switcher: Object.freeze({ editing: false, query: "", selected: null, top: 0, loose: false, line: null, refused: null }),
65
105
  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(),
106
+ helpTop: 0, actions, ascii, detachKey, opening: null, terminal: null, outcome: null, act: null, acted: 0, starting: new Map(), retiring: new Set(),
107
+ leaderKey: backKeyId(detachKey), leader: null, palette: null, recent: Object.freeze([]), souls: NO_SOULS, capabilities: NO_CAPABILITIES,
108
+ spawn: null, spawning: null, spawnCheck: null, arriving: null, previews: 0, tabs: Object.freeze([]), split: null, group: 0, aside: null,
67
109
  });
68
110
  }
69
111
 
@@ -161,7 +203,11 @@ function took(state, { id, entry, number }) {
161
203
  if (observed && unread.has(id)) { unread = new Map(unread); unread.delete(id); }
162
204
  else if (!observed && held?.deployment?.status === "observed") unread = new Map(unread).set(id, new Set((Array.isArray(held.instances) ? held.instances : []).map(instanceId)));
163
205
  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 };
206
+ if (!observed) return { state: taken, effect: null };
207
+ const step = settled(state, taken);
208
+ if (step.state.arriving?.workspace !== id) return step;
209
+ const then = arrived(step.state);
210
+ return { state: then.state, effect: both(step.effect, then.effect) };
165
211
  }
166
212
 
167
213
  /** The roster of other machines after one outcome, as the shared rule made it (lib/read.mjs),
@@ -214,6 +260,16 @@ const FIELDS = Object.freeze({
214
260
  put: (state, query) => queried(state, query),
215
261
  close: (state, query) => next(queried(state, query), { filter: Object.freeze({ editing: false, query }) }),
216
262
  }),
263
+ souls: Object.freeze({
264
+ query: (state) => state.souls.filter.query,
265
+ put: (state, query) => (query === state.souls.filter.query ? state : soulsWith(state, { filter: Object.freeze({ ...state.souls.filter, query }), top: 0, loose: false, detailTop: 0 })),
266
+ close: (state, query) => soulsWith(state, { filter: Object.freeze({ editing: false, query }), top: 0, loose: false }),
267
+ }),
268
+ capabilities: Object.freeze({
269
+ query: (state) => state.capabilities.filter.query,
270
+ put: (state, query) => (query === state.capabilities.filter.query ? state : capabilitiesWith(state, { filter: Object.freeze({ ...state.capabilities.filter, query }), top: 0, loose: false, detailTop: 0, mark: 0 })),
271
+ close: (state, query) => capabilitiesWith(state, { filter: Object.freeze({ editing: false, query }), top: 0, loose: false }),
272
+ }),
217
273
  switcher: Object.freeze({
218
274
  query: (state) => state.switcher.query,
219
275
  put: (state, query) => (query === state.switcher.query ? state : next(state, { switcher: Object.freeze({ ...state.switcher, query, top: 0, loose: false }) })),
@@ -221,7 +277,10 @@ const FIELDS = Object.freeze({
221
277
  }),
222
278
  });
223
279
  /** 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);
280
+ const fieldOf = (state) => (state.view === "instances" && state.filter.editing ? FIELDS.instances
281
+ : state.view === "switcher" && state.switcher.editing ? FIELDS.switcher
282
+ : state.view === "souls" && state.souls.filter.editing ? FIELDS.souls
283
+ : state.view === "capabilities" && state.capabilities.filter.editing ? FIELDS.capabilities : null);
225
284
 
226
285
  /** A key while a filter field is open. A key that is text is text, whatever the action table
227
286
  * says, so `q` and `j` can be typed; Backspace removes one grapheme, Enter keeps the filter and
@@ -239,6 +298,161 @@ function edited(state, field, event, action) {
239
298
  return { state, effect: null };
240
299
  }
241
300
 
301
+ /** The Souls view's own state with what changes of it. */
302
+ const soulsWith = (state, changes) => next(state, { souls: Object.freeze({ ...state.souls, ...changes }) });
303
+
304
+ /** The Souls view shown (docs/tui.md, "The Souls view"): from now on its catalog is wanted, and
305
+ * the loop settles it for the open workspace (`souls: "settle"`), which reads it only when nothing
306
+ * is held for the workspace as it is now (the shared catalog's key). */
307
+ function soulsShown(state) {
308
+ // Come back to from another view, it shows its list: what was selected and filtered stays.
309
+ const shown = state.view === "souls" ? state : next(state, { view: "souls", back: "souls", souls: Object.freeze({ ...state.souls, focus: "list" }) });
310
+ return { state: soulsWith(shown, { wanted: true }), effect: { souls: "settle" } };
311
+ }
312
+
313
+ /** What the loop holds of a workspace's catalog, told: `{ id, entry, reading }` (the shared
314
+ * catalog's projected entry, or null, and whether a read is in flight). Only a served workspace's
315
+ * is kept. */
316
+ function soulsHeard(state, { id, entry, reading }) {
317
+ if (!state.ctxs.includes(id)) return { state, effect: null };
318
+ const held = soulsWith(state, { held: new Map(state.souls.held).set(id, Object.freeze({ entry: entry ?? null, reading: reading === true })) });
319
+ // A prompt that waits for this catalog to know its soul (N, before the Souls view was ever read).
320
+ return held.spawn?.workspace === id && held.spawn.step === "preview" && held.spawn.soul === null ? soulFound(held) : { state: held, effect: null };
321
+ }
322
+
323
+ /** The Instances view with the instances of soul `row` alone: the exact soul filter, shown where a
324
+ * kept filter stands; Esc clears it and `/` replaces it. */
325
+ function soulInstances(state, row) {
326
+ const filter = Object.freeze({ editing: false, query: "", soul: Object.freeze({ name: row.name, names: Object.freeze(soulNames(row)) }) });
327
+ return { state: rehomed(roster(state), next(state, { view: "instances", back: "instances", focus: "list", filter, top: 0, loose: false })), effect: null };
328
+ }
329
+
330
+ /** A key in the Souls view (docs/tui.md, "The Souls view"). The list's keys move among the souls
331
+ * the filter keeps, or scroll the detail while it has the focus; Enter gives the detail the focus,
332
+ * and from the detail does what `i` does, the selected soul's instances in the Instances view; `/`
333
+ * opens the view's own filter field; `r` reads the catalog again (`souls: "reread"`, which starts
334
+ * nothing while a read is in flight); Esc closes the detail, then clears a kept filter, then goes
335
+ * back to the instances (to the switcher when no workspace is open), as `1` does. */
336
+ function inSouls(state, action, event, page, scrolled) {
337
+ const stay = { state, effect: null }, v = state.souls;
338
+ const s = soulsOf(state), at = s.selected ? s.rows.indexOf(s.selected) : -1;
339
+ const back = () => ({ state: state.open === null ? toSwitcher(next(state, { back: "switcher" })) : next(state, { view: "instances", back: "instances" }), effect: null });
340
+ switch (action) {
341
+ case "instances": return back();
342
+ case "close":
343
+ if (v.focus === "detail") return { state: soulsWith(state, { focus: "list" }), effect: null };
344
+ if (v.filter.query !== "") return { state: soulsWith(state, { filter: Object.freeze({ editing: false, query: "" }), top: 0, loose: false }), effect: null };
345
+ return back();
346
+ case "filter": return s.local ? { state: soulsWith(state, { focus: "list", filter: Object.freeze({ ...v.filter, editing: true }) }), effect: null } : stay;
347
+ case "refresh": return s.local ? { state, effect: { souls: "reread" } } : stay;
348
+ case "open": return at < 0 ? stay : v.focus === "detail" ? soulInstances(state, s.selected) : { state: soulsWith(state, { focus: "detail" }), effect: null };
349
+ case "detail": return at < 0 ? stay : { state: soulsWith(state, { focus: v.focus === "detail" ? "list" : "detail" }), effect: null };
350
+ case "soul-instances": return at < 0 ? stay : soulInstances(state, s.selected);
351
+ case "up": case "down": case "top": case "bottom": case "page-up": case "page-down": {
352
+ if (v.focus === "detail") return { state: soulsWith(state, { detailTop: scrolled(v.detailTop) }), effect: null };
353
+ if (!s.rows.length) return stay;
354
+ const to = Math.min(Math.max(0, at < 0 ? 0 : moved(action, at, s.rows.length, page)), s.rows.length - 1);
355
+ const name = s.rows[to].name;
356
+ return { state: soulsWith(state, { selected: name, loose: false, detailTop: name === s.selected?.name ? v.detailTop : 0 }), effect: null };
357
+ }
358
+ default: return stay;
359
+ }
360
+ }
361
+
362
+ /** The Souls view with the soul named `name` selected, as the palette's soul row and the Capabilities
363
+ * view's "Used by" show it. A kept filter of the view that hides it is cleared: the soul chosen is
364
+ * the one shown, and the one `i` acts on. */
365
+ function soulChosen(state, name) {
366
+ const step = soulsShown(state), chosen = soulsWith(step.state, { selected: name, loose: false, detailTop: 0 });
367
+ const shown = soulsOf(chosen).selected?.name === name ? chosen : soulsWith(chosen, { filter: Object.freeze({ editing: false, query: "" }), top: 0 });
368
+ return { state: shown, effect: step.effect };
369
+ }
370
+
371
+ /** The Capabilities view's own state with what changes of it. */
372
+ const capabilitiesWith = (state, changes) => next(state, { capabilities: Object.freeze({ ...state.capabilities, ...changes }) });
373
+
374
+ /** The Capabilities view shown (docs/tui.md, "The Capabilities view"): from now on its catalog is
375
+ * wanted, and so is the souls catalog its "Used by" reads, the same flag the Souls view and a spawn
376
+ * set; the loop settles both for the open workspace (`capabilities: "settle"`, `souls: "settle"`),
377
+ * each read only when nothing is held for the workspace as it is now (each its own key). */
378
+ function capabilitiesShown(state) {
379
+ // Come back to from another view, it shows its list: what was selected and filtered stays.
380
+ const shown = state.view === "capabilities" ? state : next(state, { view: "capabilities", back: "capabilities", capabilities: Object.freeze({ ...state.capabilities, focus: "list" }) });
381
+ return { state: soulsWith(capabilitiesWith(shown, { wanted: true }), { wanted: true }), effect: { souls: "settle", capabilities: "settle" } };
382
+ }
383
+
384
+ /** What the loop holds of a workspace's capabilities catalog, told: `{ id, entry, reading }`, as
385
+ * soulsHeard. Only a served workspace's is kept. */
386
+ function capabilitiesHeard(state, { id, entry, reading }) {
387
+ if (!state.ctxs.includes(id)) return { state, effect: null };
388
+ return { state: capabilitiesWith(state, { held: new Map(state.capabilities.held).set(id, Object.freeze({ entry: entry ?? null, reading: reading === true })) }), effect: null };
389
+ }
390
+
391
+ /** The row the capability detail was drawn from, told by the loop once the frame is written (the
392
+ * view keeps the marked soul in sight, so the store's `detailTop` may not be what was drawn): the
393
+ * detail scrolls on from there. */
394
+ function capabilitiesTop(state, top) {
395
+ if (state.view !== "capabilities" || !Number.isInteger(top) || top < 0 || state.capabilities.detailTop === top) return { state, effect: null };
396
+ return { state: capabilitiesWith(state, { detailTop: top }), effect: null };
397
+ }
398
+
399
+ /** A key in the Capabilities view (docs/tui.md, "The Capabilities view"). The list's keys move among
400
+ * the capabilities the filter keeps, passing over the headings of the sections and the groups (the
401
+ * switcher's way: what stands above the first comes into the pane with it, and with nothing further
402
+ * to go to the list scrolls). Enter gives the detail the focus, its mark on the first soul of "Used
403
+ * by"; there Up and Down move that mark among the listed souls, and Enter shows the marked soul in
404
+ * the Souls view. Past the first or the last soul, with none listed, and for the other movement
405
+ * keys, the detail scrolls. `/`
406
+ * opens the view's own filter field; `r` reads the catalog again (`capabilities: "reread"`, which
407
+ * starts nothing while a read is in flight); Esc closes the detail, then clears a kept filter, then
408
+ * goes back to the instances (to the switcher when no workspace is open), as `1` does. */
409
+ function inCapabilities(state, action, event, page, scrolled) {
410
+ const stay = { state, effect: null }, v = state.capabilities;
411
+ const c = capabilitiesOf(state), at = c.selected === null ? -1 : c.keys.indexOf(c.selected);
412
+ const back = () => ({ state: state.open === null ? toSwitcher(next(state, { back: "switcher" })) : next(state, { view: "instances", back: "instances" }), effect: null });
413
+ const put = (changes) => ({ state: capabilitiesWith(state, changes), effect: null });
414
+ const toDetail = { focus: "detail", mark: 0, detailTop: 0, detailLoose: false };
415
+ switch (action) {
416
+ case "instances": return back();
417
+ case "close":
418
+ if (v.focus === "detail") return put({ focus: "list" });
419
+ if (v.filter.query !== "") return put({ filter: Object.freeze({ editing: false, query: "" }), top: 0, loose: false });
420
+ return back();
421
+ case "filter": return c.local ? put({ focus: "list", filter: Object.freeze({ ...v.filter, editing: true }) }) : stay;
422
+ case "refresh": return c.local ? { state, effect: { capabilities: "reread" } } : stay;
423
+ case "open": {
424
+ if (at < 0) return stay;
425
+ if (v.focus !== "detail") return put(toDetail);
426
+ const listed = capabilityUsersOf(state, undefined, c.row).shown;
427
+ const soul = listed[Math.min(v.mark, listed.length - 1)]?.soul ?? null;
428
+ return soul === null ? stay : soulChosen(state, soul);
429
+ }
430
+ case "detail": return at < 0 ? stay : put(v.focus === "detail" ? { focus: "list" } : toDetail);
431
+ case "up": case "down": case "top": case "bottom": case "page-up": case "page-down": {
432
+ if (v.focus === "detail") {
433
+ const listed = at < 0 ? 0 : capabilityUsersOf(state, undefined, c.row).shown.length;
434
+ // The mark moves while it has a soul to go to; past the first or the last, the detail scrolls.
435
+ const to = Math.min(v.mark, listed - 1) + (action === "up" ? -1 : 1);
436
+ if (listed && (action === "up" || action === "down") && to >= 0 && to < listed) return put({ mark: to, detailLoose: false });
437
+ return put({ detailTop: scrolled(v.detailTop), detailLoose: true });
438
+ }
439
+ const count = c.items.length, height = capabilitiesHeight(c, page);
440
+ const drawn = windowOf({ top: v.top, count, height, keep: v.loose ? -1 : c.items.findIndex((item) => item.key !== undefined && item.key === c.selected) }).top;
441
+ const key = c.keys.length ? c.keys[Math.min(Math.max(0, moved(action, Math.max(0, at), c.keys.length, page)), c.keys.length - 1)] : null;
442
+ // No capability to go to in that direction: the rows scroll instead.
443
+ if (key === null || key === c.selected) {
444
+ const top = windowOf({ top: moved(action, drawn, count, height), count, height }).top;
445
+ return top === drawn ? stay : put({ top, loose: true });
446
+ }
447
+ const index = c.items.findIndex((item) => item.key === key);
448
+ // The headings above the first capability come into the pane with it, and what stands under the last one.
449
+ const top = windowOf({ top: key === c.keys[0] ? 0 : key === c.keys.at(-1) ? count : drawn, count, height, keep: index }).top;
450
+ return put({ selected: key, top, loose: false, detailTop: 0, mark: 0, detailLoose: false });
451
+ }
452
+ default: return stay;
453
+ }
454
+ }
455
+
242
456
  const MOVES = Object.freeze(["up", "down", "top", "bottom", "page-up", "page-down"]);
243
457
  /** Where a movement key takes a position `from` among `count` rows, a page being `page` rows. */
244
458
  function moved(action, from, count, page) {
@@ -299,7 +513,8 @@ function switched(state, action, page) {
299
513
  * and `room` the rows the other scrolling pane holds and shows, as the last frame drew them: the
300
514
  * store keeps no size); a paste, `{ paste: <text> }`; or what the loop read:
301
515
  * `{ 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
516
+ * (one outcome of the roster read), `{ collecting }`, `{ retiring: <Set of instanceIds> }` (this
517
+ * run's retires in flight now), `{ offered: { offered, limited } }` (the
303
518
  * deployments of `~/Agents` not served), `{ admitted: <deployment>, at }` and `{ refused: <path> }`
304
519
  * (what a picked folder turned out to be).
305
520
  * Opening an agent gives five more: `{ prepared: { id, error? } }` (the preflight of another
@@ -308,7 +523,8 @@ function switched(state, action, page) {
308
523
  * viewer's window), `{ returned: { id, status, stderr, asked, refused } }` (the viewer ended: what
309
524
  * its pane wrote of its exit status and stderr, whether it was closed because the TUI asked, and
310
525
  * the panel's refusal when it started none: model.mjs returnedLine) and
311
- * `{ back: true }` (the back key was typed in the terminal).
526
+ * `{ back: true, read, rest }` (the leader was typed in the terminal, in that read of input;
527
+ * `rest`: more bytes came after it in the same read).
312
528
  * An effect is something only the loop can do: "quit", "suspend", "redraw", or an object with
313
529
  * any of `refresh: { live }` (read now), `offer: true` (list `~/Agents` again),
314
530
  * `admit: <path>` (ask whether a picked folder is a deployment), `close: <id>` (close the open
@@ -319,7 +535,13 @@ function switched(state, action, page) {
319
535
  * nothing (a stray back key is no key at all) leaves it. */
320
536
  export function reduce(state, event, keymap = bindings(state.actions)) {
321
537
  if (state.outcome !== null && typeof event.key === "string" && keymap.has(event.key)) state = next(state, { outcome: null });
322
- const step = reduced(state, event, keymap);
538
+ let step = reduced(state, event, keymap);
539
+ // The tabs are the open workspace's: whatever opened another (or left it, gone), they all close,
540
+ // and the split with them.
541
+ if (step.state.open !== state.open && (step.state.tabs.length || step.state.split !== null)) {
542
+ const ids = step.state.tabs.map((tab) => tab.id);
543
+ step = { state: next(step.state, { tabs: Object.freeze([]), terminal: null, ...NO_SPLIT }), effect: ids.length ? both(step.effect, { close: ids }) : step.effect };
544
+ }
323
545
  // The terminal has the focus only while the list of instances is shown: anything that shows
324
546
  // another view (a workspace gone, which shows the switcher) gives the focus back to the list.
325
547
  const t = step.state.terminal;
@@ -332,10 +554,110 @@ export function reduce(state, event, keymap = bindings(state.actions)) {
332
554
  return under ? { ...step, state: next(step.state, { focus: "list", filter: Object.freeze({ ...step.state.filter, editing: false }) }) } : step;
333
555
  }
334
556
 
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. */
557
+ /** The shown terminal with what changes of it: its focus and zoom (a change of its status goes
558
+ * through tabWith, which keeps its tab in step). */
338
559
  const terminalWith = (state, changes) => next(state, { terminal: Object.freeze({ ...state.terminal, ...changes }) });
560
+ /** Tab `id` with what changes of it, and the shown terminal with it when it is that tab. */
561
+ function tabWith(state, id, changes) {
562
+ const tabs = Object.freeze(state.tabs.map((tab) => (tab.id === id ? Object.freeze({ ...tab, ...changes }) : tab)));
563
+ const { activity, ...shared } = changes;
564
+ return next(state, { tabs, ...(state.terminal?.id === id ? { terminal: Object.freeze({ ...state.terminal, ...shared }) } : {}) });
565
+ }
566
+ /** No split: one group, focused. */
567
+ const NO_SPLIT = Object.freeze({ split: null, group: 0, aside: null });
568
+ /** Group `g`'s tabs, in the strip's order. */
569
+ const inGroup = (state, g) => state.tabs.filter((tab) => tab.group === g);
570
+ /** Group `g`'s shown tab's id: the focused group's is the terminal's, the other's `aside`. */
571
+ const shownOf = (state, g) => (g === state.group ? state.terminal?.id ?? null : state.aside);
572
+ /** The cap's line: every tab is taken, and how to free one (the leader's close). */
573
+ const fullLine = (state) => Object.freeze({ said: TAB_WORDS.full(TAB_LIMIT, state.detachKey), under: Object.freeze([]) });
574
+
575
+ /** A new tab for an open decision (the model's openDecision), starting, in the focused group:
576
+ * placed after its shown one (last, with none shown: an empty group's first) and shown, with the
577
+ * focus. */
578
+ function tabOpened(state, { id, name, machine, routed }) {
579
+ const group = state.group, tab = Object.freeze({ id, name, machine, routed, status: "starting", activity: false, group });
580
+ const at = state.terminal === null ? state.tabs.length : state.tabs.findIndex((each) => each.id === state.terminal.id) + 1;
581
+ const tabs = Object.freeze([...state.tabs.slice(0, at), tab, ...state.tabs.slice(at)]);
582
+ return next(state, { tabs, terminal: Object.freeze({ id, name, machine, routed, group, focus: "terminal", zoom: false, status: "starting" }) });
583
+ }
584
+
585
+ /** Tab `id` shown (docs/tui.md, "Tabs"), with `focus` and `zoom` (the shown one's, by default),
586
+ * in its group, which is the focused one from then on (docs/tui.md, "Splits"):
587
+ * its activity mark goes, it is the most recent for the palette, its instance's row is selected
588
+ * and revealed (a filter that hides it is cleared, a collapsed parent opened), and the focus stays
589
+ * where it was. The loop is told to show it unless it is the one shown already. */
590
+ function showTab(state, id, { focus = state.terminal?.focus ?? "list", zoom = state.terminal?.zoom ?? false } = {}) {
591
+ const tab = state.tabs.find((each) => each.id === id);
592
+ if (!tab) return { state, effect: null };
593
+ const { activity, ...fields } = tab;
594
+ const before = state.terminal?.id ?? null;
595
+ // A tab of the other group: that group is focused now, and the one left keeps its shown tab.
596
+ const across = tab.group !== state.group ? { group: tab.group, aside: before } : {};
597
+ const shown = next(state, {
598
+ tabs: Object.freeze(state.tabs.map((each) => (each.id === id && each.activity ? Object.freeze({ ...each, activity: false }) : each))),
599
+ terminal: Object.freeze({ ...fields, focus, zoom: focus === "terminal" && zoom }),
600
+ recent: recentWith(state, id),
601
+ ...across,
602
+ });
603
+ return { state: revealed(shown, id), effect: before === id ? null : { show: id } };
604
+ }
605
+
606
+ /** The row of instance `id` selected and on view in the list (Settled 5 of T2): a text filter
607
+ * that hides it is cleared, and a collapsed instance above it is opened. The focus is not moved,
608
+ * and nothing is selected when the row is not in the roster at all (it went away). */
609
+ function revealed(state, id) {
610
+ if (state.view !== "instances" || state.open === null) return state;
611
+ let s = state;
612
+ 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 }));
613
+ if (!roster(s).index.has(id) && s.collapsed.size) {
614
+ // The collapsed instances that hide it: each one alone would.
615
+ const hiding = [...s.collapsed].filter((key) => !roster(next(s, { collapsed: new Set([key]) })).index.has(id));
616
+ if (hiding.length) { const collapsed = new Set(s.collapsed); for (const key of hiding) collapsed.delete(key); s = next(s, { collapsed }); }
617
+ }
618
+ return roster(s).index.has(id) ? next(s, { selected: id, loose: false, detailTop: id === s.selected ? s.detailTop : 0 }) : s;
619
+ }
620
+
621
+ /** The shown tab closed by the person (`c` in the list, the leader then `w`): its viewer ends
622
+ * (the agent keeps running), the tab to its right is shown, else the one to its left, with the
623
+ * focus `focus` and the zoom `zoom` (the closed one's), within its group; a group's last one
624
+ * closed removes the group (ungrouped), and the last one of all gives the right side back to the
625
+ * detail and the focus to the list. */
626
+ function shownClosed(state, focus, zoom = state.terminal?.zoom ?? false) {
627
+ const t = state.terminal;
628
+ if (t === null) return { state, effect: null };
629
+ const mine = inGroup(state, state.group), at = mine.findIndex((tab) => tab.id === t.id);
630
+ const rest = mine.filter((tab) => tab.id !== t.id), neighbour = rest[at] ?? rest[at - 1] ?? null;
631
+ const closed = next(state, { tabs: Object.freeze(state.tabs.filter((tab) => tab.id !== t.id)), terminal: null });
632
+ // The group's last tab: the group goes, and the other takes the panel (or none is left).
633
+ const step = neighbour !== null ? showTab(closed, neighbour.id, { focus, zoom })
634
+ : state.split !== null ? ungrouped(closed, state.group, focus)
635
+ : { state: next(closed, { focus: "list" }), effect: null };
636
+ return { state: step.state, effect: both({ close: [t.id] }, step.effect) };
637
+ }
638
+
639
+ /** Group `g` of a split, empty now, removed (docs/tui.md, "Splits"): the other group takes the
640
+ * whole panel, as group 0, and is focused, its shown tab with the focus `focus`. When it is empty
641
+ * too nothing is left, and the panel closes. */
642
+ function ungrouped(state, g, focus) {
643
+ const left = shownOf(state, 1 - g);
644
+ const tabs = Object.freeze(state.tabs.map((tab) => (tab.group === 0 ? tab : Object.freeze({ ...tab, group: 0 }))));
645
+ const one = next(state, { tabs, terminal: null, ...NO_SPLIT });
646
+ if (left === null) return { state: next(one, { focus: "list" }), effect: null };
647
+ return showTab(one, left, { focus, zoom: false });
648
+ }
649
+
650
+ /** The tab before or after the shown one (`step` -1 or 1) in the focused group shown, without
651
+ * wrapping and never into the other group: at either end
652
+ * nothing moves, nor while a tab is still starting (it is the shown one until the panel has its
653
+ * window). The focus stays where it was, and so does the zoom. */
654
+ function tabStepped(state, step, { focus = state.terminal?.focus ?? "list", zoom = state.terminal?.zoom ?? false } = {}) {
655
+ const t = state.terminal;
656
+ if (t === null || state.tabs.some((tab) => tab.status === "starting")) return { state, effect: null };
657
+ const mine = inGroup(state, state.group), at = mine.findIndex((tab) => tab.id === t.id) + step;
658
+ if (at < 0 || at >= mine.length) return { state, effect: null };
659
+ return showTab(state, mine[at].id, { focus, zoom });
660
+ }
339
661
 
340
662
  /** The preflight of another machine's agent ended. Given up meanwhile (Esc, a suspend, a second
341
663
  * open): dropped. Failed: the line that says so, unless it is the person's own giving up. Else
@@ -345,60 +667,157 @@ function prepared(state, { id, error }) {
345
667
  if (opening === null || opening.id !== id || opening.phase !== "preflight") return { state, effect: null };
346
668
  if (error !== undefined) return { state: next(state, { opening: null, outcome: preflightLine(opening, error) }), effect: null };
347
669
  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 } };
670
+ return { state: tabOpened(next(state, { opening: null }), opening), effect: { panel: id } };
349
671
  }
350
672
 
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. */
673
+ /** The viewer of a tab ended by itself: its tab closes, the line says what happened, naming its
674
+ * instance (nothing when it ended cleanly), and the instances are read again at once. The shown
675
+ * one's end shows the tab to its right, else the one to its left, with the focus in the list
676
+ * (Settled 6 of T2); the last one's gives the right side back to the detail. The other group's
677
+ * shown one's end shows its neighbour there; a group's last one's removes the group (Settled 5 of
678
+ * 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
679
+ * it. The end of a tab the person closed (no longer a tab, then reported) changes nothing. */
355
680
  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 } } };
681
+ const tab = state.tabs.find((each) => each.id === id);
682
+ if (!tab) return { state, effect: null };
683
+ const line = returnedLine(tab, status, stderr, { asked, refused });
684
+ const mine = inGroup(state, tab.group), at = mine.findIndex((each) => each.id === id);
685
+ const rest = mine.filter((each) => each.id !== id), neighbour = rest[at] ?? rest[at - 1] ?? null;
686
+ const tabs = Object.freeze(state.tabs.filter((each) => each.id !== id));
687
+ const read = { refresh: { live: true } };
688
+ const focused = state.terminal?.id === id, aside = state.aside === id;
689
+ if (!focused && !aside) return { state: next(state, { tabs, ...(line ? { outcome: line } : {}) }), effect: read };
690
+ // The other group's shown tab: its neighbour is shown there, and nothing else moves.
691
+ if (aside && neighbour !== null) {
692
+ const shown = Object.freeze(tabs.map((each) => (each.id === neighbour.id && each.activity ? Object.freeze({ ...each, activity: false }) : each)));
693
+ return { state: next(state, { tabs: shown, aside: neighbour.id, ...(line ? { outcome: line } : {}) }), effect: read };
694
+ }
695
+ const closed = next(state, { tabs, ...(focused ? { terminal: null } : { aside: null }), outcome: line });
696
+ // A group's last tab ended: the group goes, the other takes the panel, the list the focus (Settled 5 of T3).
697
+ if (neighbour === null && state.split !== null) {
698
+ const step = ungrouped(next(closed, { focus: "list" }), tab.group, "list");
699
+ return { state: step.state, effect: both(read, step.effect) };
700
+ }
701
+ if (neighbour === null) return { state: closed, effect: read };
702
+ // The list takes the focus, from the detail too (Settled 6 of T2), so the neighbour is drawn.
703
+ const step = showTab(next(closed, { focus: "list" }), neighbour.id, { focus: "list" });
704
+ return { state: step.state, effect: both(read, step.effect) };
359
705
  }
360
706
 
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 };
707
+ /** Enter in the list of instances (or a row of the palette, the leader's Up and Down, a spawn's
708
+ * arrival): an instance open as a tab shows that tab, with the focus in it; another is opened as
709
+ * a new tab after the shown one, shown, with the focus (docs/tui.md, "Tabs"), or the line says why
710
+ * not. At the cap nothing closes on its own: the line says so. One open at a time (Settled 3 of
711
+ * T2): nothing while another machine is asked first or a tab is still starting, and a preflight
712
+ * holds its tab's place in the cap. Every open counts for the palette's recency (`recent`), as
713
+ * every tab shown does (showTab). */
714
+ function openAgent(state, row) {
715
+ if (state.opening !== null) return { state, effect: null };
716
+ const id = instanceId(row);
717
+ // A tab still starting is the one shown until the panel has its window (one open at a time).
718
+ const starting = state.tabs.some((tab) => tab.status === "starting");
719
+ if (state.tabs.some((tab) => tab.id === id)) {
720
+ if (starting && state.terminal?.id !== id) return { state, effect: null };
721
+ const step = showTab(state, id, { focus: "terminal", zoom: false });
722
+ return { state: step.state, effect: step.effect };
723
+ }
724
+ if (starting) return { state, effect: null };
368
725
  const decision = openDecision(state, row, instanceActs(row));
369
726
  if (!decision.open) return { state: next(state, { outcome: decision.said }), effect: null };
370
- const close = t === null ? {} : { close: t.id };
727
+ if (state.tabs.length >= TAB_LIMIT) return { state: next(state, { outcome: fullLine(state) }), effect: null };
728
+ state = next(state, { recent: recentWith(state, decision.id) });
371
729
  if (decision.routed) {
372
730
  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 } };
731
+ return { state: next(state, { opening, outcome: null }), effect: { open: decision } };
374
732
  }
375
- return { state: next(state, { terminal: startingTerminal(decision), outcome: null }), effect: { ...close, open: decision } };
733
+ return { state: next(tabOpened(state, decision), { outcome: null }), effect: { open: decision } };
376
734
  }
377
735
 
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) {
736
+ /** The keys of the shown terminal from the list: zoom gives it the focus and the whole body, and
737
+ * close ends its viewer (the agent keeps running) and shows its neighbour, the focus `focus`. */
738
+ function terminalKey(state, action, focus = "list", zoom = false) {
381
739
  const t = state.terminal;
382
740
  if (t === null) return { state, effect: null };
383
741
  if (action === "zoom") return { state: terminalWith(state, { focus: "terminal", zoom: true }), effect: null };
384
- return { state: next(state, { terminal: null }), effect: { close: t.id } };
742
+ return shownClosed(state, focus, zoom);
743
+ }
744
+
745
+ /** THE SPLIT'S KEYS (docs/tui.md, "Splits"). Why `does` would do nothing now: `true` for nothing
746
+ * at all (no tab, a tab starting, a key that does not apply), the line that says why (a split
747
+ * there is no room for, a second split), or null when it acts. `room` is the panel's size as the
748
+ * Instances view gives it with the terminal's focus (`{ cols, rows }`, its strip row counted:
749
+ * views/frame.mjs panelPlace), measured when the key is read; a room not known admits no split. Asked
750
+ * before anything is settled, so that a key that does nothing moves no focus. */
751
+ export function splitRefused(state, does, room, inTerminal = false) {
752
+ if (state.tabs.length === 0 || state.tabs.some((tab) => tab.status === "starting") || state.opening !== null) return true;
753
+ switch (does) {
754
+ case "split-right": case "split-down": {
755
+ const dir = does === "split-right" ? "right" : "down";
756
+ if (state.split !== null) return Object.freeze({ said: SPLIT_WORDS.twice(), under: Object.freeze([]) });
757
+ return splitFits(dir, room) ? null : Object.freeze({ said: SPLIT_WORDS.small(dir, SPLIT_MIN), under: Object.freeze([]) });
758
+ }
759
+ // One group: only from the list, to its terminal.
760
+ case "group-next": return state.split === null && (inTerminal || state.terminal === null) ? true : null;
761
+ case "tab-move": return state.split === null || state.terminal === null ? true : null;
762
+ case "group-close": return state.split === null || state.terminal !== null ? true : null;
763
+ default: return true;
764
+ }
765
+ }
766
+ /** A key of the split that acts (splitRefused said null), from the Instances view, `inTerminal`
767
+ * when it came from the terminal's focus:
768
+ * split-right, split-down: the tabs stay in the first group (left or top), and the second, empty,
769
+ * is the focused one; the keys are the list's (Settled 2 of T3), so Enter on a row opens there;
770
+ * group-next: to the other group's shown terminal, with the focus (to the empty group: focused,
771
+ * the keys the list's); from the list, to the focused group's terminal, or with that group
772
+ * empty to the other's;
773
+ * tab-move: the focused group's shown tab to the other group, after its shown tab, shown there
774
+ * with the focus; the group it leaves shows its neighbour, or stays, empty;
775
+ * group-close: the empty focused group goes; the other takes the panel and is focused, and the
776
+ * keys stay the list's (Settled 8 of T3). */
777
+ function splitKey(state, does, inTerminal) {
778
+ const t = state.terminal, other = 1 - state.group;
779
+ switch (does) {
780
+ case "split-right": case "split-down":
781
+ return { state: next(state, { split: does === "split-right" ? "right" : "down", group: 1, aside: t?.id ?? null, terminal: null, focus: "list" }), effect: null };
782
+ case "group-next": {
783
+ if (state.split === null || (!inTerminal && t !== null)) return { state: terminalWith(state, { focus: "terminal" }), effect: null };
784
+ const there = shownOf(state, other);
785
+ if (there !== null) return showTab(state, there, { focus: "terminal", zoom: false });
786
+ return { state: next(state, { group: other, aside: t?.id ?? null, terminal: null, focus: "list" }), effect: null };
787
+ }
788
+ case "tab-move": {
789
+ const mine = inGroup(state, state.group), at = mine.findIndex((tab) => tab.id === t.id);
790
+ const rest = mine.filter((tab) => tab.id !== t.id), neighbour = rest[at] ?? rest[at - 1] ?? null;
791
+ const without = state.tabs.filter((tab) => tab.id !== t.id);
792
+ const place = state.aside === null ? without.length : without.findIndex((tab) => tab.id === state.aside) + 1;
793
+ const moved = Object.freeze({ ...state.tabs.find((tab) => tab.id === t.id), group: other, activity: false });
794
+ 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)));
795
+ const { activity, ...fields } = moved;
796
+ const s = next(state, { tabs, group: other, aside: neighbour?.id ?? null, terminal: Object.freeze({ ...fields, focus: "terminal", zoom: false }) });
797
+ return { state: revealed(s, t.id), effect: { show: t.id } };
798
+ }
799
+ case "group-close": return ungrouped(state, state.group, "list");
800
+ default: return { state, effect: null };
801
+ }
385
802
  }
386
803
 
387
804
  /** The keys of the act view that are not the action table's: the focus moves with these and with
388
805
  * no printable key, so nothing typed or pasted as text reaches a button. */
389
806
  const FOCUS_KEYS = Object.freeze({ left: -1, "shift+tab": -1, right: 1, tab: 1 });
390
807
 
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);
808
+ /** An act key on `row` (the selected one; the open terminal's from the terminal's focus): the
809
+ * confirmation it opens, or the line that says why not (lib/model.mjs actDecision, over the row's
810
+ * instanceActs answer read now). A stop or a retire asks the loop for the shared confirmation
811
+ * (`act`), which reads the plan; a start or a restart opens the TUI's own confirmation, and
812
+ * nothing is asked of the loop until it is pressed. The focus starts on the first button,
813
+ * Cancel. Nothing while an open is under way. `after`: "terminal" when the confirmation was
814
+ * asked for from the terminal's focus, which it gives back when it closes. */
815
+ function actOn(state, row, verb, after = null) {
816
+ if (state.opening !== null) return { state, effect: null };
817
+ const decision = actDecision(state, row, instanceActs(row), verb);
399
818
  if (!decision.open) return { state: next(state, { outcome: decision.said }), effect: null };
400
819
  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 };
820
+ 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
821
  const act = decision.kind === "start"
403
822
  ? Object.freeze({ ...base, phase: "review", offers: Object.freeze(["close", "apply"]), answer: null })
404
823
  : Object.freeze({ ...base, phase: "reading", offers: Object.freeze(["close"]), outcome: null, notice: null, running: null, view: null, plan: null });
@@ -406,8 +825,13 @@ function actOn(state, r, at, verb) {
406
825
  }
407
826
 
408
827
  /** 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 } });
828
+ * the loop is told; a plan read, an apply or a start it sent goes on. One asked for from the
829
+ * terminal's focus gives it back, while that terminal is still the open one. */
830
+ function actClosed(state) {
831
+ const shut = next(state, { view: "instances", back: "instances", act: null }), t = shut.terminal;
832
+ const back = state.act.after === "terminal" && t !== null && t.id === state.act.id ? terminalWith(shut, { focus: "terminal", zoom: false }) : shut;
833
+ return { state: back, effect: { dismiss: state.act.n } };
834
+ }
411
835
 
412
836
  /** A key in the act view. Left/Right and Tab/Shift+Tab move the focus among the buttons, Enter
413
837
  * presses the one that has it, Esc closes, Space sets the plan's choice, the movement keys scroll
@@ -479,25 +903,273 @@ function acted(state, event) {
479
903
  return { state, effect: null };
480
904
  }
481
905
 
906
+ /** The instances the palette's recency keeps. */
907
+ const RECENT_KEPT = 50;
908
+ /** The actions of the split (docs/tui.md, "Splits"). */
909
+ const SPLIT_KEYS = Object.freeze(["split-right", "split-down", "group-next", "tab-move", "group-close"]);
910
+ /** The palette's recency with `id` the most recent: an open, and a tab shown. */
911
+ const recentWith = (state, id) => Object.freeze([id, ...state.recent.filter((each) => each !== id)].slice(0, RECENT_KEPT));
912
+ /** How many terminals the panel holds open at once (lib/panel.mjs MAX_TERMINALS, which a test
913
+ * holds this to). */
914
+ export const TAB_LIMIT = 4;
915
+ const leaderAt = (read, waiting) => Object.freeze({ read: Number.isInteger(read) ? read : null, waiting });
916
+ /** Whether an event came in the same read of input as the leader. */
917
+ const sameRead = (leader, event) => leader.read !== null && event.read === leader.read;
918
+ /** Two effects as one: the dismissal of a confirmation the leader closed, and what it then ran. */
919
+ const both = (a, b) => (a === null ? b : b === null ? a : typeof b === "string" ? b : { ...a, ...b });
920
+
921
+ /** THE LEADER (docs/tui.md, "The leader"): tui.json's open.detachKey, read as `leaderKey` where the
922
+ * TUI reads keys and as `{ back }` from the bytes typed into a terminal (term/through.mjs). It
923
+ * waits, with no timeout, for the key of LEADER's table that follows it IN A LATER READ, so a
924
+ * paste can never run a command: what comes in the leader's own read cancels it and is dropped.
925
+ * The key that follows is one key: the rest of its read is dropped too. A key not in the table
926
+ * cancels the leader and is dropped. Answers the step, or `{ pass }`: the state the event goes on
927
+ * in, when it is not the leader's. */
928
+ function leading(state, event, keymap) {
929
+ const l = state.leader;
930
+ // The leader typed in a terminal: the rest of that read is never the agent's (lib/main.mjs), and
931
+ // when there was a rest (`rest`), it cancelled the leader.
932
+ if (event.back !== undefined) return { state: state.terminal?.focus === "terminal" ? next(state, { leader: leaderAt(event.read, event.rest !== true) }) : state, effect: null };
933
+ if (typeof event.key !== "string" && !("paste" in event)) return { pass: state };
934
+ if (l !== null && sameRead(l, event)) return { state: l.waiting ? next(state, { leader: leaderAt(l.read, false) }) : state, effect: null };
935
+ if (l !== null && l.waiting) {
936
+ const after = next(state, { leader: leaderAt(event.read, false) });
937
+ const does = typeof event.key !== "string" ? undefined : event.key === state.leaderKey ? "list" : LEADER_KEYS.get(event.key);
938
+ return does === undefined ? { state: after, effect: null } : led(after, does, event, keymap);
939
+ }
940
+ const plain = l === null ? state : next(state, { leader: null });
941
+ if (event.key === state.leaderKey) return { state: next(plain, { leader: leaderAt(event.read, true) }), effect: null };
942
+ return { pass: plain };
943
+ }
944
+
945
+ /** Whatever has the focus, settled, so the list has it: the palette closed, a confirmation closed
946
+ * (the loop told), the help and the views of this machine left, a filter field kept as Enter keeps
947
+ * it, the terminal and the detail left. -> { state, effect } */
948
+ function toList(state) {
949
+ let s = state, effect = null;
950
+ if (s.palette !== null) s = next(s, { palette: null });
951
+ if (s.spawn !== null) s = next(s, { spawn: null });
952
+ if (s.view === "act" && s.act !== null) { effect = { dismiss: s.act.n }; s = next(s, { view: "instances", back: "instances", act: null }); }
953
+ if (s.view === "help") s = next(s, { view: s.back });
954
+ // The open field is the shown view's: kept before that view is left (the Souls view's too).
955
+ const field = fieldOf(s);
956
+ if (field) s = field.close(s, field.query(s).trim());
957
+ if (s.view === "souls" || s.view === "capabilities") s = s.open === null ? toSwitcher(next(s, { back: "switcher" })) : next(s, { view: "instances", back: "instances" });
958
+ if (s.terminal?.focus === "terminal") s = terminalWith(s, { focus: "list", zoom: false });
959
+ if (s.view === "instances" && s.focus === "detail") s = next(s, { focus: "list" });
960
+ return { state: s, effect };
961
+ }
962
+
963
+ /** As toList, then the Instances view itself: the switcher, while a workspace is open, closed onto
964
+ * it. Where the terminal commands (open, previous, next, zoom, close) and the acts go, from
965
+ * whatever was shown; with no workspace open the switcher stays. -> { state, effect } */
966
+ function toInstances(state) {
967
+ const settled = toList(state), s = settled.state;
968
+ if (s.view !== "switcher" || s.open === null) return settled;
969
+ return { state: next(s, { view: "instances", back: "instances", switcher: Object.freeze({ ...s.switcher, line: null, refused: null }) }), effect: settled.effect };
970
+ }
971
+
972
+ /** What the leader's key does (LEADER's `does`), from wherever the focus was. From the terminal's
973
+ * focus the acts are the open terminal's instance's and give the focus back when their
974
+ * confirmation closes, zoom zooms it in or out, and the palette gives it back when it is closed;
975
+ * Up and Down go from the open terminal's instance. Every other key first gives the focus to
976
+ * the list, then does what its action does there; the terminal's keys and the acts first go to
977
+ * the Instances view, from any view (toInstances). */
978
+ function led(state, does, event, keymap) {
979
+ const stay = { state, effect: null }, t = state.terminal;
980
+ const inTerminal = t?.focus === "terminal" && state.view === "instances";
981
+ if (does === "list") return toList(state);
982
+ if (does === "palette") return { state: paletteOpened(state, event, inTerminal ? "terminal" : "list"), effect: null };
983
+ if (does === "zoom" || does === "close-terminal") {
984
+ if (t === null) return stay;
985
+ if (does === "zoom" && inTerminal) return { state: terminalWith(state, { zoom: !t.zoom }), effect: null };
986
+ const settledState = toInstances(state);
987
+ if (settledState.state.view !== "instances") return stay;
988
+ // A close from the terminal's focus gives that focus, and the zoom, to the tab shown next
989
+ // (Settled 6 of T2): both are taken before settling, which gives the list the focus.
990
+ const step = terminalKey(settledState.state, does, inTerminal ? "terminal" : "list", inTerminal && t.zoom);
991
+ return { state: step.state, effect: both(settledState.effect, step.effect) };
992
+ }
993
+ // The tabs, from any focus: the one shown next keeps the focus and the zoom it had.
994
+ if (does === "tab-previous" || does === "tab-next") {
995
+ // At either end, or while a tab starts, nothing at all: not even the settling, which would
996
+ // take the focus from the terminal.
997
+ if (tabStepped(state, does === "tab-previous" ? -1 : 1).effect === null) return stay;
998
+ const settledState = toInstances(state);
999
+ if (settledState.state.view !== "instances") return stay;
1000
+ const step = tabStepped(settledState.state, does === "tab-previous" ? -1 : 1, { focus: inTerminal ? "terminal" : "list", zoom: inTerminal && t.zoom });
1001
+ return { state: step.state, effect: both(settledState.effect, step.effect) };
1002
+ }
1003
+ // The split's keys, from any focus: nothing at all when they do not apply (splitRefused).
1004
+ if (SPLIT_KEYS.includes(does)) {
1005
+ const refused = splitRefused(state, does, event.panel, inTerminal);
1006
+ if (refused === true) return stay;
1007
+ if (refused !== null) return { state: next(state, { outcome: refused }), effect: null };
1008
+ const settledState = toInstances(state);
1009
+ if (settledState.state.view !== "instances") return stay;
1010
+ const step = splitKey(settledState.state, does, inTerminal);
1011
+ return { state: step.state, effect: both(settledState.effect, step.effect) };
1012
+ }
1013
+ if (does === "previous" || does === "next") return stepped(state, does === "previous" ? -1 : 1, event);
1014
+ // Another of the open terminal's soul, from its focus; from anywhere else, of the selection's.
1015
+ // The Souls view's selected soul is named before the list is shown, which leaves that view.
1016
+ if (does === "spawn" || does === "spawn-another") {
1017
+ const target = spawnTarget(state, inTerminal ? t.id : state.selected);
1018
+ const settledState = toList(state);
1019
+ const step = spawnAsked(settledState.state, event, does, target);
1020
+ return { state: step.state, effect: both(settledState.effect, step.effect) };
1021
+ }
1022
+ if (does === "stop" || does === "retire" || does === "start" || does === "restart") {
1023
+ const id = inTerminal ? t.id : state.selected;
1024
+ const row = id === null ? null : roster(state).instances.find((each) => instanceId(each) === id) ?? null;
1025
+ if (row === null || state.open === null) return stay;
1026
+ const settledState = toInstances(state);
1027
+ const step = actOn(settledState.state, row, does, inTerminal ? "terminal" : null);
1028
+ return { state: step.state, effect: both(settledState.effect, step.effect) };
1029
+ }
1030
+ const settledState = toList(state);
1031
+ const { key, text, ...rest } = event;
1032
+ const step = reduced(settledState.state, { ...rest, action: does }, keymap);
1033
+ return { state: step.state, effect: both(settledState.effect, step.effect) };
1034
+ }
1035
+
1036
+ /** The leader's Up and Down: the instance before or after the open terminal's (or the selection's,
1037
+ * with none open) in the list as it is drawn, passing over the rows that cannot be opened, is
1038
+ * selected and opened with the focus in it, in the Instances view from whatever was shown (a
1039
+ * confirmation is closed, the loop told). At either end of the list nothing moves, and nothing
1040
+ * is left. */
1041
+ function stepped(state, step, event) {
1042
+ const stay = { state, effect: null };
1043
+ if (state.opening !== null || state.open === null) return stay;
1044
+ const settled = toInstances(state), s = settled.state;
1045
+ if (s.view !== "instances") return stay;
1046
+ const page = Math.max(1, Number.isInteger(event.page) ? event.page : 1);
1047
+ const r = roster(s, undefined, Number.isInteger(event.cols) ? event.cols : undefined);
1048
+ const from = indexOf(r, s.terminal !== null && r.index.has(s.terminal.id) ? s.terminal.id : s.selected);
1049
+ if (from < 0) return stay;
1050
+ for (let i = from + step; i >= 0 && i < r.items.length; i += step) {
1051
+ const item = r.items[i];
1052
+ if (!isRow(item) || !openDecision(s, item.row, instanceActs(item.row)).open) continue;
1053
+ const opened = openAgent(selectAt(s, r, i, page, step), item.row);
1054
+ return { state: opened.state, effect: both(settled.effect, opened.effect) };
1055
+ }
1056
+ return stay;
1057
+ }
1058
+
1059
+ /** THE PALETTE (docs/tui.md, "The palette"), opened: one input over the rows lib/model.mjs
1060
+ * paletteItems lists. `read` is the read of input that opened it: a press of Enter in that same
1061
+ * read runs nothing (a paste cannot open it and run a row). `from`: "terminal" when it was opened
1062
+ * from the terminal's focus, which closing it gives back. While it is open the TUI reads keys,
1063
+ * so the terminal does not have the focus. */
1064
+ function paletteOpened(state, event, from) {
1065
+ const palette = Object.freeze({ query: "", selected: null, top: 0, read: Number.isInteger(event.read) ? event.read : null, from });
1066
+ const t = state.terminal;
1067
+ return next(state, { palette, ...(t?.focus === "terminal" ? { terminal: Object.freeze({ ...t, focus: "list", zoom: false }) } : {}) });
1068
+ }
1069
+ /** The palette closed: the focus goes back to the terminal it came from, while that is open. */
1070
+ function paletteClosed(state) {
1071
+ const shut = next(state, { palette: null }), t = shut.terminal;
1072
+ return state.palette.from === "terminal" && t !== null && shut.view === "instances" ? terminalWith(shut, { focus: "terminal" }) : shut;
1073
+ }
1074
+ /** The keys that move the palette's selection: named keys only, so every letter is the query's. */
1075
+ const PALETTE_MOVES = Object.freeze({ up: "up", down: "down", pageup: "page-up", pagedown: "page-down" });
1076
+ /** A key or a paste while the palette is open. Text and a paste's first line go to the query,
1077
+ * Backspace takes a grapheme off it, Up and Down (and PageUp, PageDown) move among its rows,
1078
+ * Enter runs the selected row, Esc (or its own key again) closes it; quit, suspend and redraw keep
1079
+ * their actions. Every other key does nothing. */
1080
+ function inPalette(state, event, keymap) {
1081
+ const p = state.palette, stay = { state, effect: null };
1082
+ const put = (changes) => next(state, { palette: Object.freeze({ ...p, ...changes }) });
1083
+ const query = (text) => (text === p.query ? stay : { state: put({ query: text, selected: null, top: 0 }), effect: null });
1084
+ if ("paste" in event) return typeof event.paste === "string" ? query(typed(p.query, event.paste.split(LINE_END)[0])) : stay;
1085
+ if (typeof event.text === "string") return query(typed(p.query, event.text, { key: true }));
1086
+ const action = keymap.get(event.key);
1087
+ if (event.key === "backspace") return query([...GRAPHEMES.segment(p.query)].map((g) => g.segment).slice(0, -1).join(""));
1088
+ if (event.key === "escape" || action === "close" || action === "palette") return { state: paletteClosed(state), effect: null };
1089
+ if (action === "quit" || action === "suspend" || action === "redraw") return { state, effect: action };
1090
+ const list = paletteItems(state);
1091
+ const keys = list.items.map((item) => item.key);
1092
+ if (Object.hasOwn(PALETTE_MOVES, event.key)) {
1093
+ if (!keys.length) return stay;
1094
+ const page = Math.max(1, (Number.isInteger(event.page) ? event.page : 1) - 1);
1095
+ const from = Math.max(0, keys.indexOf(list.selected));
1096
+ const to = Math.min(Math.max(0, moved(PALETTE_MOVES[event.key], from, keys.length, page)), keys.length - 1);
1097
+ return { state: put({ selected: keys[to] }), effect: null };
1098
+ }
1099
+ if (event.key !== "enter") return stay;
1100
+ if (p.read !== null && event.read === p.read) return stay;
1101
+ const item = list.items.find((each) => each.key === list.selected);
1102
+ return item ? ranFromPalette(state, item, event, keymap) : stay;
1103
+ }
1104
+ /** A palette row run, what was open under the palette settled first as the leader settles it (a
1105
+ * filter field kept, a confirmation closed, the loop told): an instance is opened (its terminal
1106
+ * swapped into the panel) and an act opens its confirmation on the palette's instance, both in
1107
+ * the Instances view whatever was shown (toInstances); a view or a command does what its action
1108
+ * does from the list (toList). */
1109
+ function ranFromPalette(state, item, event, keymap) {
1110
+ const from = state.palette.from;
1111
+ const settled = item.kind === "instance" || item.kind === "act" ? toInstances(state) : toList(state), shut = settled.state;
1112
+ const then = (step) => ({ state: step.state, effect: both(settled.effect, step.effect) });
1113
+ // A soul: the Souls view, with it selected (soulChosen).
1114
+ if (item.kind === "soul") return then(soulChosen(shut, item.name));
1115
+ // A capability: the Capabilities view, with it selected, as a soul is shown.
1116
+ if (item.kind === "capability") {
1117
+ const step = capabilitiesShown(shut), chosen = capabilitiesWith(step.state, { selected: item.capability, loose: false, detailTop: 0, mark: 0, detailLoose: false });
1118
+ const shown = capabilitiesOf(chosen).selected === item.capability ? chosen : capabilitiesWith(chosen, { filter: Object.freeze({ editing: false, query: "" }), top: 0 });
1119
+ return then({ state: shown, effect: step.effect });
1120
+ }
1121
+ if (item.kind === "instance" || item.kind === "act") {
1122
+ const row = shut.view === "instances" ? roster(shut).instances.find((each) => instanceId(each) === item.id) : undefined;
1123
+ if (!row) return settled;
1124
+ if (item.does === "spawn-another") return then(spawnAsked(shut, event, item.does, { id: item.id }));
1125
+ if (item.kind === "act") return then(actOn(shut, row, item.does, from === "terminal" ? "terminal" : null));
1126
+ const r = roster(shut, undefined, Number.isInteger(event.cols) ? event.cols : undefined);
1127
+ const page = Math.max(1, Number.isInteger(event.page) ? event.page : 1);
1128
+ const at = indexOf(r, item.id);
1129
+ return then(openAgent(at < 0 ? shut : selectAt(shut, r, at, page), row));
1130
+ }
1131
+ const { key, text, ...rest } = event;
1132
+ return then(reduced(shut, { ...rest, action: item.does }, keymap));
1133
+ }
1134
+
482
1135
  function reduced(state, event, keymap) {
1136
+ const lead = leading(state, event, keymap);
1137
+ if (lead.pass === undefined) return lead;
1138
+ state = lead.pass;
483
1139
  const stay = { state, effect: null };
484
1140
  if (event.acted !== undefined) return acted(state, event.acted);
485
1141
  if (event.prepared !== undefined) return prepared(state, event.prepared);
486
1142
  if (event.given !== undefined) return state.opening?.phase === "preflight" ? { state: next(state, { opening: null }), effect: null } : stay;
487
1143
  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;
1144
+ 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;
1145
+ // A hidden tab's agent wrote (the panel says so once per hidden spell): its mark.
1146
+ 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
1147
  if (event.entry !== undefined) return took(state, event);
491
1148
  if (event.roster !== undefined) return heard(state, event.roster);
492
1149
  if (event.collecting !== undefined) return { state: event.collecting === state.collecting ? state : next(state, { collecting: event.collecting === true }), effect: null };
1150
+ // The rows stay where they are: only what they read changes.
1151
+ if (event.retiring !== undefined) return { state: next(state, { retiring: new Set(event.retiring) }), effect: null };
493
1152
  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
1153
  if (event.admitted !== undefined) return { state: admitted(state, event), effect: { refresh: { live: true } } };
495
1154
  if (event.refused !== undefined) return { state: next(state, { switcher: Object.freeze({ ...state.switcher, refused: event.refused }) }), effect: null };
496
- const field = fieldOf(state);
1155
+ if (event.souls !== undefined) return soulsHeard(state, event.souls);
1156
+ if (event.capabilities !== undefined) return capabilitiesHeard(state, event.capabilities);
1157
+ if (event.capabilitiesTop !== undefined) return capabilitiesTop(state, event.capabilitiesTop);
1158
+ if (event.spawnRead !== undefined) return spawnRead(state, event.spawnRead);
1159
+ if (event.spawnDrawn !== undefined) return spawnDrawn(state, event.spawnDrawn);
1160
+ if (event.spawnTop !== undefined) return spawnTop(state, event.spawnTop);
1161
+ if (event.spawnProgress !== undefined) return { state: state.spawning?.phase === "submitting" ? next(state, { spawning: Object.freeze({ ...state.spawning, phase: "spawning" }) }) : state, effect: null };
1162
+ if (event.spawnDone !== undefined) return spawnDone(state, event.spawnDone);
1163
+ // An action the leader or the palette runs comes as `{ action }`, with no key: whatever field or
1164
+ // confirmation was open has been settled first.
1165
+ const given = event.action !== undefined;
1166
+ if (!given && state.palette !== null) return inPalette(state, event, keymap);
1167
+ if (!given && state.spawn !== null) return inSpawn(state, event, keymap);
1168
+ const field = given ? null : fieldOf(state);
497
1169
  // A paste goes only into an open filter field: its first line. Anywhere else it is dropped whole.
498
1170
  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);
1171
+ if (typeof event.key !== "string" && !given) return stay;
1172
+ const action = given ? event.action : keymap.get(event.key);
501
1173
  if (field) return edited(state, field, event, action);
502
1174
  if (state.view === "act" && state.act !== null) return inAct(state, event, action);
503
1175
  const page = Math.max(1, Number.isInteger(event.page) ? event.page : 1);
@@ -512,11 +1184,21 @@ function reduced(state, event, keymap) {
512
1184
  switch (action) {
513
1185
  case "quit": case "suspend": case "redraw": return { state, effect: action };
514
1186
  // 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 } : {}) } };
1187
+ // In the Souls view it reads the souls again, and nothing else; in the Capabilities view, the capabilities.
1188
+ case "refresh": return state.view === "souls" ? inSouls(state, action, event, page, scrolled) : state.view === "capabilities" ? inCapabilities(state, action, event, page, scrolled) : { state, effect: { refresh: { live: true }, ...((state.view === "help" ? state.back : state.view) === "switcher" ? { offer: true } : {}) } };
516
1189
  case "help": return { state: next(state, state.view === "help" ? { view: state.back } : { view: "help", back: state.view, helpTop: 0 }), effect: null };
517
1190
  case "workspaces": return state.view === "switcher" ? stay : { state: toSwitcher(next(state, { back: "switcher" })), effect: { offer: true } };
1191
+ case "palette": return { state: paletteOpened(state, event, "list"), effect: null };
1192
+ // Souls and Capabilities are views of this machine, whatever workspace is open, or none.
1193
+ case "souls": return soulsShown(state);
1194
+ case "capabilities": return capabilitiesShown(state);
1195
+ // A spawn starts from the list of instances or the Souls view (the leader reaches them from anywhere).
1196
+ case "spawn": case "spawn-another": return state.view === "instances" || state.view === "souls" ? spawnAsked(state, event, action, spawnTarget(state)) : stay;
1197
+ case "spawn-check": return spawnChecked(state);
518
1198
  default:
519
1199
  }
1200
+ if (state.view === "souls") return inSouls(state, action, event, page, scrolled);
1201
+ if (state.view === "capabilities") return inCapabilities(state, action, event, page, scrolled);
520
1202
  if (state.view === "help") {
521
1203
  if (action === "close") return { state: next(state, { view: state.back }), effect: null };
522
1204
  if (action === "instances") return state.open === null ? stay : { state: next(state, { view: "instances", back: "instances" }), effect: null };
@@ -527,18 +1209,22 @@ function reduced(state, event, keymap) {
527
1209
  if (action === "close") {
528
1210
  // In this order: an open under way (another machine is asked first), a kept filter, the detail.
529
1211
  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 };
1212
+ if (state.filter.query !== "" || state.filter.soul) return { state: rehomed(roster(state), next(state, { filter: NO_FILTER, top: 0, loose: false })), effect: null };
531
1213
  return state.focus === "detail" ? { state: next(state, { focus: "list" }), effect: null } : stay;
532
1214
  }
533
1215
  const r = roster(state, undefined, Number.isInteger(event.cols) ? event.cols : undefined);
534
1216
  const at = indexOf(r, state.selected);
535
1217
  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);
1218
+ // A soul filter gives way to the text one.
1219
+ case "filter": return { state: rehomed(roster(state), next(state, { focus: "list", filter: Object.freeze({ editing: true, query: state.filter.query }) })), effect: null };
1220
+ case "open": return at < 0 ? stay : openAgent(state, r.items[at].row);
538
1221
  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);
1222
+ case "tab-previous": case "tab-next": return tabStepped(state, action === "tab-previous" ? -1 : 1);
1223
+ case "split-right": case "split-down": case "group-next": case "tab-move": case "group-close": {
1224
+ const refused = splitRefused(state, action, event.panel);
1225
+ return refused === true ? { state, effect: null } : refused !== null ? { state: next(state, { outcome: refused }), effect: null } : splitKey(state, action, false);
1226
+ }
1227
+ case "stop": case "retire": case "start": case "restart": return at < 0 ? stay : actOn(state, r.items[at].row, action);
542
1228
  case "detail": return at < 0 ? stay : { state: next(state, { focus: state.focus === "detail" ? "list" : "detail" }), effect: null };
543
1229
  case "up": case "down": case "top": case "bottom": case "page-up": case "page-down": {
544
1230
  if (state.focus === "detail") return { state: next(state, { detailTop: scrolled(state.detailTop) }), effect: null };
@@ -570,3 +1256,277 @@ function reduced(state, event, keymap) {
570
1256
  default: return stay;
571
1257
  }
572
1258
  }
1259
+
1260
+ // ── SPAWNING (docs/tui.md, "Spawning an agent"; Spec 6-spawn) ───────────────────────────────────
1261
+
1262
+ /** The longest name the name field takes: the kernel's instance-name limit (spawn-preview-contract
1263
+ * INSTANCE_NAME_MAX). The preview says when the soul's name and the dash leave less room. */
1264
+ const NAME_LIMIT = 64;
1265
+ /** What the name field takes as typed: the characters an instance name is made of. */
1266
+ const NAME_TEXT = /^[A-Za-z0-9-]+$/;
1267
+ /** The prompt with what changes of it. */
1268
+ const spawnWith = (state, changes) => next(state, { spawn: Object.freeze({ ...state.spawn, ...changes }) });
1269
+ /** A line of its own, and nothing else. */
1270
+ const said = (state, parts) => ({ state: next(state, { outcome: { said: parts, under: [] } }), effect: null });
1271
+ const remoteRow = (row) => typeof row?.server === "string" && row.server !== "";
1272
+ /** The parent a prompt can offer ("child of"): the selected instance of this workspace when it
1273
+ * opened, as the shared relation anchors it. */
1274
+ const anchorOf = (row) => (row && !remoteRow(row) ? Object.freeze({ id: instanceId(row), instance: row.instance, agent: row.agent, agentsRoot: row.agentsRoot }) : null);
1275
+
1276
+ /** What n and N are of, named in the view they were pressed in: the Souls view's selected soul
1277
+ * (`{ souls: row|null }`), else instance `id` (the selection's, or the open terminal's). */
1278
+ function spawnTarget(state, id = state.selected) {
1279
+ if ((state.view === "help" ? state.back : state.view) === "souls") return { souls: soulsOf(state).selected };
1280
+ return { id };
1281
+ }
1282
+
1283
+ /** n, N, the leader's n and N, and the palette's two rows (docs/tui.md, "Spawning an agent").
1284
+ * One spawn at a time: while one is under way the line says so and nothing opens. Only this
1285
+ * machine's workspace is offered: on another machine's workspace or row the line says so.
1286
+ * n opens the soul picker, and N the preview of the soul of instance `target.id` (the selection's,
1287
+ * or the open terminal's from its focus); from the Souls view (`target.souls`) both start from
1288
+ * its selected soul, at the preview. The catalog is wanted from now on (settled for the open
1289
+ * workspace, as the Souls view settles it). `read`: the read of input the prompt opened in, whose
1290
+ * Enter does nothing. */
1291
+ function spawnAsked(state, event, verb, target) {
1292
+ const stay = { state, effect: null };
1293
+ if (state.open === null) return stay;
1294
+ if (state.spawning !== null) return said(state, SPAWN_WORDS.busy(state.spawning.name));
1295
+ if (!state.ctxs.includes(state.open)) return said(state, SPAWN_WORDS.remote());
1296
+ const fromSouls = Object.hasOwn(target, "souls"), id = fromSouls ? null : target.id;
1297
+ const row = state.view === "instances" && id !== null ? roster(state).instances.find((each) => instanceId(each) === id) ?? null : null;
1298
+ // Settled 9: on another machine's row, neither n nor N opens anything of this one.
1299
+ if (row !== null && remoteRow(row)) return said(state, SPAWN_WORDS.remote());
1300
+ let soul = null, wanted = null;
1301
+ if (fromSouls) {
1302
+ if (target.souls) soul = Object.freeze({ name: target.souls.name, agentsRoot: target.souls.agentsRoot });
1303
+ } else if (verb === "spawn-another") {
1304
+ if (row === null) return stay;
1305
+ wanted = row.agent;
1306
+ }
1307
+ const preview = soul !== null || wanted !== null;
1308
+ const prompt = Object.freeze({
1309
+ workspace: state.open, step: preview ? "preview" : "picker", read: Number.isInteger(event.read) ? event.read : null,
1310
+ back: preview && (verb === "spawn-another" || fromSouls) ? "list" : "picker",
1311
+ query: "", selected: null, soul, wanted, anchor: anchorOf(row),
1312
+ name: "", nameRead: "", child: false, focus: "spawn", folds: Object.freeze([]), top: 0,
1313
+ n: 0, asked: null, status: preview ? "souls" : null, data: null, reason: null, shownIn: null, readKey: null, problem: null,
1314
+ });
1315
+ const opened = soulsWith(next(state, { spawn: prompt, outcome: null }), { wanted: true });
1316
+ const step = preview ? (soul ? previewAsked(opened) : soulFound(opened)) : { state: opened, effect: null };
1317
+ return { state: step.state, effect: both({ souls: "settle" }, step.effect) };
1318
+ }
1319
+
1320
+ /** A preview read asked of the loop (`spawnPreview`), numbered in the run (`previews`), not in the
1321
+ * prompt: only the answer to the last one is taken, and never one asked by a prompt closed since.
1322
+ * What was on screen stays while it is read, as stale, and Spawn is not armed until the answer
1323
+ * is drawn (`spawnDrawn`). */
1324
+ function previewAsked(state) {
1325
+ const p = state.spawn, n = state.previews + 1;
1326
+ const request = { action: "preview", selector: spawnSelector(p), choices: spawnChoices(p) };
1327
+ 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 } } };
1328
+ }
1329
+
1330
+ /** N's soul, found in the workspace's catalog once it is held: the preview is read for it. A
1331
+ * catalog that does not list it says so, and there is nothing to read or to spawn. */
1332
+ function soulFound(state) {
1333
+ const p = state.spawn, found = soulOfAgent(state, p.workspace, p.wanted);
1334
+ if (found) return previewAsked(spawnWith(state, { soul: Object.freeze({ name: found.name, agentsRoot: found.agentsRoot }) }));
1335
+ const held = state.souls.held.get(p.workspace)?.entry ?? null;
1336
+ if (!Array.isArray(held?.souls)) return { state, effect: null }; // still read
1337
+ return { state: spawnWith(state, { status: "failed", reason: null, problem: { said: SPAWN_WORDS.noSoul(p.wanted), under: [] } }), effect: null };
1338
+ }
1339
+
1340
+ /** The preview's answer (`{ n, answer }`): taken only for the last read asked. One the workspace
1341
+ * moved under is read again at once, as its shared words say. An answer taken is not yet seen:
1342
+ * Spawn is armed only once a frame that shows it ready is written (`spawnDrawn`). */
1343
+ function spawnRead(state, { n, answer }) {
1344
+ const p = state.spawn;
1345
+ if (p === null || p.step !== "preview" || p.n !== n) return { state, effect: null };
1346
+ if (answer?.status === "available") return { state: spawnWith(state, { status: "shown", data: answer.data, reason: null, readKey: p.asked, shownIn: null }), effect: null };
1347
+ if (answer?.reason?.code === "E_TARGET_CHANGED") return previewAsked(state);
1348
+ return { state: spawnWith(state, { status: "failed", reason: answer?.reason ?? null, readKey: null }), effect: null };
1349
+ }
1350
+
1351
+ /** A frame was written that shows preview `n` ready, its Spawn button on the screen
1352
+ * (`{ n, read }`, `read` the number of the last read of input before that frame): the paste guard
1353
+ * (inSpawn) takes Enter on Spawn only from a later read. Kept from the first such frame. */
1354
+ function spawnDrawn(state, { n, read }) {
1355
+ const p = state.spawn;
1356
+ if (p === null || p.step !== "preview" || p.n !== n || p.shownIn !== null || !spawnReady(p) || !Number.isInteger(read)) return { state, effect: null };
1357
+ return { state: spawnWith(state, { shownIn: read }), effect: null };
1358
+ }
1359
+
1360
+ /** The preview's window as a frame painted it (`{ n, top }`): it keeps the fold with the focus in
1361
+ * sight, so it may stand where `top` does not. Taken once for each frame painted, `top` is then
1362
+ * that window, and the movement keys go on from it, each from where the one before left it,
1363
+ * painted or not (round 1 of the polish's review). */
1364
+ function spawnTop(state, { n, top }) {
1365
+ const p = state.spawn;
1366
+ if (p === null || p.step !== "preview" || p.n !== n || !Number.isInteger(top) || top < 0 || p.top === top) return { state, effect: null };
1367
+ return { state: spawnWith(state, { top }), effect: null };
1368
+ }
1369
+
1370
+ /** The name field's text left as it is now: when it is not what the preview was read with, the
1371
+ * preview is read again. A changed choice puts away what an earlier spawn's outcome said. */
1372
+ function nameKept(state) {
1373
+ const p = state.spawn;
1374
+ if (p.name === p.nameRead) return { state, effect: null };
1375
+ return previewAsked(spawnWith(state, { nameRead: p.name, problem: null }));
1376
+ }
1377
+
1378
+ /** A key or a paste while the prompt is open.
1379
+ * THE PICKER, as the palette: text and a paste's first line go to the query, Backspace takes a
1380
+ * grapheme off it, Up and Down (PageUp, PageDown) move, Enter picks the selected soul (one whose
1381
+ * spawn would be refused is not picked), Esc closes the prompt.
1382
+ * THE PREVIEW (Settled 1): one focus ring, Spawn, the name, child of, each fold; Tab and Shift+Tab
1383
+ * move along it. Enter does what the focus says: spawns, keeps the name and reads the preview
1384
+ * again, toggles the parent, opens or closes a fold. On the name, text and a paste's first line
1385
+ * are the name's (the characters of an instance name only), and Esc puts back the name the
1386
+ * preview was read with; Esc elsewhere gives the focus to Spawn, and on Spawn backs out (to the
1387
+ * picker, or to the list for N and from the Souls view). The movement keys scroll it.
1388
+ * quit, suspend and redraw keep their actions where no text is typed.
1389
+ * THE PASTE GUARD (Settled 2): Enter in the read of input the prompt opened in does nothing, and
1390
+ * Enter on Spawn spawns only the preview read for the choices on screen, from a read of input
1391
+ * later than the one in which that answer landed: a pasted `n…⏎⏎` stops at the preview. */
1392
+ function inSpawn(state, event, keymap) {
1393
+ const p = state.spawn, stay = { state, effect: null };
1394
+ const action = typeof event.key === "string" ? keymap.get(event.key) : undefined;
1395
+ const sameRead = p.read !== null && event.read === p.read;
1396
+ if (p.step === "picker") {
1397
+ const query = (text) => (text === p.query ? stay : { state: spawnWith(state, { query: text, selected: null }), effect: null });
1398
+ if ("paste" in event) return typeof event.paste === "string" ? query(typed(p.query, event.paste.split(LINE_END)[0])) : stay;
1399
+ if (typeof event.text === "string") return query(typed(p.query, event.text, { key: true }));
1400
+ if (event.key === "backspace") return query([...GRAPHEMES.segment(p.query)].map((g) => g.segment).slice(0, -1).join(""));
1401
+ if (event.key === "escape" || action === "close") return { state: next(state, { spawn: null }), effect: null };
1402
+ if (action === "quit" || action === "suspend" || action === "redraw") return { state, effect: action };
1403
+ const list = spawnPickerItems(state), names = list.items.map((item) => item.name);
1404
+ if (Object.hasOwn(PALETTE_MOVES, event.key)) {
1405
+ if (!names.length) return stay;
1406
+ const page = Math.max(1, (Number.isInteger(event.page) ? event.page : 1) - 2);
1407
+ const from = Math.max(0, names.indexOf(list.selected));
1408
+ 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 };
1409
+ }
1410
+ if (event.key !== "enter" || sameRead) return stay;
1411
+ const item = list.items.find((each) => each.name === list.selected);
1412
+ if (!item || item.refused) return stay;
1413
+ 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 }));
1414
+ }
1415
+ const ring = spawnRing(p);
1416
+ const focus = ring.includes(p.focus) ? p.focus : "spawn";
1417
+ const moveFocus = (by) => { const to = ring[(ring.indexOf(focus) + by + ring.length) % ring.length]; return to === focus ? state : spawnWith(state, { focus: to }); };
1418
+ if (focus === "name") {
1419
+ const name = (text) => (text === p.name ? stay : { state: spawnWith(state, { name: text }), effect: null });
1420
+ const fits = (text) => text !== "" && NAME_TEXT.test(text) && p.name.length + text.length <= NAME_LIMIT;
1421
+ if ("paste" in event) { const line = typeof event.paste === "string" ? event.paste.split(LINE_END)[0] : ""; return fits(line) ? name(p.name + line) : stay; }
1422
+ if (typeof event.text === "string") return fits(event.text) ? name(p.name + event.text) : stay;
1423
+ if (event.key === "backspace") return name(p.name.slice(0, -1));
1424
+ if (action === "quit" || action === "suspend" || action === "redraw") return { state, effect: action };
1425
+ if (event.key === "escape") return { state: spawnWith(state, { name: p.nameRead, focus: "spawn" }), effect: null };
1426
+ if (event.key === "enter") return nameKept(spawnWith(state, { focus: "spawn" }));
1427
+ if (event.key === "tab" || event.key === "shift+tab") return nameKept(moveFocus(event.key === "tab" ? 1 : -1));
1428
+ return stay;
1429
+ }
1430
+ if ("paste" in event) return stay;
1431
+ if (event.key === "tab" || event.key === "shift+tab") return { state: moveFocus(event.key === "tab" ? 1 : -1), effect: null };
1432
+ if (event.key === "escape" || action === "close") {
1433
+ if (focus !== "spawn") return { state: spawnWith(state, { focus: "spawn" }), effect: null };
1434
+ return { state: p.back === "picker" ? spawnWith(state, { step: "picker", problem: null, status: null, data: null, readKey: null }) : next(state, { spawn: null }), effect: null };
1435
+ }
1436
+ if (action === "quit" || action === "suspend" || action === "redraw") return { state, effect: action };
1437
+ if (MOVES.includes(action)) {
1438
+ const count = event.extent ?? 0, height = event.room ?? 1;
1439
+ const from = windowOf({ top: p.top, count, height }).top;
1440
+ return { state: spawnWith(state, { top: windowOf({ top: moved(action, from, count, height), count, height }).top }), effect: null };
1441
+ }
1442
+ if (event.key !== "enter" || sameRead) return stay;
1443
+ if (focus === "child") return previewAsked(spawnWith(state, { child: !p.child, problem: null }));
1444
+ if (focus.startsWith("fold:")) {
1445
+ const key = focus.slice("fold:".length);
1446
+ return { state: spawnWith(state, { folds: Object.freeze(p.folds.includes(key) ? p.folds.filter((each) => each !== key) : [...p.folds, key]) }), effect: null };
1447
+ }
1448
+ if (p.status === "failed") return p.soul === null ? stay : previewAsked(state);
1449
+ if (!spawnReady(p) || p.shownIn === null || !Number.isInteger(event.read) || event.read <= p.shownIn) return stay;
1450
+ return spawnPressed(state);
1451
+ }
1452
+
1453
+ /** Enter on Spawn, the preview ready: the prompt closes, and the loop is asked to spawn it
1454
+ * (`spawn`): the prepare body the TUI builds (Settled 4), and the decision on screen, which is
1455
+ * the only one applied. The line says what is under way until its outcome. */
1456
+ function spawnPressed(state) {
1457
+ const p = state.spawn, selector = spawnSelector(p), choices = spawnChoices(p);
1458
+ // The kernel's name for it (a purpose typed is put after the soul's name), for the lines that follow.
1459
+ const name = p.data.instance || p.name || p.soul.name;
1460
+ const spawning = Object.freeze({ name, soul: p.soul.name, workspace: p.workspace, phase: "submitting", prompt: p });
1461
+ const spawn = { workspace: p.workspace, selector, input: { action: "prepare", selector, choices, task: "" }, decision: structuredClone(p.data.decision), name };
1462
+ return { state: next(state, { spawn: null, spawning, spawnCheck: null, outcome: null }), effect: { spawn } };
1463
+ }
1464
+
1465
+ /** C, while a check of an outcome not known is offered: the loop reads its result once
1466
+ * (`spawnCheck`); an unknown result applies the same reference again, never a new one. */
1467
+ function spawnChecked(state) {
1468
+ const c = state.spawnCheck;
1469
+ if (c === null || state.spawning !== null) return { state, effect: null };
1470
+ 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 } };
1471
+ }
1472
+
1473
+ /** Whether the person is busy elsewhere: an outcome then says what to do, and nothing opens over
1474
+ * what they are doing. */
1475
+ const free = (state) => state.palette === null && state.spawn === null && state.act === null && state.opening === null && (state.view === "instances" || state.view === "souls");
1476
+
1477
+ /** A spawn's outcome (`{ kind, view, reason, instance, home }`, the shared transaction's, with the
1478
+ * instance it is of), as Done 5 says each:
1479
+ * created, complete and launched: the instances are read at once, and the new row is waited
1480
+ * for (`arriving`, see `arrived`); its terminal opens with the focus;
1481
+ * created otherwise: the shared words, and nothing opens;
1482
+ * unknown, pending-expired, cleanup-owed: the shared words; a check is offered where they name one;
1483
+ * drifted, refused, rolled-back, never-submitted: the shared words, and the preview again (read
1484
+ * again, with the choices as they were), unless the person is busy elsewhere. */
1485
+ function spawnDone(state, { kind, view = null, reason = null, instance = null, home = null }) {
1486
+ const s = state.spawning;
1487
+ if (s === null) return { state, effect: null };
1488
+ const name = instance ?? s.name, settled = next(state, { spawning: null });
1489
+ const words = kind === "unknown" || kind === "refused" ? spawnProblem(reason, "spawn") : outcomeWords(kind, view, name);
1490
+ const line = spawnLine(words, name, state.actions);
1491
+ const refresh = { refresh: { live: true } };
1492
+ if (kind === "created") {
1493
+ const launched = view?.status === "complete" && view.receipt?.launched !== false;
1494
+ 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;
1495
+ return { state: next(settled, { arriving, outcome: launched ? null : line }), effect: refresh };
1496
+ }
1497
+ if (["unknown", "pending-expired", "cleanup-owed"].includes(kind)) {
1498
+ const spawnCheck = words?.next === "check-result" ? Object.freeze({ name, soul: s.soul, workspace: s.workspace, prompt: s.prompt }) : null;
1499
+ return { state: next(settled, { spawnCheck, outcome: line }), effect: refresh };
1500
+ }
1501
+ if (!free(settled) || !settled.ctxs.includes(s.workspace) || settled.open !== s.workspace) return { state: next(settled, { outcome: line }), effect: refresh };
1502
+ const back = next(settled, { spawn: Object.freeze({ ...s.prompt, read: null, focus: "spawn", problem: line, data: null, readKey: null, shownIn: null }) });
1503
+ const step = previewAsked(back);
1504
+ return { state: step.state, effect: both(refresh, step.effect) };
1505
+ }
1506
+
1507
+ /** A read of the workspace a spawn created an instance in (Settled 5): when its row is there and
1508
+ * can be opened, it is selected and its terminal opened with the focus, in the Instances view, as
1509
+ * the palette's open does (a filter that hides it is cleared). Not yet, after two reads: the line
1510
+ * says so. The person busy elsewhere, or another workspace open: the line says it was created. */
1511
+ function arrived(state) {
1512
+ const a = state.arriving, row = spawnedRow(state, a);
1513
+ if (row && openDecision(state, row, instanceActs(row)).open) {
1514
+ const done = next(state, { arriving: null });
1515
+ 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 };
1516
+ const settledState = toInstances(done), id = instanceId(row);
1517
+ // Every tab taken (Settled 7 of T2): the created line, then the cap's; nothing opens.
1518
+ if (!done.tabs.some((tab) => tab.id === id) && done.tabs.length >= TAB_LIMIT) {
1519
+ const created = spawnLine({ ...a.words, next: null }, a.instance, state.actions), full = fullLine(done);
1520
+ const said = created?.said.length ? [...created.said, { own: " " }, ...full.said] : full.said;
1521
+ return { state: next(done, { outcome: Object.freeze({ said: Object.freeze(said), under: created?.under ?? [] }) }), effect: null };
1522
+ }
1523
+ let s = settledState.state;
1524
+ if (!roster(s).index.has(id)) s = rehomed(roster(s), next(s, { filter: NO_FILTER, top: 0, loose: false }));
1525
+ const shown = roster(s).instances.find((each) => instanceId(each) === id) ?? row;
1526
+ const step = openAgent(next(s, { selected: id, loose: false, detailTop: 0 }), shown);
1527
+ return { state: step.state, effect: both(settledState.effect, step.effect) };
1528
+ }
1529
+ const reads = a.reads + 1;
1530
+ if (reads < 2) return { state: next(state, { arriving: Object.freeze({ ...a, reads }) }), effect: null };
1531
+ return { state: next(state, { arriving: null, outcome: spawnLine(outcomeWords("not-yet-visible", null, a.instance), a.instance, state.actions) }), effect: null };
1532
+ }