@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
@@ -8,16 +8,21 @@
8
8
  import {
9
9
  TERMS, panelData, displayLine, DETAIL_WITHHELD, originLead, instanceId, instanceVisibleInTree, waitingRollup, collapseKey, filterInstanceTree,
10
10
  hasInstanceChildren, heldHome, rosterSections, deploymentState, rowStale, primaryDeployment, isMultiDeployment, runtimeState, runtimeCounts,
11
- waitingClaim, waitingLabel, waitedText, waitingClock, waitingBelowText, instanceActs,
11
+ waitingClaim, waitingLabel, waitedText, waitingClock, waitingBelowText, instanceActs, rowReason,
12
12
  identityMemory, viewModel, workspaceChoices, workspaceChoiceRows, choiceMatches, UNMATCHED_SECTION, shortPath,
13
13
  openAct, deployments as heldDeployments, attachExit, preflightFailure, kernelLines,
14
- startGate, launchFlagIgnored, flagIgnoredNotice, retainedStartMessage,
14
+ startGate, launchFlagIgnored, flagIgnoredNotice, retainedStartMessage, retiringRows, soulRows, soulFacts, spawnRefusal,
15
+ defaultSpawnChoices, spawnProblem, outcomeWords, previewFacts, deploymentLabel, subsequenceScore, soulMatches, soulCatalogFailure, catalogFailure,
16
+ memberNames, capabilitySource, groupCapabilities, hostKeyOf, capabilitySections, matchCapabilities, soulsComposition, rosterAgentName, layerLabel, capabilityUsers,
17
+ capabilityFacts, CAPABILITY_COPY,
15
18
  } from "./client.mjs";
16
- import { shownLines } from "./term/text.mjs";
19
+ import { LEADER, keyLabel } from "./actions.mjs";
20
+ import { ownEllipsis, shownLines } from "./term/text.mjs";
17
21
  import { textWidth } from "./term/width.mjs";
18
22
  import { windowOf } from "./views/scroll.mjs";
23
+ import { SOUL_COLOURS } from "./views/souls.mjs";
19
24
 
20
- /** The widest the state column of the list may be, in cells. */
25
+ /** The widest the word column of the list may be, in cells. */
21
26
  export const WORD_MAX = 20;
22
27
  /** The most rows one sentence takes inside the list (a deployment's note, a reason). */
23
28
  const SENTENCE_ROWS = 4;
@@ -43,7 +48,8 @@ export function heldOf(state, at) {
43
48
 
44
49
  /** The panel of the view that holds `state.open`: the composition the Desktop's own panel is
45
50
  * served from (panel-views.mjs `panelData`), so nothing of it is put together by hand here.
46
- * Null while nothing is open (a run started outside a deployment, before a pick). */
51
+ * Null while nothing is open (a run started outside a deployment, before a pick). Its rows are
52
+ * as read: this run's retires in flight are put on them by `build` alone. */
47
53
  export function panelOf(state, at) {
48
54
  return state.open === null ? null : panelData(heldOf(state, at), state.open, TERMS);
49
55
  }
@@ -56,18 +62,38 @@ export function clockTime(iso) {
56
62
  return text(iso) && Number.isFinite(at.getTime()) ? `${pad(at.getHours())}:${pad(at.getMinutes())}:${pad(at.getSeconds())}` : null;
57
63
  }
58
64
 
65
+ /** The deployments of other machines whose rows the last roster outcome read (their group's probe
66
+ * answered), by the ids the shared `deployments` gives them, which a row's `deployment.id` carries:
67
+ * what a roster outcome covers of this run's retires in flight (lib/main.mjs). */
68
+ export function reachedMachines(state, at) {
69
+ return new Set(heldDeployments(heldOf(state, at)).filter((w) => w.remote && w.group?.probe?.ok === true).map((w) => w.id));
70
+ }
71
+
59
72
  /** A row's state in a word: the one the kernel or the collector reported on the row, else the
60
73
  * shared word for what is known of it (running, stopped, unknown). A row kept from a machine
61
74
  * that was not reached (the shared home marks it) still carries the word of its last report,
62
75
  * which is not its state now: it gets the shared word, so nothing reads as stopped, or as
63
76
  * running, that is only not reached. */
64
77
  const stateWord = (row) => (text(row.runtimeState) && row.serverUnreached !== true ? row.runtimeState : runtimeState(row));
65
- /** What a list row shows at its right edge: a held home's state, the harness of a running
66
- * instance, else its state. */
67
- function wordOf(row) {
78
+ /** The word a list row shows beside its name, or null: only what its mark cannot say. That is a
79
+ * held home's state (Retiring… while a retire runs, or this run's own is in flight), else the
80
+ * shared label of the reason the row can't be reached or opened (remote-address.mjs rowReason:
81
+ * `gone from <machine>`, `<machine> not reached`, `state unknown`, …). A row that runs, is
82
+ * stopped, or keeps a shell has no word: its mark says it, and its harness is in the detail. */
83
+ function wordOf(row, ascii) {
84
+ const held = heldHome(row);
85
+ return held ? ownEllipsis(held.state, ascii) : rowReason(row)?.label ?? null;
86
+ }
87
+ /** The detail's state: the list's word when it is a held home's state or the label of a reason
88
+ * the row can't be reached (a row gone from its machine reads `gone from <machine>`, not
89
+ * `unknown`); else the word the kernel or the collector reported, else the shared word. The
90
+ * reason that says only that the state is not known gives way to the kernel's own word for it
91
+ * (`unreachable`), which says more. */
92
+ function detailState(row, ascii) {
68
93
  const held = heldHome(row);
69
- if (held) return held.state;
70
- return row.running === true && text(row.harness) ? row.harness : stateWord(row);
94
+ if (held) return ownEllipsis(held.state, ascii);
95
+ const reason = rowReason(row);
96
+ return reason && reason.key !== "unknown" ? reason.label : stateWord(row);
71
97
  }
72
98
  /** Which mark a row carries: the shared word, `held` for a home the kernel holds, and `shell`
73
99
  * for a stopped instance whose terminal still has a shell in it. */
@@ -77,8 +103,10 @@ function markOf(row) {
77
103
  return word === "stopped" && row.runtimeState === "shell" ? "shell" : word;
78
104
  }
79
105
 
80
- /** The group of instances that are related to no other, as the shared grouping names it. */
81
- const SINGLES = "independent";
106
+ /** The key prefix of each run of instances related to no other, as the shared grouping names it
107
+ * (`independent:<id>`). Read by key, not by label: a cluster whose root is named `independent` has that
108
+ * label too, and its key is `cluster:<n>:independent`. */
109
+ const SINGLES = "independent:";
82
110
 
83
111
  /** Everything of a state that does not depend on a width: the panel, the rows as the shared
84
112
  * grouping orders them, the headings, and what stands after the sections. */
@@ -87,31 +115,57 @@ function build(state, at) {
87
115
  // No view holds what was open (a machine that is no longer listed): the store shows the
88
116
  // switcher for it; nothing is drawn from this answer.
89
117
  const gone = panel !== null && !panel.workspace;
90
- const instances = panel?.instances ?? [], deployments = panel?.deployments ?? [];
118
+ // A row whose retire this run sent and has not read since reads as retiring (#1247): every answer
119
+ // below, the acts included, is made from these rows.
120
+ const instances = retiringRows(panel?.instances ?? [], state.retiring), deployments = panel?.deployments ?? [];
91
121
  const multi = isMultiDeployment(deployments);
92
- const query = state.filter.query, filtering = query.trim() !== "";
122
+ // The filter: the text typed after `/`, or the exact soul filter the Souls view's `i` sets
123
+ // (`soul`: the names an instance's soul may carry), matched by the shared walk all the same.
124
+ const query = state.filter.query, soul = state.filter.soul ?? null, filtering = query.trim() !== "" || soul !== null;
93
125
  // The section (deployment) each row is drawn in, read from the shared split itself: the
94
126
  // sections of all rows. A collapse hides, and rolls up, only rows of its own section, as in the
95
127
  // Desktop: a parent's name can resolve to a row of another deployment of the view.
96
- const sectionOf = new Map();
97
- for (const part of rosterSections(instances, instances, deployments, TERMS)) for (const group of part.groups) for (const cluster of group.clusters) for (const row of cluster.instances) sectionOf.set(instanceId(row), part.deployment?.id ?? null);
128
+ // `ordered`: every row in that order, whatever is filtered or folded (the palette's).
129
+ const sectionOf = new Map(), ordered = [];
130
+ for (const part of rosterSections(instances, instances, deployments, TERMS)) for (const group of part.groups) for (const cluster of group.clusters) for (const row of cluster.instances) { sectionOf.set(instanceId(row), part.deployment?.id ?? null); ordered.push(row); }
98
131
  const section = (row) => sectionOf.get(instanceId(row)) ?? null;
99
- const matched = filterInstanceTree(instances, query);
132
+ const matched = soul !== null ? filterInstanceTree(instances, soul.name, (row) => soul.names.includes(row.agent)) : filterInstanceTree(instances, query);
100
133
  const visible = matched.filter((i) => instanceVisibleInTree(i, instances, state.collapsed, state.open, filtering, { section }));
101
134
  const sections = rosterSections(instances, visible, deployments, TERMS);
135
+ // How many instances each collapse folds away under its row: every descendant of the row in its
136
+ // own section, as the shared walk finds them when it is asked with that collapse alone (so a
137
+ // fold further down hides none of them from the count). A filter folds nothing away.
138
+ const folded = new Map();
139
+ if (!filtering) for (const row of visible) {
140
+ const key = collapseKey(state.open, instanceId(row));
141
+ if (!state.collapsed.has(key)) continue;
142
+ const alone = new Set([key]);
143
+ folded.set(instanceId(row), instances.filter((other) => !instanceVisibleInTree(other, instances, alone, state.open, false, { section })).length);
144
+ }
102
145
  const stale = (row) => rowStale(row, deployments);
146
+ const primary = primaryDeployment(deployments), said = deploymentState(primary);
147
+ const live = primary !== null && said.key === "live";
148
+ // The time of the read the screen shows: the cycle's own (`generatedAt`), never
149
+ // `observedAt`, which is when the kernel last looked at the workspace's remotes and is up
150
+ // to a minute older on a read in the background. Nothing drawn here comes from the remotes.
151
+ // In a view whose primary is a machine it is the time of the last roster read (heldOf).
152
+ const readAt = live ? clockTime(panel.generatedAt) : null;
103
153
 
104
154
  // The list, top to bottom, before any width. A section that has a label (a view of two or more
105
155
  // deployments) starts with its heading and the deployment's note; then the groups in the order
106
- // given, every cluster's members in order, with one gap before the group of single instances
107
- // when rows of the section came before it.
156
+ // given, every cluster's members in order, with one gap at every boundary between a run of single
157
+ // instances and a cluster, both ways (#1262).
108
158
  const parts = [], rows = [];
109
159
  const heading = (deployment, label, path = null) => {
110
- const said = deploymentState(deployment), live = said.key === "live";
160
+ const its = deploymentState(deployment), up = its.key === "live";
161
+ // A machine's rows are what it reported at the last roster read: that time stands on its
162
+ // heading only when the header's time is another, so the heading of a machine read with
163
+ // this one is its name alone. A deployment that is not live has its state and short reason
164
+ // in the shared words instead, and no time.
165
+ const read = up && deployment.local === false ? clockTime(state.rosterAt) : null;
111
166
  return {
112
- kind: "heading", label, path, state: live ? null : said.text, short: live || !text(deployment.short) ? null : deployment.short,
113
- // A machine's rows are what it reported at the last roster read.
114
- readAt: live && deployment.local === false ? clockTime(state.rosterAt) : null,
167
+ kind: "heading", label, path, state: up ? null : its.text, short: up || !text(deployment.short) ? null : deployment.short,
168
+ readAt: read !== readAt ? read : null,
115
169
  };
116
170
  };
117
171
  for (const part of sections) {
@@ -119,34 +173,35 @@ function build(state, at) {
119
173
  parts.push(heading(part.deployment, part.label));
120
174
  if (text(part.deployment.note)) parts.push({ kind: "sentence", value: part.deployment.note });
121
175
  }
122
- let drawn = 0;
176
+ let previous = null; // whether the group drawn last was a run of single instances
123
177
  for (const group of part.groups) {
124
- if (group.key === SINGLES && drawn) parts.push({ kind: "gap" });
178
+ // A gap at every boundary between a run of single instances and a cluster, both ways (#1262).
179
+ const singles = group.key.startsWith(SINGLES);
180
+ if (previous !== null && singles !== previous) parts.push({ kind: "gap" });
181
+ previous = singles;
125
182
  for (const cluster of group.clusters) for (const row of cluster.instances) {
126
183
  const item = { kind: "row", row, id: instanceId(row), depth: Number.isInteger(row.depth) ? row.depth : 0 };
127
- parts.push(item); rows.push(item); drawn++;
184
+ parts.push(item); rows.push(item);
128
185
  }
129
186
  }
130
187
  }
131
188
  // A deployment of the view that is not live and has no row is in no section: it is named
132
189
  // after them, with its state, and its reason on rows of its own.
133
190
  if (multi) for (const deployment of deployments) {
134
- const said = deploymentState(deployment);
135
- if (said.key === "live" || sections.some((part) => part.deployment?.id === deployment.id)) continue;
191
+ const its = deploymentState(deployment);
192
+ if (its.key === "live" || sections.some((part) => part.deployment?.id === deployment.id)) continue;
136
193
  parts.push(heading(deployment, deployment.machine, deployment.label));
137
- if (text(said.detail)) parts.push({ kind: "sentence", value: said.detail });
194
+ if (text(its.detail)) parts.push({ kind: "sentence", value: its.detail });
138
195
  if (text(deployment.note)) parts.push({ kind: "sentence", value: deployment.note });
139
196
  }
140
197
  // The roster read failed and no answer has arrived yet: there is no machine to say it.
141
198
  // It is about no row above it: an empty row sets it apart when something stands there.
142
199
  if (state.remote.rosterFailure !== null) parts.push(...(parts.length ? [{ kind: "gap" }] : []), { kind: "own", words: ROSTER_FAILED }, { kind: "sentence", value: state.remote.rosterFailure });
143
200
 
144
- const primary = primaryDeployment(deployments), said = deploymentState(primary);
145
201
  // The entry of this machine's deployment, when the view's primary is one: only it is ever
146
202
  // pending, withholds homes, or holds nothing after a failed read. A machine's panel has none.
147
203
  const status = panel?.deployment?.status ?? null;
148
204
  const local = panel !== null && !!panel.deployment;
149
- const live = primary !== null && said.key === "live";
150
205
  const counted = runtimeCounts(instances);
151
206
  const waiting = instances.filter((row) => waitingClaim(row, { stale: stale(row) })).length;
152
207
  const withheld = Array.isArray(panel?.deployment?.withheld) ? panel.deployment.withheld.length : 0;
@@ -158,7 +213,7 @@ function build(state, at) {
158
213
  // observed, nor for a machine that is not live and has no row kept. Each has only its reason.
159
214
  const observed = panel !== null && !gone && (local ? status === "observed" : live || instances.length > 0);
160
215
  return {
161
- panel, gone, instances, deployments, multi, parts, rows, filtering, stale, section, live, observed,
216
+ panel, gone, instances, ordered, deployments, multi, parts, rows, filtering, stale, section, live, observed, folded,
162
217
  below: waitingRollup(instances, state.collapsed, state.open, { filtering, stale, section }),
163
218
  status,
164
219
  workspace: text(panel?.workspace?.name) ? panel.workspace.name : "",
@@ -173,11 +228,7 @@ function build(state, at) {
173
228
  ...Object.entries(counted).slice(1).map(([word, n]) => ({ n, word, shared: true })),
174
229
  { n: withheld, word: "withheld", shared: false },
175
230
  ].filter((count) => count.n > 0),
176
- // The time of the read the screen shows: the cycle's own (`generatedAt`), never
177
- // `observedAt`, which is when the kernel last looked at the workspace's remotes and is up
178
- // to a minute older on a read in the background. Nothing drawn here comes from the remotes.
179
- // In a view whose primary is a machine it is the time of the last roster read (heldOf).
180
- readAt: live ? clockTime(panel.generatedAt) : null,
231
+ readAt,
181
232
  // A deployment that is not live says so above the list, with why. Before the first answer
182
233
  // the list holds the TUI's own line instead: the shared sentence for that moment names an
183
234
  // installed CLI, and the TUI runs its own kernel.
@@ -193,7 +244,7 @@ function build(state, at) {
193
244
  empty: status === "pending" ? "reading" : !observed ? null : !instances.length ? "none" : !rows.length ? "nomatch" : null,
194
245
  // As wide as the widest word among all the rows of the list, so the column does not move
195
246
  // while the list scrolls.
196
- wordWidth: Math.min(WORD_MAX, rows.reduce((widest, { row }) => Math.max(widest, textWidth(displayLine(wordOf(row)) ?? "")), 0)),
247
+ wordWidth: Math.min(WORD_MAX, rows.reduce((widest, { row }) => Math.max(widest, textWidth(displayLine(wordOf(row, state.ascii)) ?? "")), 0)),
197
248
  };
198
249
  }
199
250
 
@@ -224,14 +275,14 @@ function flatten(base, cols, ascii) {
224
275
  * from read it again without asking the shared home again (its grouping walks the whole roster
225
276
  * for each row). The state's values are never changed in place, so their identity says whether
226
277
  * they changed. The flattening for the last width asked is kept beside it. */
227
- const MADE_FROM = ["entries", "remote", "memory", "notes", "rosterAt", "collecting", "ctxs", "open", "collapsed", "cli", "home"];
278
+ const MADE_FROM = ["entries", "remote", "memory", "notes", "rosterAt", "collecting", "ctxs", "open", "collapsed", "cli", "home", "retiring", "ascii"];
228
279
  let kept = null;
229
280
  /** The roster of a state: the rows in drawn order and what the header says, for a list pane
230
281
  * `cols` wide. Only `items` and `index` depend on the width; `rows`, the instances in drawn
231
282
  * order, do not. `at` stamps a machine's panel before any roster outcome was taken, which
232
283
  * never shows; it is passed on. */
233
284
  export function roster(state, at = new Date(0).toISOString(), cols = ANY_WIDTH) {
234
- const same = kept && MADE_FROM.every((name) => kept.state[name] === state[name]) && kept.state.filter.query === state.filter.query;
285
+ const same = kept && MADE_FROM.every((name) => kept.state[name] === state[name]) && kept.state.filter.query === state.filter.query && kept.state.filter.soul === state.filter.soul;
235
286
  if (!same) kept = { state, base: build(state, at), flat: null };
236
287
  if (!kept.flat || kept.flat.cols !== cols || kept.flat.ascii !== state.ascii) kept.flat = { cols, ascii: state.ascii, ...flatten(kept.base, cols, state.ascii) };
237
288
  return { ...kept.base, items: kept.flat.items, index: kept.flat.index };
@@ -244,13 +295,18 @@ export function disclosure(state, r, item) {
244
295
  return !r.filtering && state.collapsed.has(collapseKey(state.open, item.id)) ? "closed" : "open";
245
296
  }
246
297
 
298
+ /** One row of the list: its mark, its name, the word its mark cannot say (or null), whether it
299
+ * waits, and on a folded row only, how many instances are folded away under it (`folded`) and how
300
+ * many of those wait (`below`). A row that is not folded says nothing of its children: they
301
+ * stand under it, indented. */
247
302
  function listRow(state, r, item) {
248
- const fold = disclosure(state, r, item);
303
+ const closed = disclosure(state, r, item) === "closed";
249
304
  return {
250
305
  id: item.id, name: item.row.instance, depth: item.depth, selected: item.id === state.selected,
251
- disclosure: fold, mark: markOf(item.row), word: wordOf(item.row),
306
+ mark: markOf(item.row), word: wordOf(item.row, state.ascii),
252
307
  waiting: waitingClaim(item.row, { stale: r.stale(item.row) }) !== null,
253
- below: fold === "closed" ? r.below.get(item.id)?.length ?? 0 : 0,
308
+ folded: closed ? r.folded.get(item.id) ?? 0 : 0,
309
+ below: closed ? r.below.get(item.id)?.length ?? 0 : 0,
254
310
  };
255
311
  }
256
312
 
@@ -288,12 +344,31 @@ export const OPEN_WORDS = Object.freeze({
288
344
  notRunning: (name) => [{ shown: name }, { own: " is not running, so it has no terminal to open." }],
289
345
  stateUnknown: (name) => [{ own: "Whether " }, { shown: name }, { own: " runs is not known, so it is not opened." }],
290
346
  });
291
- /** The line of a view that is not in this version (its key: 2, 3), with what to run instead: the
292
- * help's commands (views/help.mjs VIEWS), in the TUI's own words. */
293
- export const NOT_BUILT = Object.freeze({
294
- souls: Object.freeze({ said: Object.freeze([{ own: "Souls are not in this version: `oats souls` lists them, and `oats spawn <soul>` makes an instance of one." }]), under: Object.freeze([]) }),
295
- capabilities: Object.freeze({ said: Object.freeze([{ own: "Capabilities are not in this version: `oats capabilities` lists them." }]), under: Object.freeze([]) }),
347
+ /** The tabs' own words (docs/tui.md, "Tabs"): at the cap, how many are open and the leader's key
348
+ * that closes the shown one. */
349
+ const LEADER_CLOSE = LEADER.find((entry) => entry.does === "close-terminal").keys[0];
350
+ export const TAB_WORDS = Object.freeze({
351
+ full: (limit, leader) => [{ own: `${limit} terminals are open; close one with ` }, { own: `${leader} ${keyLabel(LEADER_CLOSE)}`, whole: true }, { own: "." }],
352
+ });
353
+ /** The lines of a split that is not made (docs/tui.md, "Splits"): a second split, and a panel too
354
+ * small for two groups (`min` views/split.mjs SPLIT_MIN). */
355
+ export const SPLIT_WORDS = Object.freeze({
356
+ twice: () => [{ own: "The panel has two groups already." }],
357
+ small: (dir, min) => [{ own: dir === "right" ? `No room to split side by side: each group needs ${min.cols} columns.` : `No room to split one above the other: each group needs ${min.rows} rows.` }],
296
358
  });
359
+ /** The groups of the panel as the frame draws them (docs/tui.md, "Splits"): one, or two with a
360
+ * split, each `{ tabs, shown }`: its tabs in the strip's order (`{ id, name, machine, routed,
361
+ * shown, activity }`, `machine` only for another machine's) and its shown tab's id, or null for
362
+ * an empty group. */
363
+ function groupsOf(state) {
364
+ return Array.from({ length: state.split === null ? 1 : 2 }, (_, g) => {
365
+ const shown = g === state.group ? state.terminal?.id ?? null : state.aside;
366
+ const tabs = state.tabs.filter((tab) => tab.group === g).map((tab) => ({ id: tab.id, name: tab.name, machine: tab.routed ? tab.machine : null, routed: tab.routed, shown: tab.id === shown, activity: tab.activity }));
367
+ return { tabs, shown };
368
+ });
369
+ }
370
+ /** A command in a line of the TUI's own: whole, never broken over two rows. */
371
+ const command = (text) => Object.freeze({ own: `\`${text}\``, whole: true });
297
372
  /** A sentence from outside (a reason of the shared home's, the preflight table's), as a text
298
373
  * under the line: drawn as the detail draws a reason, wrapped on the reason's rows, never as one
299
374
  * unbroken part (a part is a name). */
@@ -384,7 +459,7 @@ function detailOf(state, r, item, now, acts) {
384
459
  const said = of ? deploymentState(of) : null;
385
460
  if (said && said.key !== "live") add("", said.detail, "wrap");
386
461
  }
387
- add("state", heldHome(row)?.state ?? stateWord(row)); // the word of its list row, harness apart
462
+ add("state", detailState(row, state.ascii));
388
463
  const held = acts.blocked ?? acts.limited;
389
464
  // The row's own text stands under its state, in the form that says who made it. Who made it is
390
465
  // the shared home's to say, in two ways, and the TUI writes no word and no sentence of its own
@@ -399,10 +474,12 @@ function detailOf(state, r, item, now, acts) {
399
474
  // in front never change the answer; a closing quotation mark can, for a text that ends in a
400
475
  // secret's name and its sign, and that text is then withheld.)
401
476
  add("", rowText(row, acts), "wrap");
402
- // What holds the row, when that is a sentence of the shared home's and not the row's text: a
403
- // reason with an `origin` is the row's text, and so is one whose sentence is that text. Either
404
- // stands once, under the state.
405
- if (held && held.origin === undefined && held.sentence !== row.runtimeError) add("held", held.sentence, "wrap");
477
+ // What holds the row, when that is not the row's text, said as `spoken` says it. A held home's
478
+ // reason (code `held`) is never the row's text: the shared home's sentence, or a failed retire's
479
+ // words of the kernel's (#1247), whose speaker `spoken` names. Any other reason is the row's text
480
+ // when it carries an `origin`, or when its sentence is that text: either stands once, under the state.
481
+ const own = held && (held.code === "held" || (held.origin === undefined && held.sentence !== row.runtimeError));
482
+ if (own) add("held", reasonSpoken(held), "wrap");
406
483
  const claim = waitingClaim(row, { stale: r.stale(row) });
407
484
  if (claim) {
408
485
  add("needs", `${waitingLabel(claim)}, ${waitedText(claim.since, now)}`);
@@ -458,6 +535,93 @@ export function switcher(state, at = new Date(0).toISOString()) {
458
535
  };
459
536
  }
460
537
 
538
+ /** The palette's views and commands, each a row's label and the action it runs. */
539
+ const PALETTE_VIEWS = Object.freeze([["instances", "Instances"], ["souls", "Souls"], ["capabilities", "Capabilities"]]);
540
+ const PALETTE_COMMANDS = Object.freeze([["spawn", "Spawn an agent"], ["workspaces", "Workspaces"], ["refresh", "Refresh"], ["help", "Help"]]);
541
+ const PALETTE_SPLIT = Object.freeze({
542
+ one: Object.freeze([["split-right", "Split right"], ["split-down", "Split down"]]),
543
+ shown: Object.freeze([["tab-move", "Move tab to the other group"]]),
544
+ empty: Object.freeze([["group-close", "Close the empty group"]]),
545
+ });
546
+ const PALETTE_ACTS = Object.freeze({ stop: "Stop", restart: "Restart", retire: "Retire", start: "Start" });
547
+
548
+ /** THE PALETTE'S ROWS (docs/tui.md, "The palette"), in this order: the instances that can be
549
+ * opened (the most recently opened in this run first, then the shared order), the souls of the
550
+ * open workspace once its catalog was read, its capabilities once theirs was, the views, the acts
551
+ * the palette's instance offers (the open terminal's, when the palette came from its focus; else
552
+ * the selected one) and, once the catalog lists its soul, another of that soul, then spawning an
553
+ * agent, workspaces, refresh and help, and the split's that apply. With a query, each group keeps the rows the
554
+ * Desktop's subsequence score matches, the best first (a prefix first); a tie keeps that order.
555
+ * A row: `{ key, kind, label, does?, id?, name?, machine?, mark?, capability?, source? }`; `selected` is the key the
556
+ * selection stands on (the first row when the palette's own is not listed). */
557
+ export function paletteItems(state, at = new Date(0).toISOString()) {
558
+ const p = state.palette;
559
+ if (p === null) return { items: [], selected: null };
560
+ const groups = [];
561
+ if (state.open !== null) {
562
+ const r = roster(state, at);
563
+ const recent = new Map(state.recent.map((id, i) => [id, i]));
564
+ const rank = (row) => recent.get(instanceId(row)) ?? Infinity;
565
+ const openable = r.ordered.filter((row) => openDecision(state, row, instanceActs(row)).open);
566
+ groups.push(openable.map((row, i) => ({ row, i })).sort((a, b) => rank(a.row) - rank(b.row) || a.i - b.i).map(({ row }) => {
567
+ const machine = elsewhere(row) ? row.deployment?.machine ?? row.server : null;
568
+ return { key: `instance\u0000${instanceId(row)}`, kind: "instance", label: row.instance, id: instanceId(row), name: row.instance, machine, mark: markOf(row), text: `${row.instance} ${machine ?? ""}` };
569
+ }));
570
+ }
571
+ // The souls of the open workspace, once its catalog was read (the Souls view opened): choosing
572
+ // one shows the Souls view with it selected. A palette never reads the catalog.
573
+ groups.push(soulsOf(state).all.map((row) => ({ key: `soul\u0000${row.name}`, kind: "soul", label: row.name, name: row.name, text: row.name })));
574
+ // The capabilities of the open workspace, once its catalog was read (the Capabilities view opened):
575
+ // choosing one shows that view with it selected. Each says where it comes from (a package's and a
576
+ // member's may share a name).
577
+ const c = capabilitiesOf(state), names = memberNames(c.status);
578
+ groups.push(c.all.map((row) => {
579
+ const capability = capabilityKey(row, names);
580
+ return { key: `capability\u0000${capability}`, kind: "capability", label: row.name, name: row.name, capability, source: capabilitySource(row, names).label, text: row.name };
581
+ }));
582
+ groups.push(PALETTE_VIEWS.map(([does, label]) => ({ key: `view\u0000${does}`, kind: "view", label, does, text: label })));
583
+ const id = p.from === "terminal" && state.terminal !== null ? state.terminal.id : state.selected;
584
+ const row = id === null || state.open === null ? null : roster(state, at).instances.find((each) => instanceId(each) === id) ?? null;
585
+ if (row !== null && state.opening === null) {
586
+ const acts = instanceActs(row);
587
+ const another = !elsewhere(row) && state.ctxs.includes(state.open) ? soulOfAgent(state, state.open, row.agent) : null;
588
+ groups.push([
589
+ ...ACT_VERBS.filter((verb) => actDecision(state, row, acts, verb).open)
590
+ .map((verb) => ({ key: `act\u0000${verb}`, kind: "act", label: PALETTE_ACTS[verb], does: verb, id: instanceId(row), name: row.instance, text: `${PALETTE_ACTS[verb]} ${row.instance}` })),
591
+ // Another of its soul (N), once the catalog lists that soul: the row names the soul.
592
+ ...(another ? [{ key: "act\u0000spawn-another", kind: "act", label: "Spawn another", does: "spawn-another", id: instanceId(row), name: another.name, text: `Spawn another ${another.name}` }] : []),
593
+ ]);
594
+ }
595
+ // The split's, after them, where each applies (docs/tui.md, "Splits"): a split while there is one
596
+ // group, and with two the move of the shown tab, or the close of the focused group while it is
597
+ // empty. A split there is no room for says so when it is run.
598
+ const splitting = state.tabs.length > 0 && state.opening === null && !state.tabs.some((tab) => tab.status === "starting");
599
+ const SPLIT = splitting ? (state.split === null ? PALETTE_SPLIT.one : state.terminal !== null ? PALETTE_SPLIT.shown : PALETTE_SPLIT.empty) : [];
600
+ groups.push([...PALETTE_COMMANDS, ...SPLIT].map(([does, label]) => ({ key: `command\u0000${does}`, kind: "command", label, does, text: label })));
601
+ const query = p.query.trim();
602
+ const items = groups.flatMap((group) => (query === ""
603
+ ? group
604
+ : group.map((item, i) => ({ item, i, score: subsequenceScore(item.text, query) })).filter((each) => each.score !== null).sort((a, b) => a.score - b.score || a.i - b.i).map(({ item }) => item)));
605
+ // With nothing chosen yet, the first row; but in the palette as it opens (no query), when the
606
+ // first row is the shown tab's instance (the most recent), the second instance: the palette and
607
+ // Enter go back to the terminal before it, as the Desktop's recent group does.
608
+ const first = p.query === "" && items[0]?.kind === "instance" && items[0].id === state.terminal?.id && items[1]?.kind === "instance" ? items[1] : items[0];
609
+ return { items, selected: items.some((item) => item.key === p.selected) ? p.selected : first?.key ?? null };
610
+ }
611
+ /** The palette as the view draws it, in a body `page` rows tall: its query on the first row, and
612
+ * under it the window of its rows that holds the selection (whose last row says what is cut off,
613
+ * when something is: scroll.mjs windowOf keeps it). */
614
+ function paletteView(state, page, at) {
615
+ const list = paletteItems(state, at), height = Math.max(1, page - 1);
616
+ const selected = list.items.findIndex((item) => item.key === list.selected);
617
+ const win = windowOf({ top: 0, count: list.items.length, height, keep: selected });
618
+ return {
619
+ query: state.palette.query, from: state.palette.from,
620
+ rows: list.items.slice(win.top, win.top + win.size).map((item) => ({ ...item, selected: item.key === list.selected })),
621
+ above: win.above, below: win.below, empty: list.items.length === 0,
622
+ };
623
+ }
624
+
461
625
  /** What the views draw for a state. For the Instances view, in a list pane `page` rows tall and
462
626
  * `cols` wide: the header's facts, the rows of the window with their marks, and the selected
463
627
  * instance's detail. For the switcher, in a pane `page` rows tall: the window of its rows. Only
@@ -465,12 +629,26 @@ export function switcher(state, at = new Date(0).toISOString()) {
465
629
  export function model(state, { page, now, at, cols }) {
466
630
  const r = roster(state, at, cols);
467
631
  const common = {
468
- view: state.view, focus: state.focus, ascii: state.ascii, actions: state.actions, filter: state.filter,
632
+ view: state.view, focus: state.focus, ascii: state.ascii, actions: state.actions,
633
+ // The filter of the view shown: the Souls view has one of its own.
634
+ filter: state.view === "souls" ? state.souls.filter : state.view === "capabilities" ? state.capabilities.filter : state.filter,
469
635
  workspace: r.workspace, machines: r.machines, here: r.here, machine: r.machine, counts: r.counts, readAt: r.readAt, notice: r.notice, note: r.note, empty: r.empty, observed: r.observed,
470
636
  detailTop: state.detailTop, helpTop: state.helpTop, open: state.open !== null,
471
- detachKey: state.detachKey, opening: state.opening, outcome: state.outcome, openable: false, actable: [],
637
+ detachKey: state.detachKey, opening: state.opening, openable: false, actable: [],
472
638
  terminal: state.terminal, onTerminal: false,
639
+ // The panel's groups (views/frame.mjs), the split and the focused group; the panel stands while
640
+ // any tab is open. `tabs` is the focused group's strip: each tab in order, the shown one marked,
641
+ // a hidden one's activity. A strip is drawn with two tabs or more; one reads as a title row.
642
+ split: state.split, group: state.group, panelOpen: state.tabs.length > 0, groups: groupsOf(state),
643
+ tabs: groupsOf(state)[state.group].tabs,
473
644
  act: state.view === "act" && state.act ? actView(state) : null,
645
+ // The leader waits for its key (the footer is its hint), and the palette, while it is open.
646
+ leader: state.leader?.waiting === true, palette: state.palette === null ? null : paletteView(state, page, at),
647
+ souls: state.view === "souls" ? soulsView(state, page, at) : null,
648
+ capabilities: state.view === "capabilities" ? capabilitiesView(state, page, at) : null,
649
+ spawn: state.spawn === null ? null : spawnView(state, page, at),
650
+ // The line above the panes: the last outcome, else a spawn under way (outcomeOf).
651
+ outcome: outcomeOf(state),
474
652
  };
475
653
  // The view under the help, or under a confirmation, decides what the header says.
476
654
  const under = state.view === "help" || state.view === "act" ? state.back : state.view;
@@ -506,8 +684,9 @@ export function model(state, { page, now, at, cols }) {
506
684
  openable: decision?.open === true && state.opening === null,
507
685
  onTerminal: row !== null && state.terminal !== null && state.terminal.id === instanceId(row),
508
686
  // The acts whose key opens a confirmation now, read from the same instanceActs answer: the
509
- // footer names them. A key not named still answers, with the line that says why.
510
- actable: row && state.opening === null ? ACT_VERBS.filter((verb) => actDecision(state, row, acts, verb).open) : [],
687
+ // footer names them. A key not named still answers, with the line that says why. A secondary
688
+ // act (Retire while a retire runs) opens on its key and is not named.
689
+ actable: row && state.opening === null ? ACT_VERBS.filter((verb) => !acts.acts.some((each) => each.verb === verb && each.secondary) && actDecision(state, row, acts, verb).open) : [],
511
690
  switcher: null,
512
691
  };
513
692
  }
@@ -696,3 +875,381 @@ export function actView(state) {
696
875
  const buttons = a.offers.map((offer) => ({ id: offer, label: buttonLabel(offer, a.verb, a.phase), focused: offer === a.focus }));
697
876
  return { title, lines, buttons, top: a.top };
698
877
  }
878
+
879
+ // ── THE SOULS VIEW (docs/tui.md, "The Souls view") ───────────────────────────────────────────────
880
+
881
+ /** The names an instance's soul (its row's `agent`) may carry for a soul row: its name, and for a
882
+ * package soul the kernel's key, its qualified name and its name in the roster, `<package>--<soul>`
883
+ * (the shared rosterAgentName: the agent directory a package soul's instances are made under). The
884
+ * exact soul filter, the count of a soul's instances and "Used by" match these. */
885
+ export function soulNames(row) {
886
+ return [...new Set([row.name, row.key, row.qualifiedName, rosterAgentName(row)].filter(text))];
887
+ }
888
+
889
+ /** The souls of the open workspace as the store and the view read them: the shared rows
890
+ * (soul-rows.mjs soulRows) of the catalog the loop holds for it, filtered by the view's own
891
+ * filter. Only a workspace of this machine has souls here (`local`). `held` is what the loop
892
+ * holds of its catalog (`{ entry, reading }`), `rows` the rows the filter keeps, `selected` the
893
+ * row the selection stands on: the store's, while it is listed, else the first. */
894
+ export function soulsOf(state) {
895
+ const { local, deployment, held, all } = catalogOf(state, state.open);
896
+ // The Souls view's filter is the Desktop's soul grid's (soulMatches), on the trimmed text.
897
+ const query = state.souls.filter.query.trim();
898
+ const rows = query ? all.filter((row) => soulMatches(row, query)) : all;
899
+ const selected = rows.find((row) => row.name === state.souls.selected) ?? rows[0] ?? null;
900
+ return { local, deployment, held, all, rows, selected };
901
+ }
902
+
903
+ /** The souls of workspace `id` (one of this machine's, or nothing): its observed deployment, what
904
+ * the loop holds of its catalog, and the shared rows of that catalog. */
905
+ function catalogOf(state, id) {
906
+ const local = id !== null && state.ctxs.includes(id);
907
+ const entry = local ? state.entries.get(id) ?? null : null;
908
+ const deployment = entry?.deployment?.status === "observed" ? entry.deployment : null;
909
+ const held = local ? state.souls.held.get(id) ?? null : null;
910
+ const all = deployment && Array.isArray(held?.entry?.souls) ? soulRows(deployment, held.entry.souls) : [];
911
+ return { local, deployment, held, all };
912
+ }
913
+
914
+ /** The most instances the detail names; the rest are counted, `+n`. */
915
+ const INSTANCES_NAMED = 8;
916
+
917
+ /** This machine's instances of a soul in the open workspace, in the list's order: the rows of
918
+ * another machine are not counted, since the view is of this machine's souls. */
919
+ function instancesOf(state, at, row) {
920
+ const names = soulNames(row);
921
+ return roster(state, at).ordered.filter((each) => !elsewhere(each) && names.includes(each.agent));
922
+ }
923
+
924
+ /** Where a soul comes from, in one value: the member it is in, and for a package soul the package
925
+ * and its version (the shared row's `repoName` already names the package when no member does). */
926
+ function soulFrom(row) {
927
+ if (row.soulKind !== "package" || !text(row.package)) return row.repoName;
928
+ const pkg = `package ${row.package}${text(row.version) ? ` ${row.version}` : ""}`;
929
+ return row.repoName === `package ${row.package}` || !text(row.repoName) ? pkg : `${row.repoName} · ${pkg}`;
930
+ }
931
+
932
+ /** The selected soul's detail, from its row and the shared facts (soul-facts.mjs soulFacts, with
933
+ * no inspection): nothing of a soul is worded here but the labels the view puts beside them. */
934
+ function soulDetail(state, at, row) {
935
+ const facts = soulFacts(row, null, state.cli, TERMS);
936
+ const teams = Array.isArray(row.teams) && row.teams.length
937
+ ? [...row.teams].sort((a, b) => (b.default === true) - (a.default === true)).map((team) => ({ label: team.label, default: team.default === true || team.label === row.defaultTeam?.label }))
938
+ : null;
939
+ const capabilities = Array.isArray(row.capabilities) && row.capabilities.length ? row.capabilities.map((c) => c.name) : null;
940
+ const here = instancesOf(state, at, row);
941
+ return {
942
+ name: row.name, description: row.description ?? "", from: soulFrom(row), works: facts.work, refusal: facts.refusalLine,
943
+ harness: { rows: facts.rows, notes: facts.notes, problem: facts.problem },
944
+ teams, capabilities,
945
+ instances: { shown: here.slice(0, INSTANCES_NAMED).map((each) => ({ name: each.instance, mark: markOf(each) })), more: Math.max(0, here.length - INSTANCES_NAMED) },
946
+ };
947
+ }
948
+
949
+ /** What the Souls view draws, in a list pane `page` rows tall (views/souls.mjs): the state of the
950
+ * catalog, the window of its rows, and the selected soul's detail. A failed re-read keeps the
951
+ * rows it held, and says so on a heading above them, as a machine's heading says it. */
952
+ function soulsView(state, page, at) {
953
+ const s = soulsOf(state), v = state.souls;
954
+ const base = { local: s.local, failure: null, heading: null, list: [], above: 0, below: 0, focus: v.focus, filter: v.filter, detail: null, detailTop: v.detailTop };
955
+ if (!s.local) return { ...base, state: "none" };
956
+ const entry = s.held?.entry ?? null, reason = entry?.reason ?? null;
957
+ if (!Array.isArray(entry?.souls)) {
958
+ // Nothing held: the first read is in flight (or the deployment not read yet), or it failed.
959
+ return reason && !s.held.reading ? { ...base, state: "failed", failure: soulCatalogFailure(reason) } : { ...base, state: "reading" };
960
+ }
961
+ const heading = reason ? { label: "Souls", path: null, state: null, short: soulCatalogFailure(reason), readAt: clockTime(entry.observedAt) } : null;
962
+ const state_ = !s.all.length ? "none" : !s.rows.length ? "nomatch" : "rows";
963
+ const height = Math.max(1, page - (heading ? 1 : 0));
964
+ const at_ = s.selected ? s.rows.indexOf(s.selected) : -1;
965
+ const win = windowOf({ top: v.top, count: s.rows.length, height, keep: v.loose ? -1 : at_ });
966
+ const count = (row) => instancesOf(state, at, row).length;
967
+ return {
968
+ ...base, state: state_, heading,
969
+ list: s.rows.slice(win.top, win.top + win.size).map((row) => ({
970
+ name: row.name, color: SOUL_COLOURS[row.color] ?? null, count: count(row), refused: spawnRefusal(row, state.cli) !== null, selected: row === s.selected,
971
+ })),
972
+ above: win.above, below: win.below,
973
+ // The heading has room for little of a failed re-read's sentence: the detail holds it whole,
974
+ // as a machine's full reason stands in the detail of each of its rows.
975
+ detail: s.selected ? { ...soulDetail(state, at, s.selected), failure: heading ? heading.short : null } : null,
976
+ };
977
+ }
978
+
979
+ // ── THE CAPABILITIES VIEW (docs/tui.md, "The Capabilities view"; Spec 7) ──────────────────────────
980
+
981
+ /** A capability's identity in the view: its source's key and its name, since a package's capability
982
+ * and a member's may share a name (Spec 7, Settled 8). */
983
+ export const capabilityKey = (row, names) => `${capabilitySource(row, names).key}\u0000${row.name}`;
984
+
985
+ /** The view's sections, in the order they stand (the Desktop's): Workspace owned, Repo owned, Packages. */
986
+ const SECTION_ORDER = Object.freeze(["workspace", "repo", "packages"]);
987
+
988
+ /** The capabilities of the open workspace as the store and the view read them: the rows of the
989
+ * catalog the loop holds for it (`held`, `{ entry, reading }`), filtered by the view's own filter
990
+ * (the shared matchCapabilities), in the shared sections (capabilitySections) and groups
991
+ * (groupCapabilities), as `items` in drawn order: `{ section }` (a section's heading), `{ group, note }`
992
+ * (a repository's or a package's), and `{ key, row }` (a capability). A section or a group with no
993
+ * row is not listed. `keys` are the capabilities in order, `selected` the key the selection stands
994
+ * on (the store's while it is listed, else the first) and `row` its row; `heading` whether a failed
995
+ * re-read's heading stands above the rows. Only a workspace of this machine has them (`local`). */
996
+ export function capabilitiesOf(state) {
997
+ const id = state.open, local = id !== null && state.ctxs.includes(id);
998
+ const entry = local ? state.entries.get(id) ?? null : null;
999
+ const deployment = entry?.deployment?.status === "observed" ? entry.deployment : null;
1000
+ const held = local ? state.capabilities.held.get(id) ?? null : null;
1001
+ const status = deployment?.workspaceStatus ?? null;
1002
+ const listed = deployment !== null && Array.isArray(held?.entry?.capabilities?.capabilities);
1003
+ const all = listed ? held.entry.capabilities.capabilities : [];
1004
+ const names = memberNames(status), hostKey = hostKeyOf(status);
1005
+ const sections = capabilitySections(matchCapabilities(all, state.capabilities.filter.query));
1006
+ const items = [];
1007
+ for (const section of SECTION_ORDER) {
1008
+ if (!sections[section].length) continue;
1009
+ items.push({ section });
1010
+ for (const group of groupCapabilities(sections[section], names, hostKey)) {
1011
+ items.push({ group: group.name, note: group.note });
1012
+ for (const row of group.rows) items.push({ key: capabilityKey(row, names), row });
1013
+ }
1014
+ }
1015
+ const keys = items.filter((item) => item.key !== undefined).map((item) => item.key);
1016
+ const selected = keys.includes(state.capabilities.selected) ? state.capabilities.selected : keys[0] ?? null;
1017
+ const row = selected === null ? null : items.find((item) => item.key === selected).row;
1018
+ return { local, deployment, status, held, listed, all, items, keys, selected, row, heading: listed && Boolean(held.entry.reason) };
1019
+ }
1020
+ /** The rows the list of capabilities has in a pane `page` rows tall: a failed re-read's heading takes one. */
1021
+ export const capabilitiesHeight = (c, page) => Math.max(1, page - (c.heading ? 1 : 0));
1022
+
1023
+ /** "Used by" of capability `row` (capability-rows.mjs capabilityUsers): with the kernel's
1024
+ * souls-capabilities, the souls of the open workspace's catalog whose composition includes it; before
1025
+ * it, the souls whose instances carry it. `instances` are this machine's rows of the open workspace.
1026
+ * Each user is drawn by its catalog row (soulOfAgent maps an instance's agent name to it): its name
1027
+ * and colour, and the soul Enter shows in the Souls view (`soul`, null when no row matches); `count`
1028
+ * its instances carrying the capability, and `behind` the shared words for those on an older
1029
+ * version, or null. Until the souls catalog is read the souls are not known (`reading`, or `failed`
1030
+ * with its sentence): nothing claims that no soul includes it. */
1031
+ export function capabilityUsersOf(state, at, row) {
1032
+ const composition = soulsComposition(state.cli), souls = catalogOf(state, state.open), entry = souls.held?.entry ?? null;
1033
+ const none = { shown: [], more: 0, count: null, empty: null, failure: null };
1034
+ if (composition && !Array.isArray(entry?.souls)) return { ...none, state: entry?.reason && !souls.held.reading ? "failed" : "reading", failure: entry?.reason && !souls.held.reading ? soulCatalogFailure(entry.reason) : null };
1035
+ const instances = roster(state, at).ordered.filter((each) => !elsewhere(each) && each.deployment?.id === state.open);
1036
+ const users = capabilityUsers(row, { souls: souls.all, instances, composition }).map(({ soul, carrying, behind }) => {
1037
+ const found = composition ? soul : soulOfAgent(state, state.open, soul.name);
1038
+ return { name: found?.name ?? soul.name, color: found ? SOUL_COLOURS[found.color] ?? null : null, count: carrying.length, behind: behind > 0 ? CAPABILITY_COPY.behind(behind) : null, soul: found?.name ?? null };
1039
+ });
1040
+ return {
1041
+ ...none, state: "known", shown: users.slice(0, INSTANCES_NAMED), more: Math.max(0, users.length - INSTANCES_NAMED), count: CAPABILITY_COPY.souls(users.length),
1042
+ empty: users.length ? null : composition ? CAPABILITY_COPY.noSoul : CAPABILITY_COPY.noInstance,
1043
+ };
1044
+ }
1045
+
1046
+ /** The selected capability's detail, from its row and the shared facts (capability-facts.mjs
1047
+ * capabilityFacts) in the shared words (CAPABILITY_COPY): nothing of a capability is worded here. A
1048
+ * kind of Provides the kernel could not list (`names` null) says CAPABILITY_COPY.unlistable, and one
1049
+ * with no name CAPABILITY_COPY.none. `comesFrom` holds the facts' "Comes from" rows as `{ label,
1050
+ * value }`, the shortened value (not `origin`: in this package that names a reason's speaker, which
1051
+ * test/tui-boundary.test.mjs holds to originLead). */
1052
+ function capabilityDetail(state, at, c) {
1053
+ const row = c.row, { origin, provides } = capabilityFacts(row, { status: c.status });
1054
+ return {
1055
+ name: row.name, layer: text(row.layer) ? layerLabel(row.layer) : null, description: row.description ?? "",
1056
+ words: { comesFrom: CAPABILITY_COPY.comesFrom, provides: CAPABILITY_COPY.provides, usedBy: CAPABILITY_COPY.usedBy },
1057
+ comesFrom: origin.map(([label, value]) => ({ label, value })),
1058
+ provides: provides.map(([label, names]) => ({ label, names: names ?? [], said: names === null ? CAPABILITY_COPY.unlistable : names.length ? null : CAPABILITY_COPY.none })),
1059
+ used: capabilityUsersOf(state, at, row),
1060
+ };
1061
+ }
1062
+
1063
+ /** What the Capabilities view draws, in a list pane `page` rows tall (views/capabilities.mjs): the
1064
+ * state of the catalog, the window of its items, and the selected capability's detail with the soul
1065
+ * of "Used by" that has the detail's mark (`mark`, an index of its listed souls). A failed re-read
1066
+ * keeps the rows it held, under a heading that says so, as the Souls view's does. */
1067
+ function capabilitiesView(state, page, at) {
1068
+ const c = capabilitiesOf(state), v = state.capabilities;
1069
+ const base = { local: c.local, failure: null, heading: null, list: [], above: 0, below: 0, focus: v.focus, filter: v.filter, detail: null, detailTop: v.detailTop, keep: !v.detailLoose, mark: v.mark };
1070
+ if (!c.local) return { ...base, state: "none" };
1071
+ const entry = c.held?.entry ?? null, reason = entry?.reason ?? null;
1072
+ if (!c.listed) return reason && !c.held.reading ? { ...base, state: "failed", failure: catalogFailure("capabilities", reason) } : { ...base, state: "reading" };
1073
+ const heading = c.heading ? { label: "Capabilities", path: null, state: null, short: catalogFailure("capabilities", reason), readAt: clockTime(entry.observedAt) } : null;
1074
+ const state_ = !c.all.length ? "none" : !c.keys.length ? "nomatch" : "rows";
1075
+ const at_ = c.items.findIndex((item) => item.key !== undefined && item.key === c.selected);
1076
+ const win = windowOf({ top: v.top, count: c.items.length, height: capabilitiesHeight(c, page), keep: v.loose ? -1 : at_ });
1077
+ const detail = c.row ? capabilityDetail(state, at, c) : null;
1078
+ return {
1079
+ ...base, state: state_, heading,
1080
+ list: c.items.slice(win.top, win.top + win.size).map((item) => (item.key === undefined ? item
1081
+ : { name: item.row.name, layer: text(item.row.layer) ? layerLabel(item.row.layer) : null, selected: item.key === c.selected })),
1082
+ above: win.above, below: win.below,
1083
+ detail: detail && { ...detail, failure: heading ? heading.short : null },
1084
+ // The mark stands on a listed soul only: the store keeps it inside them.
1085
+ mark: detail && v.focus === "detail" && detail.used.shown.length ? Math.min(v.mark, detail.used.shown.length - 1) : -1,
1086
+ };
1087
+ }
1088
+
1089
+ // ── SPAWNING (docs/tui.md, "Spawning an agent"; Spec 6-spawn) ───────────────────────────────────
1090
+
1091
+ /** A shared sentence as parts the outcome line wraps (views/frame.mjs partRows): each word is
1092
+ * text from outside, and the gaps between them are the TUI's. */
1093
+ const sentenceParts = (text) => String(text ?? "").split(/ +/).filter(Boolean).flatMap((word, i) => (i ? [{ own: " " }, { shown: word }] : [{ shown: word }]));
1094
+ /** The label of the first key the effective table gives action `id`, or the action's id. */
1095
+ const keyOf = (actions, id) => { const a = actions.find((each) => each.id === id && each.keys.length); return a ? keyLabel(a.keys[0]) : id; };
1096
+
1097
+ /** The TUI's own words around a spawn, as parts the way ACT_WORDS are. Every fact of a spawn (what
1098
+ * happened, what the preview holds, why a soul can't be spawned) is the shared home's
1099
+ * (spawn-messages.mjs, spawn-preview-facts.mjs, soul-facts.mjs): the TUI words only what follows a
1100
+ * fact (`next`, naming its own keys), and the prompt around them. */
1101
+ export const SPAWN_WORDS = Object.freeze({
1102
+ /** From the press of Enter until the outcome. */
1103
+ spawning: (name) => [{ own: "Spawning " }, { shown: name }, { own: "\u2026" }],
1104
+ checking: (name) => [{ own: "Checking the spawn of " }, { shown: name }, { own: "\u2026" }],
1105
+ /** n or N while a spawn is under way: one at a time. */
1106
+ busy: (name) => [{ own: "The spawn of " }, { shown: name }, { own: " is still under way: one spawn at a time." }],
1107
+ /** n or N on another machine's row or workspace (#855: remote spawn is out of scope here). */
1108
+ remote: () => [{ own: "Spawning on another machine is not offered here;" }, { own: " " }, command("oats spawn"), { own: " there makes one." }],
1109
+ /** N on a row whose soul the workspace's catalog does not list. */
1110
+ noSoul: (soul) => [{ own: "The soul " }, { shown: soul }, { own: " isn't in this workspace's catalog: there is nothing to spawn." }],
1111
+ });
1112
+
1113
+ /** THE TUI'S WORDS FOR WHAT FOLLOWS A SPAWN'S FACT, one entry per SPAWN_NEXT code
1114
+ * (spawn-messages.mjs): each names a key of the effective table, or an `oats` command
1115
+ * (test/tui-... pins that every code has one). `(instance, actions)` -> parts. */
1116
+ export const SPAWN_NEXT_WORDS = Object.freeze({
1117
+ "change-options": () => [{ own: "Change the choices with Tab and Enter." }],
1118
+ "review-again": () => [{ own: "Check the preview and press Enter again." }],
1119
+ "check-result": (_, actions) => [{ own: `Press ${keyOf(actions, "spawn-check")} to check before spawning again.` }],
1120
+ "update-oats": () => [{ own: "Update OATS with" }, { own: " " }, command("oats update"), { own: ", then try again." }],
1121
+ "choose-workspace": (_, actions) => [{ own: `Choose it again with ${keyOf(actions, "workspaces")}.` }],
1122
+ "sync-workspace": () => [{ own: "Run" }, { own: " " }, command("oats sync"), { own: " in the workspace, then try again." }],
1123
+ details: () => [{ own: "The details below say more." }],
1124
+ retire: (instance, actions) => [{ own: "Retire " }, { shown: instance ?? "it" }, { own: ` with ${keyOf(actions, "retire")} to finish its cleanup.` }],
1125
+ "view-schedules": () => [command("oats schedule list"), { own: " shows its schedules." }],
1126
+ "open-from-list": (_, actions) => [{ own: `Open it from the list with ${keyOf(actions, "open")}.` }],
1127
+ });
1128
+
1129
+ /** A spawn's words as the outcome line (or the prompt's) says them, `{ said, under }`: the shared
1130
+ * fact, then the TUI's words for its `next`; under them the shared `detail` (the code and the
1131
+ * kernel's message) where the next act is to read it. `words`: spawnProblem's or outcomeWords'. */
1132
+ export function spawnLine(words, instance, actions) {
1133
+ if (!words) return null;
1134
+ const next = words.next && Object.hasOwn(SPAWN_NEXT_WORDS, words.next) ? SPAWN_NEXT_WORDS[words.next](words.instance ?? instance, actions) : [];
1135
+ return { said: [...sentenceParts(words.fact), ...(next.length ? [{ own: " " }, ...next] : [])], under: words.next === "details" && words.detail ? [words.detail] : [] };
1136
+ }
1137
+
1138
+ /** The line above the panes: the last outcome; else, while a spawn is under way, what it does. */
1139
+ export function outcomeOf(state) {
1140
+ if (state.outcome !== null) return state.outcome;
1141
+ const s = state.spawning;
1142
+ return s ? { said: (s.phase === "checking" ? SPAWN_WORDS.checking : SPAWN_WORDS.spawning)(s.name), under: [] } : null;
1143
+ }
1144
+
1145
+ /** The choices a prompt asks the preview for: the shared defaults, the name typed (`--purpose`),
1146
+ * and the parent when "child of" is on. Nothing else is offered here (out of scope: harness,
1147
+ * model, work mode, teams). */
1148
+ export function spawnChoices(p) {
1149
+ return {
1150
+ ...defaultSpawnChoices(),
1151
+ ...(p.name ? { purpose: p.name } : {}),
1152
+ ...(p.child && p.anchor ? { relation: { kind: "child", anchor: { instance: p.anchor.instance, agent: p.anchor.agent, agentsRoot: p.anchor.agentsRoot, server: null } } } : {}),
1153
+ };
1154
+ }
1155
+ /** The choices as one value, to tell whether the preview on screen was read for them. */
1156
+ export const spawnChoicesKey = (p) => JSON.stringify(spawnChoices(p));
1157
+ /** The soul a preview is read for, as the shared preview selects it. */
1158
+ export const spawnSelector = (p) => ({ soul: p.soul.name, agentsRoot: p.soul.agentsRoot });
1159
+
1160
+ /** What the spawn boundaries admit a request of workspace `id` against (their `getContext()`),
1161
+ * asked at every admission: the deployment as the shared `deployments` lists it, the kernel
1162
+ * record, its souls (the catalog's shared rows) and its rows now. */
1163
+ export function spawnContext(state, id, at) {
1164
+ const held = heldOf(state, at);
1165
+ const workspace = heldDeployments(held).find((w) => w.id === id) ?? null;
1166
+ return { workspace, cli: state.cli, agents: catalogOf(state, id).all, instances: workspace ? rowsOf(held, id) : [] };
1167
+ }
1168
+
1169
+ /** The soul row of workspace `id` an instance's soul (its row's `agent`) names, or null. */
1170
+ export function soulOfAgent(state, id, agent) {
1171
+ return catalogOf(state, id).all.find((row) => soulNames(row).includes(agent)) ?? null;
1172
+ }
1173
+
1174
+ /** The picker's rows: the souls of the prompt's workspace, filtered by the query with the palette's
1175
+ * subsequence score (the best first, a tie in the catalog's order). `selected` is the soul the
1176
+ * selection stands on: the prompt's, while it is listed, else the first. */
1177
+ export function spawnPickerItems(state) {
1178
+ const p = state.spawn, c = catalogOf(state, p.workspace), query = p.query.trim();
1179
+ const items = (query === "" ? c.all : c.all.map((row, i) => ({ row, i, score: subsequenceScore(row.name, query) })).filter((each) => each.score !== null).sort((a, b) => a.score - b.score || a.i - b.i).map(({ row }) => row))
1180
+ .map((row) => ({ name: row.name, row, refused: spawnRefusal(row, state.cli) !== null }));
1181
+ return { catalog: c, items, selected: items.some((item) => item.name === p.selected) ? p.selected : items[0]?.name ?? null };
1182
+ }
1183
+
1184
+ /** The folded parts a preview's data has, in order: the launch-prompt policy, the capabilities'
1185
+ * warnings and the modules, where it carries them (previewFacts makes `prompts`, `warnings` and
1186
+ * `modules` of exactly these). */
1187
+ const foldKeys = (data) => (data ? [
1188
+ ...(data.launchPromptAnswers ? ["prompts"] : []),
1189
+ ...(Array.isArray(data.warnings) && data.warnings.length ? ["warnings"] : []),
1190
+ ...(Array.isArray(data.modules) ? ["modules"] : []),
1191
+ ] : []);
1192
+ /** Each fold of a preview, one row until opened: the labels and the one-line summaries are the
1193
+ * TUI's; what they fold is the shared facts'. */
1194
+ function spawnFolds(data, facts) {
1195
+ const caps = facts?.modules?.caps.length ?? 0, core = facts?.modules?.core.filter((slot) => slot.module).length ?? 0;
1196
+ const made = {
1197
+ prompts: { label: "Launch prompts", summary: "what the launcher answers for this home" },
1198
+ warnings: { label: "Warnings", summary: `${facts?.warnings.length ?? 0} from its capabilities; they block nothing` },
1199
+ modules: { label: "Modules", summary: `${core} core, ${caps} other capabilit${caps === 1 ? "y" : "ies"}` },
1200
+ };
1201
+ return foldKeys(data).map((key) => ({ key, ...made[key] }));
1202
+ }
1203
+ /** The preview's focus ring, in Tab's order: Spawn, the name, child of (when offered), each fold. */
1204
+ export const spawnRing = (p) => ["spawn", "name", ...(p.anchor ? ["child"] : []), ...foldKeys(p.data).map((key) => `fold:${key}`)];
1205
+
1206
+ /** The row of the instance a spawn created (`arriving`), as the Desktop's spawn jobs find it
1207
+ * (spawn-jobs.mjs `observe`): its workspace's rows holding exactly one of that instance, home,
1208
+ * root and soul, on this machine. Null while there is none. */
1209
+ export function spawnedRow(state, a, at = new Date(0).toISOString()) {
1210
+ const same = rowsOf(heldOf(state, at), a.workspace).filter((row) => row.instance === a.instance && row.home === a.home && row.agentsRoot === a.agentsRoot
1211
+ && (a.agent === null || a.agent === undefined || row.agent === a.agent) && !row.server);
1212
+ return same.length === 1 ? same[0] : null;
1213
+ }
1214
+
1215
+ /** The preview's facts as the shared home words them: the name typed, else the kernel's; where
1216
+ * it runs in the Desktop's words for the deployment (deployment-label.mjs). Null before an answer. */
1217
+ function spawnFacts(state, p, at) {
1218
+ if (!p.data) return null;
1219
+ const workspace = heldDeployments(heldOf(state, at)).find((w) => w.id === p.workspace) ?? null;
1220
+ return previewFacts(p.data, { name: p.name || p.data.instance || null, runsOn: workspace ? deploymentLabel(workspace, TERMS) : null, cli: state.cli });
1221
+ }
1222
+ /** Whether the preview on screen is the one Enter on Spawn would spawn: read, and for the choices shown. */
1223
+ export const spawnReady = (p) => p.step === "preview" && p.status === "shown" && p.data !== null && p.readKey === spawnChoicesKey(p);
1224
+
1225
+ /** The prompt as views/spawn.mjs draws it (that file has the shape), in a body `page` rows tall. */
1226
+ function spawnView(state, page, at) {
1227
+ const p = state.spawn;
1228
+ if (p.step === "picker") {
1229
+ const list = spawnPickerItems(state), c = list.catalog, entry = c.held?.entry ?? null;
1230
+ const height = Math.max(1, page - 2), at_ = list.items.findIndex((item) => item.name === list.selected);
1231
+ const win = windowOf({ top: 0, count: list.items.length, height, keep: at_ });
1232
+ const reading = !Array.isArray(entry?.souls), failed = reading && entry?.reason && !c.held?.reading;
1233
+ return {
1234
+ step: "picker", query: p.query,
1235
+ rows: list.items.slice(win.top, win.top + win.size).map((item) => ({ name: item.name, refused: item.refused, refusal: item.refused ? soulFacts(item.row, null, state.cli, TERMS).refusalLine : null, selected: item.name === list.selected })),
1236
+ above: win.above, below: win.below,
1237
+ state: failed ? "failed" : reading ? "reading" : !c.all.length ? "none" : !list.items.length ? "nomatch" : "rows",
1238
+ failure: failed ? soulCatalogFailure(entry.reason) : null,
1239
+ };
1240
+ }
1241
+ const facts = spawnFacts(state, p, at), ring = spawnRing(p);
1242
+ const focus = ring.includes(p.focus) ? p.focus : "spawn";
1243
+ const folds = spawnFolds(p.data, facts).map((fold) => ({ ...fold, open: p.folds.includes(fold.key), focused: focus === `fold:${fold.key}` }));
1244
+ const problem = p.problem ?? (p.status === "failed" ? spawnLine(spawnProblem(p.reason, "preview"), p.name || null, state.actions) : null);
1245
+ const ready = spawnReady(p);
1246
+ const enter = focus === "spawn" ? (ready ? "spawn" : p.status === "failed" && p.soul !== null ? "read again" : null)
1247
+ : focus === "name" ? "keep the name"
1248
+ : focus === "child" ? (p.child ? "no parent" : "child of")
1249
+ : folds.find((fold) => fold.focused)?.open ? "close" : "open";
1250
+ return {
1251
+ step: "preview", soul: p.soul?.name ?? null, status: p.status, facts, problem,
1252
+ fields: { name: { text: p.name, focused: focus === "name" }, child: { offered: p.anchor !== null, on: p.child, label: p.anchor?.instance ?? null, focused: focus === "child" } },
1253
+ focus, folds, enter, ready, top: p.top,
1254
+ };
1255
+ }