@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
@@ -1,16 +1,20 @@
1
1
  // `oats tui` (preview): the loop. Events from the keyboard and from the reader go through one
2
2
  // pure reduce(state, event); what only the loop can do comes back as an effect; the frame is
3
3
  // drawn from the state. This version shows a workspace's instances, on this machine and on the
4
- // machines registered here, follows them, opens an agent's terminal in a panel beside the list
5
- // (the kernel's own viewer, in a pane of the run's private tmux server: lib/panel.mjs), and
6
- // stops, starts, restarts and retires an instance after a confirmation, through the shared
7
- // lifecycle boundary and start rule (docs/tui.md).
4
+ // machines registered here, follows them, opens agents' terminals as tabs of a panel beside the
5
+ // list (up to four, each the kernel's own viewer in a pane of the run's private tmux server:
6
+ // lib/panel.mjs; `viewers` maps each tab's instance to its window), in one group or two (a split;
7
+ // after every frame `fitPanel` tells the panel which windows the frame's regions display, at what
8
+ // size, and which has the keys), stops,
9
+ // starts, restarts and retires an instance after a confirmation, through the shared lifecycle
10
+ // boundary and start rule, and spawns an agent on this machine from the shared preview and apply
11
+ // (docs/tui.md).
8
12
  import { homedir } from "node:os";
9
13
  import { resolve } from "node:path";
10
14
  import { bindings } from "./actions.mjs";
11
- import { TERMS, createLifecycleBoundary, createLifecycleConfirmation, displayLine, heldHome, pendingEntry, prepareRemoteTerm, sessionAttachArgv, startInstance } from "./client.mjs";
15
+ import { TERMS, capabilityCatalogKey, createCapabilityCatalog, createLifecycleBoundary, createLifecycleConfirmation, createRetiresInFlight, createSoulCatalog, createSpawnApplyBoundary, createSpawnPreview, createSpawnTransaction, displayLine, heldHome, pendingEntry, prepareRemoteTerm, sessionAttachArgv, soulCatalogKey, startInstance } from "./client.mjs";
12
16
  import { loadConfig } from "./config.mjs";
13
- import { ACT_WORDS, actContext, actCwd, localDeployments, model, roster } from "./model.mjs";
17
+ import { ACT_WORDS, actContext, actCwd, localDeployments, model, outcomeOf, reachedMachines, roster, spawnContext } from "./model.mjs";
14
18
  import { createPanel, sweep } from "./panel.mjs";
15
19
  import { CHANGE_FILES, admitDeployment, createReader, findDeployment, leaveInstance, offeredDeployments, probeKernel, realpath, tellable } from "./read.mjs";
16
20
  import { initialState, reduce } from "./store.mjs";
@@ -20,16 +24,17 @@ import { createScreen, glyphs } from "./term/screen.mjs";
20
24
  import { colorEnabled } from "./term/style.mjs";
21
25
  import { backKeySequences, createThrough } from "./term/through.mjs";
22
26
  import { createGuard, isTerminal } from "./term/tty.mjs";
23
- import { frame, layout } from "./views/frame.mjs";
27
+ import { frame, layout, panelPlace } from "./views/frame.mjs";
24
28
 
25
29
  export const USAGE = "oats tui [--dir <path>] [--ascii]";
26
30
  const HELP = `Usage:
27
31
  ${USAGE}
28
32
 
29
33
  The OATS terminal client (preview): a full-screen view of a workspace's instances,
30
- on this machine and on the machines registered here. It follows them, opens an
31
- agent's terminal beside the list with Enter, and stops, retires, starts or
32
- restarts an instance (X, D, S, R) after a confirmation.
34
+ on this machine and on the machines registered here. It follows them, opens
35
+ agents' terminals beside the list with Enter, as tabs, stops, retires, starts or
36
+ restarts an instance (X, D, S, R) after a confirmation, and spawns an agent
37
+ on this machine (n, or N for another of the selected one's soul).
33
38
  Keys: ? help, Enter open, w workspaces, q quit.
34
39
  docs/tui.md has the rest.
35
40
 
@@ -71,9 +76,36 @@ function errorLines(error) {
71
76
  * are the shared home's, replaceable so a test can drive the loop's wiring. `runDir` makes the
72
77
  * run's private directory (the reader's change output and the panel's tmux server share it), and
73
78
  * `removeDir` removes it on the way out once both have removed their files; `sweep` removes what
74
- * runs that are gone left of theirs (lib/panel.mjs). */
79
+ * runs that are gone left of theirs (lib/panel.mjs). `createSoulCatalog` is the shared home's
80
+ * catalog of a workspace's souls, and `createCapabilityCatalog` its table of capabilities, each
81
+ * replaceable so a test can count its reads; the three spawn
82
+ * factories are the shared home's preview, apply boundary and transaction, replaceable so a test
83
+ * can answer them. */
75
84
  const EFFECTS = Object.freeze({ loadConfig, findDeployment, probeKernel, createReader, offeredDeployments, admitDeployment, prepareRemoteTerm, createPanel, sweep,
76
- runDir: CHANGE_FILES.dir, removeDir: CHANGE_FILES.remove, realpath, tellable, startInstance, createLifecycleConfirmation, createLifecycleBoundary });
85
+ runDir: CHANGE_FILES.dir, removeDir: CHANGE_FILES.remove, realpath, tellable, startInstance, createLifecycleConfirmation, createLifecycleBoundary, createSoulCatalog,
86
+ createCapabilityCatalog, createSpawnPreview, createSpawnApplyBoundary, createSpawnTransaction });
87
+
88
+ /** The timers a run lends the shared spawn: the apply's deadline and its grace (the boundary's
89
+ * `applyTimer`), the boundary's wait for an answer (`timer`) and the transaction's polls
90
+ * (`sleep`). They are the run's: `end()`, as the run ends, clears every one still armed, so a
91
+ * TUI that has gone neither signals a spawn it let go nor is kept alive by one: the spawn
92
+ * finishes, or the kernel's own limits bound it (Spec 6-spawn, Settled 4). `timer(fn, ms)`
93
+ * returns its cancel, as the shared home's timers do. */
94
+ export function createRunTimers({ setTimer, clearTimer }) {
95
+ const armed = new Set();
96
+ let over = false;
97
+ function timer(fn, ms) {
98
+ if (over) return () => {};
99
+ const handle = setTimer(() => { armed.delete(handle); if (!over) fn(); }, ms);
100
+ armed.add(handle);
101
+ return () => { if (armed.delete(handle)) clearTimer(handle); };
102
+ }
103
+ return {
104
+ timer,
105
+ sleep: (ms) => new Promise((resolve) => { timer(resolve, ms); }),
106
+ end() { over = true; for (const handle of armed) clearTimer(handle); armed.clear(); },
107
+ };
108
+ }
77
109
 
78
110
  /** Run. Resolves with the exit status; never calls process.exit, so what was written drains.
79
111
  * Before the alternate screen, in this order, each failure one line on stderr and status 1:
@@ -111,7 +143,8 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
111
143
  let through = createThrough({ sequences: backKey, now }), throughTimer = null;
112
144
  if (offered) state = reduce(state, { offered }, keymap).state;
113
145
  // What the last frame drew, for the store: how tall the list pane is and how far the other
114
- // pane scrolls. The store holds no size of its own.
146
+ // pane scrolls. The store holds no size of its own; the panel's room goes with each key as it
147
+ // is when the key is read (placed), whatever the last frame drew.
115
148
  let drawn = { page: 1, extent: 0, room: 1, cols: 1 };
116
149
  let full = true, escTimer = null, ended = false, reads = 0;
117
150
  /** The preflight of another machine's agent under way: `{ id, controller, prepared }`, where
@@ -123,6 +156,30 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
123
156
  let dir = null;
124
157
  const runDir = () => (dir ??= effects.runDir());
125
158
 
159
+ // THIS RUN'S RETIRES IN FLIGHT (#1247, packages/client retire-in-flight.mjs): a row whose retire
160
+ // this run sent reads Retiring… from the send, before any read says so, until its answer is in
161
+ // and a read begun after that answer covers the row; a refused or stale answer lets it go at once.
162
+ // The mark is the reader's count of cycles begun (lib/read.mjs `begun`), never the clock: the
163
+ // live read a settled answer asks for begins in the same millisecond. The store holds the ids.
164
+ const retires = createRetiresInFlight({ mark: () => reader.begun(), onChange: () => heard({ retiring: retires.ids() }) });
165
+ /** The cycle that began the roster read in flight: lib/read.mjs says `collecting` as it begins one. */
166
+ let rosterBegun = 0;
167
+ /** A served deployment's entry: taken, then, when it is a read the store took (its cycle is the
168
+ * newest of that deployment), it covers that deployment's rows of this machine. A failed read
169
+ * covers nothing, whatever entry it kept. */
170
+ function entered(event) {
171
+ heard(event);
172
+ if (event.read === true && state.numbers.get(event.id) === event.number) retires.landed(event.number, (t) => !t.server && t.workspace === event.id);
173
+ }
174
+ /** An event of the roster read: taken, then an outcome covers the rows of each machine it reached
175
+ * (a read that failed marks every machine not reached, and covers none). */
176
+ function rostered(event) {
177
+ if (event.collecting === true) rosterBegun = reader.begun();
178
+ heard(event);
179
+ if (event.roster === undefined || ended) return;
180
+ const reached = reachedMachines(state, clock());
181
+ if (reached.size) retires.landed(rosterBegun, (t) => !!t.server && reached.has(t.workspace));
182
+ }
126
183
  // What the reader reads for, it asks of the state at that moment: the served deployments, the
127
184
  // entry a failed read keeps, and the roster and the memory the next outcome is made from.
128
185
  const reader = effects.createReader({
@@ -130,24 +187,33 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
130
187
  getServed: () => state.ctxs,
131
188
  getEntry: (id) => state.entries.get(id) ?? null,
132
189
  getRoster: () => ({ remote: state.remote, memory: state.memory, notes: state.notes }),
133
- onEntry: heard, onRoster: heard,
190
+ onEntry: entered, onRoster: rostered,
134
191
  files: { ...CHANGE_FILES, dir: runDir },
135
192
  });
136
- // THE OPEN TERMINAL (docs/tui.md, "Open an agent's terminal"): one at a time, in the panel.
137
- // `viewing` is its viewer, `{ id, panel }` (the row's instanceId, and the panel's own id once
138
- // the window exists, null before); `screenNow` the last capture (`{ lines, cursor }`), drawn
139
- // until the next; `panelSize` and `panelShown` what the panel was last told.
140
- let viewing = null, screenNow = null, panelSize = null, panelShown = true;
193
+ // THE TABS AND THE SPLIT (docs/tui.md, "Tabs", "Splits"): the terminals open in the panel, at
194
+ // most the store's TAB_LIMIT across its groups. `viewers` maps each tab's instanceId to its
195
+ // viewer, `{ id, panel, cols, rows }` (the panel's own id once the window exists, null before,
196
+ // and the size its window was last given); the store holds their groups, their order and which
197
+ // are shown, and after every frame the panel is brought to what the frame drew (fitPanel): the
198
+ // tabs it displays (each group's shown one, as the frame has room for), the one that takes the
199
+ // keys (the focused group's), and each group's size for every tab of it. `screens` is each
200
+ // displayed tab's last capture (`{ lines, cursor }`), drawn until the next; `displayed`, `keysTo`
201
+ // and `panelShown` what the panel was last told.
202
+ const viewers = new Map(), screens = new Map(), displayed = new Set();
203
+ let keysTo = null, panelShown = true;
204
+ const viewerOf = (panelId) => [...viewers.values()].find((each) => each.panel === panelId) ?? null;
141
205
  const panel = effects.createPanel({
142
206
  dir: runDir, env, capture: captureRows,
143
- onScreen: ({ id, screen: lines, cursor }) => { if (!ended && viewing !== null && viewing.panel === id) { screenNow = { lines, cursor }; guard.attempt(() => guard.draw()); } },
144
- // The viewer ended. The store is told, whatever ended it; a terminal the person closed is no
145
- // longer `viewing`, and the store says nothing of it.
207
+ onScreen: ({ id, screen: lines, cursor }) => { const v = viewerOf(id); if (!ended && v !== null && displayed.has(id)) { screens.set(v.id, { lines, cursor }); guard.attempt(() => guard.draw()); } },
208
+ // A hidden tab's agent wrote: its mark.
209
+ onActivity: ({ id }) => { const v = viewerOf(id); if (!ended && v !== null) heard({ activity: { id: v.id } }); },
210
+ // A viewer ended. The store is told, whatever ended it; a tab the person closed is no longer
211
+ // in `viewers`, and the store says nothing of it.
146
212
  onClosed: ({ id, status = null, stderr = "", asked = false }) => {
147
- if (viewing === null || viewing.panel !== id) return;
148
- const row = viewing.id;
149
- viewing = null; screenNow = null;
150
- heard({ returned: { id: row, status, stderr, asked } });
213
+ const v = viewerOf(id);
214
+ if (v === null) return;
215
+ forgetViewer(v);
216
+ heard({ returned: { id: v.id, status, stderr, asked } });
151
217
  },
152
218
  });
153
219
  // THE ACTS (docs/tui.md, "Stopping, starting, restarting and retiring"). One lifecycle boundary
@@ -163,8 +229,155 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
163
229
  /** The confirmation open now: `{ n, made }`, `made` the shared confirmation; or null. */
164
230
  let confirmation = null;
165
231
 
166
- /** What the reader gave, into the state, and the screen after it. */
167
- function heard(event) { if (!ended) guard.attempt(() => { if (!took(reduce(state, event, keymap))) guard.draw(); }); }
232
+ // THE SOULS (docs/tui.md, "The Souls view"): one catalog per run, the shared home's, over the
233
+ // reader's exec: its `oats souls` is a read like any other (kind "read", the reader's time limit,
234
+ // ended on every way out). It is settled for the open workspace with that workspace's own
235
+ // `workspace status`, so it is read only when nothing is held for the workspace as it is now
236
+ // (the shared key), and never before the Souls view was first shown.
237
+ const souls = effects.createSoulCatalog({ terms: TERMS, exec: reader.exec });
238
+ /** The catalog of workspace `id` settled now, and the store told what is held and whether a read
239
+ * is in flight; once that read lands, told again. Nothing for a workspace not read yet: its
240
+ * first observed entry settles it. */
241
+ function settleSouls(id) {
242
+ const deployment = state.entries.get(id)?.deployment;
243
+ if (ended || deployment?.status !== "observed") return;
244
+ // The workspace moved (its catalog's key): what the spawn preview holds of it goes too (Settled 7).
245
+ const key = soulsKeyNow(id);
246
+ if (catalogKeys.has(id) && catalogKeys.get(id) !== key) { try { preview.cache.invalidate(id); } catch { /* never blocks a read */ } }
247
+ catalogKeys.set(id, key);
248
+ let settled;
249
+ try { settled = souls.settle(id, probe.cli, deployment.workspaceStatus); } catch { return; } // the reader has stopped
250
+ const { entry, pending } = settled;
251
+ heard({ souls: { id, entry, reading: pending !== null } });
252
+ // A read lands with its own entry, even one a newer key has since replaced (the shared
253
+ // catalog keeps its held entry from it): only the read of the workspace as it is now is told.
254
+ if (pending) pending.then((landed) => { if (landed?.key === soulsKeyNow(id)) heard({ souls: { id, entry: landed, reading: souls.refreshing(id) } }); }, () => {});
255
+ }
256
+ /** The catalog's key for the workspace as the loop holds it now, or null when it is not observed. */
257
+ function soulsKeyNow(id) {
258
+ const deployment = state.entries.get(id)?.deployment;
259
+ return deployment?.status === "observed" ? soulCatalogKey(probe.cli, deployment.workspaceStatus) : null;
260
+ }
261
+ /** `r` in the Souls view, as `r` in the Capabilities view: one live read, never a second while one
262
+ * is in flight. What is held stays held beside it (the shared catalog's refresh), so a read that
263
+ * fails keeps the last good souls under the failure, as a failed read of the workspace's moved key
264
+ * does. */
265
+ function rereadSouls(id) {
266
+ const deployment = state.entries.get(id)?.deployment;
267
+ if (ended || deployment?.status !== "observed" || souls.refreshing(id)) return;
268
+ let pending;
269
+ try { pending = souls.refresh(id, probe.cli, deployment.workspaceStatus); } catch { return; } // the reader has stopped
270
+ heard({ souls: { id, entry: souls.held(id), reading: true } });
271
+ pending.then((landed) => { if (landed?.key === soulsKeyNow(id)) heard({ souls: { id, entry: landed, reading: souls.refreshing(id) } }); }, () => {});
272
+ }
273
+
274
+ // THE CAPABILITIES (docs/tui.md, "The Capabilities view"; Spec 7): as the souls, one table per run,
275
+ // the shared home's, over the reader's exec (its `oats capabilities` a read of kind "read", ended on
276
+ // every way out), settled for the open workspace with its own `workspace status`, so read only when
277
+ // nothing is held for the workspace as it is now (capabilityCatalogKey), and never before the
278
+ // Capabilities view was first shown. Its "Used by" reads the souls catalog above, settled with it.
279
+ const capabilities = effects.createCapabilityCatalog({ terms: TERMS, exec: reader.exec });
280
+ /** The table of workspace `id` settled now, and the store told what is held and whether a read is
281
+ * in flight; once that read lands, told again, when it is of the workspace as it is now. */
282
+ function settleCapabilities(id) {
283
+ const deployment = state.entries.get(id)?.deployment;
284
+ if (ended || deployment?.status !== "observed") return;
285
+ let settled;
286
+ try { settled = capabilities.settle(id, probe.cli, deployment.workspaceStatus); } catch { return; } // the reader has stopped
287
+ const { entry, pending } = settled;
288
+ heard({ capabilities: { id, entry, reading: pending !== null } });
289
+ if (pending) pending.then((landed) => { if (landed?.key === capabilitiesKeyNow(id)) heard({ capabilities: { id, entry: landed, reading: capabilities.refreshing(id) } }); }, () => {});
290
+ }
291
+ /** The table's key for the workspace as the loop holds it now, or null when it is not observed. */
292
+ function capabilitiesKeyNow(id) {
293
+ const deployment = state.entries.get(id)?.deployment;
294
+ return deployment?.status === "observed" ? capabilityCatalogKey(probe.cli, deployment.workspaceStatus) : null;
295
+ }
296
+ /** `r` in the Capabilities view: one live read, never a second while one is in flight. What is
297
+ * held stays held beside it (the shared catalog's refresh), so a read that fails keeps the last
298
+ * good table under the failure, as a failed read of the workspace's moved key does. */
299
+ function rereadCapabilities(id) {
300
+ const deployment = state.entries.get(id)?.deployment;
301
+ if (ended || deployment?.status !== "observed" || capabilities.refreshing(id)) return;
302
+ let pending;
303
+ try { pending = capabilities.read(id, probe.cli, deployment.workspaceStatus, { refresh: true }); } catch { return; } // the reader has stopped
304
+ heard({ capabilities: { id, entry: capabilities.held(id), reading: true } });
305
+ pending.then((landed) => { if (landed?.key === capabilitiesKeyNow(id)) heard({ capabilities: { id, entry: landed, reading: capabilities.refreshing(id) } }); }, () => {});
306
+ }
307
+
308
+ // THE SPAWN (docs/tui.md, "Spawning an agent"; Spec 6-spawn). One preview, one apply boundary and
309
+ // one transaction per run, the shared home's. The preview's kernel reads are reads (the reader's
310
+ // exec, ended on every way out). The apply is a change (`detached: true`, the shared apply's
311
+ // mark), which the reader never ends on its own: on a kernel without worktree-event it honours
312
+ // the deadline the shared apply gives it (lib/read.mjs changeExec); on one with it, the shared
313
+ // boundary ends it at its deadline through the child returned. `spawnLabel` names the spawn for
314
+ // the line after leaving (one at a time); `job` is the transaction's record of the last spawn,
315
+ // kept for a check (C) in this run only: the TUI keeps nothing on disk. `catalogKeys`: the key
316
+ // each workspace's catalog was last settled at, to tell when the workspace moved. Every timer
317
+ // the shared spawn arms is the run's (`spawnTimers`), cleared as the run ends: a spawn let go is
318
+ // never signalled after the TUI has gone, on any kernel.
319
+ const spawnTimers = createRunTimers({ setTimer, clearTimer });
320
+ const preview = effects.createSpawnPreview({ exec: reader.exec });
321
+ let spawnLabel = null, job = null;
322
+ const catalogKeys = new Map();
323
+ const spawnApply = effects.createSpawnApplyBoundary({ read: preview.prepareRead, exec: (bin, argv, { detached, ...options }, callback) => (detached
324
+ ? reader.changeExec(bin, argv, { ...options, label: spawnLabel }, callback)
325
+ : reader.exec(bin, argv, options, callback)),
326
+ timer: spawnTimers.timer, applyTimer: spawnTimers.timer });
327
+ /** As the Desktop's (server/oats-web.mjs): a spawn in the air changes what a preview answers, so
328
+ * held previews go when it is applied, and again when a pending apply settles, with a read. */
329
+ const forgetPreviews = (id) => { try { preview.cache.invalidate(id); } catch { /* never blocks a spawn */ } };
330
+ const transaction = effects.createSpawnTransaction({ request: (body, tx) => {
331
+ if (body?.action === "apply") forgetPreviews(tx.address);
332
+ return spawnApply(body, () => spawnContext(state, tx.address, clock()), { settled: () => { forgetPreviews(tx.address); refresh({ live: true }); } });
333
+ }, sleep: spawnTimers.sleep });
334
+ /** What a spawn's call is told: its owner is gone once the TUI leaves (`alive`), and the job is
335
+ * kept once it is submitted, for a check. */
336
+ const spawnCall = { alive: () => !ended, progress: (event, made) => { if (event === "submitted") { job = made; heard({ spawnProgress: { event } }); } } };
337
+ /** A transaction's outcome as the store takes it: the shared one, with the instance it names. */
338
+ const spawnTold = (outcome) => {
339
+ const receipt = outcome.view?.receipt ?? null, prepared = outcome.view?.preview ?? null;
340
+ return { kind: outcome.kind, view: outcome.view, reason: outcome.reason, instance: receipt?.instance ?? prepared?.instance ?? null, home: receipt?.home ?? prepared?.home ?? null };
341
+ };
342
+ /** A call that threw instead of answering: what it did is not known. */
343
+ const UNKNOWN = Object.freeze({ kind: "unknown", reason: Object.freeze({ code: "E_OUTCOME_UNKNOWN" }) });
344
+ /** The preview the store asked for (`{ n, workspace, request }`), read against the workspace as
345
+ * it is at that moment; its answer goes to the store. It arms Spawn only once a frame that
346
+ * shows it is written (the guard's `frame`). */
347
+ function previewRead({ n, workspace, request }) {
348
+ Promise.resolve()
349
+ .then(() => preview.read(request, () => spawnContext(state, workspace, clock())))
350
+ .then((answer) => heard({ spawnRead: { n, answer } }), () => heard({ spawnRead: { n, answer: null } }));
351
+ }
352
+ /** The spawn the store decided on: submitted once; its outcome goes to the store. */
353
+ function spawnNow({ workspace, selector, input, decision, name }) {
354
+ spawnLabel = { verb: "spawn", name };
355
+ job = null;
356
+ Promise.resolve()
357
+ .then(() => transaction.submit({ address: workspace, selector, input, decision }, spawnCall))
358
+ .then((outcome) => { if (outcome) heard({ spawnDone: spawnTold(outcome) }); }, () => heard({ spawnDone: UNKNOWN }));
359
+ }
360
+ /** C: the last spawn's result read once (an unknown one applies the same reference again). */
361
+ function checkSpawn() {
362
+ const mine = job;
363
+ if (mine === null) return void heard({ spawnDone: UNKNOWN });
364
+ Promise.resolve()
365
+ .then(() => transaction.check(mine, spawnCall))
366
+ .then((outcome) => { if (outcome) heard({ spawnDone: spawnTold(outcome) }); }, () => heard({ spawnDone: UNKNOWN }));
367
+ }
368
+
369
+ /** What the reader gave, into the state, and the screen after it. A read of the open workspace,
370
+ * once the Souls view (or the Capabilities view, or a spawn) wanted its catalog, settles it, and
371
+ * once the Capabilities view was shown its table: each read again only when its key moved. */
372
+ function heard(event) {
373
+ if (ended) return;
374
+ guard.attempt(() => {
375
+ if (took(reduce(state, event, keymap))) return;
376
+ if (event.entry !== undefined && event.id === state.open && state.souls.wanted) settleSouls(event.id);
377
+ if (event.entry !== undefined && event.id === state.open && state.capabilities.wanted) settleCapabilities(event.id);
378
+ guard.draw();
379
+ });
380
+ }
168
381
  /** One step of the reducer taken: the state, then what only the loop can do. True once the
169
382
  * TUI is leaving. Listing ~/Agents and asking whether a picked folder is a deployment read the
170
383
  * file system (lib/read.mjs); what they find is an event of its own. */
@@ -181,7 +394,8 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
181
394
  took(reduce(state, admitted.ok ? { admitted: admitted.deployment, at: clock() } : { refused: effect.admit }, keymap));
182
395
  }
183
396
  if (effect.abandon) giveUpPreflight();
184
- if (effect.close !== undefined) closeTerminal();
397
+ // A tab shown (`show`) needs nothing here: the frame after it brings the panel to it (fitPanel).
398
+ if (effect.close !== undefined) for (const id of effect.close) closeTerminal(id);
185
399
  if (effect.open) open(effect.open);
186
400
  if (effect.panel !== undefined) {
187
401
  const ready = preflight;
@@ -193,6 +407,13 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
193
407
  if (effect.call) callConfirmation(effect.call);
194
408
  if (effect.start) startAct(effect.start);
195
409
  if (effect.refresh) refresh(effect.refresh);
410
+ if (effect.souls === "settle" && state.open !== null) settleSouls(state.open);
411
+ if (effect.souls === "reread" && state.open !== null) rereadSouls(state.open);
412
+ if (effect.capabilities === "settle" && state.open !== null) settleCapabilities(state.open);
413
+ if (effect.capabilities === "reread" && state.open !== null) rereadCapabilities(state.open);
414
+ if (effect.spawnPreview) previewRead(effect.spawnPreview);
415
+ if (effect.spawn) spawnNow(effect.spawn);
416
+ if (effect.spawnCheck) checkSpawn();
196
417
  return false;
197
418
  }
198
419
 
@@ -200,7 +421,8 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
200
421
  const contextOf = (id) => actContext(state, id, clock());
201
422
  /** Open the shared confirmation of a stop or a retire the store decided on (`{ n, verb, row,
202
423
  * label }`). Every step it tells goes to the store as `{ acted }`; an answer that settles asks
203
- * for a live read of the rows (onSettled), and nothing else after an apply does. */
424
+ * for a live read of the rows (onSettled), and nothing else after an apply does. A retire's
425
+ * apply is held in `retires` from its send, whether or not the confirmation is still open. */
204
426
  function openConfirmation({ n, verb, row, label }) {
205
427
  dismiss(confirmation?.n);
206
428
  const id = row.deployment?.id, name = row.instance;
@@ -211,7 +433,7 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
211
433
  mine.made = effects.createLifecycleConfirmation({
212
434
  request: (body) => { if (body?.action === "apply") applying = { verb, name }; return boundary(body, () => contextOf(id)); },
213
435
  target, operation: verb, terms: TERMS, label, leftover: heldHome(row)?.kind === "spawn-incomplete",
214
- onChange: tell, onSettled: () => refresh({ live: true }),
436
+ onChange: tell, onSettled: () => refresh({ live: true }), retires,
215
437
  });
216
438
  tell();
217
439
  }
@@ -269,74 +491,126 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
269
491
  preflight = null;
270
492
  }
271
493
  /** Start the viewer of row `id` (`node <bin> <args…>`) in the panel, at the size the frame gives
272
- * the terminal, and tell the store when its window exists. One the panel could not start is a
273
- * viewer that ended, with the panel's refusal: no tmux (or one too old), or tmux's own words.
274
- * Nothing is lent: the reads and the screen go on. */
494
+ * the focused group, and tell the store when its window exists. The tab it takes the place of is
495
+ * no longer displayed from then on (the frame for the new state is fitted first). One the panel
496
+ * could not start is a viewer that ended, with the panel's refusal: no tmux (or one too old), or
497
+ * tmux's own words. Nothing is lent: the reads and the screen go on. */
275
498
  function view(id, bin, args) {
276
- const mine = viewing = { id, panel: null };
277
- const size = guard.size(), area = composed().made.terminal ?? { cols: size.cols, rows: Math.max(1, size.rows - 6) };
278
- panelSize = { cols: area.cols, rows: area.rows };
279
- // Shown: the panel keeps hidden or shown across its viewers, and the last one may have been
280
- // closed hidden (behind the detail, or the list alone under 80 columns).
281
- if (!panelShown) panel.setVisible(true);
282
- panelShown = true;
499
+ const size = guard.size();
500
+ // The focused group's screen as the Instances view gives it, also behind the help or another
501
+ // overlay, which draw no panel (round 1 of T3's review).
502
+ const region = placed()?.focused ?? { cols: Math.max(1, size.cols), rows: Math.max(1, size.rows - 6) };
503
+ const mine = { id, panel: null, cols: region.cols, rows: region.rows };
504
+ viewers.set(id, mine);
505
+ // Shown or hidden as this frame draws the panel: behind an overlay it shows once that closes.
506
+ fitPanel(composed().made);
283
507
  Promise.resolve()
284
- .then(() => panel.open({ argv: [process.execPath, bin, ...args], cols: area.cols, rows: area.rows }))
508
+ .then(() => panel.open({ argv: [process.execPath, bin, ...args], cols: region.cols, rows: region.rows, instead: null }))
285
509
  .then(({ id: made }) => {
286
- if (viewing !== mine) return;
510
+ if (viewers.get(id) !== mine) return;
287
511
  mine.panel = made;
288
- // A frame of another size while the window was being made told a panel with no window yet.
289
- if (panelSize.cols !== area.cols || panelSize.rows !== area.rows) panel.resize(panelSize.cols, panelSize.rows);
512
+ // The panel displays it, and it takes the keys; a frame of another size meanwhile is the
513
+ // next fitPanel's.
514
+ displayed.add(made);
515
+ keysTo = made;
290
516
  heard({ shown: { id } });
291
517
  },
292
- (error) => { if (viewing === mine) { viewing = null; heard({ returned: { id, status: null, stderr: typeof error?.detail === "string" ? error.detail : "", refused: error?.code === "E_PANEL_TMUX" ? "tmux" : "start" } }); } });
293
- }
294
- /** Close the open terminal's viewer (also one whose window is still being made): the agent keeps
295
- * running, and the panel reports the end as asked for, which nobody waits for. */
296
- function closeTerminal() {
297
- if (viewing === null) return;
298
- viewing = null; screenNow = null;
299
- panel.close();
300
- }
301
- /** The panel told what the frame gives the terminal: shown or not (no capture runs while it is
302
- * hidden, and one runs when it shows again), and its size (the viewer's window follows it). */
303
- function fitPanel(given) {
304
- // A view that draws no terminal (the help, the switcher, a confirmation) gives none.
305
- const area = given ?? null;
306
- if (viewing === null) return;
307
- if ((area !== null) !== panelShown) { panelShown = area !== null; panel.setVisible(panelShown); }
308
- if (area !== null && (area.cols !== panelSize.cols || area.rows !== panelSize.rows)) { panelSize = { cols: area.cols, rows: area.rows }; panel.resize(area.cols, area.rows); }
518
+ (error) => { if (viewers.get(id) === mine) { forgetViewer(mine); heard({ returned: { id, status: null, stderr: typeof error?.detail === "string" ? error.detail : "", refused: error?.code === "E_PANEL_TMUX" ? "tmux" : "start" } }); } });
519
+ }
520
+ /** What the loop holds of viewer `v` let go: the panel no longer displays it, or gives it keys. */
521
+ function forgetViewer(v) {
522
+ viewers.delete(v.id);
523
+ screens.delete(v.id);
524
+ if (v.panel !== null) { displayed.delete(v.panel); if (keysTo === v.panel) keysTo = null; }
525
+ }
526
+ /** Close tab `id`'s viewer (also one whose window is still being made: the open under way): the
527
+ * agent keeps running, and the panel reports the end as asked for, which nobody waits for. */
528
+ function closeTerminal(id) {
529
+ const v = viewers.get(id);
530
+ if (v === undefined) return;
531
+ forgetViewer(v);
532
+ if (v.panel === null) panel.close(); else panel.close(v.panel);
533
+ }
534
+ /** The panel brought to what the frame drew (`made.regions`, one per group drawn): shown or not
535
+ * (no capture runs while it is hidden, and one runs when it shows again); every tab of a drawn
536
+ * group at that group's size (the viewer's window follows it); each region's shown tab
537
+ * displayed, and no other; and the focused region's taking the keys. A group not drawn (the
538
+ * focused one alone, zoomed or with no room for both) keeps its tabs at their size, and its
539
+ * shown tab only marks. */
540
+ function fitPanel(made) {
541
+ if (viewers.size === 0) return;
542
+ const regions = made.regions ?? [];
543
+ if ((regions.length > 0) !== panelShown) { panelShown = regions.length > 0; panel.setVisible(panelShown); }
544
+ if (!panelShown) return;
545
+ const groupOf = (id) => state.tabs.find((tab) => tab.id === id)?.group ?? null;
546
+ for (const r of regions) {
547
+ const resized = [...viewers.values()].filter((v) => v.panel !== null && groupOf(v.id) === r.group && (v.cols !== r.cols || v.rows !== r.rows));
548
+ if (resized.length === 0) continue;
549
+ panel.resize(r.cols, r.rows, resized.map((v) => v.panel));
550
+ for (const v of resized) { v.cols = r.cols; v.rows = r.rows; }
551
+ }
552
+ const wanted = regions.map((r) => ({ r, v: r.id === null ? null : viewers.get(r.id) ?? null })).filter(({ v }) => v !== null && v.panel !== null);
553
+ const pids = new Set(wanted.map(({ v }) => v.panel));
554
+ // The shown tab hidden: the panel shows the other displayed one, or none (lib/panel.mjs hide).
555
+ for (const pid of [...displayed]) if (!pids.has(pid)) { panel.hide(pid); displayed.delete(pid); if (keysTo === pid) keysTo = [...displayed][0] ?? null; const v = viewerOf(pid); if (v) screens.delete(v.id); }
556
+ for (const { v } of wanted) if (!displayed.has(v.panel)) { panel.show(v.panel, { instead: null }); displayed.add(v.panel); keysTo = v.panel; }
557
+ const keys = wanted.find(({ r }) => r.focused)?.v.panel ?? null;
558
+ if (keys !== null && keys !== keysTo) { panel.focus(keys); keysTo = keys; }
309
559
  }
310
560
  /** The frame for the state now, with what the loop needs of it: the layout first, because the
311
561
  * model's window is as tall, and its sentences as wide, as the list pane it gives. The switcher
312
- * takes the whole body and has no notice of a deployment. The last capture of the open
313
- * terminal goes with the model: it is the panel's, not the store's. */
562
+ * takes the whole body and has no notice of a deployment. The last captures of the displayed
563
+ * tabs go with the model: they are the panel's, not the store's. */
314
564
  function composed() {
565
+ const { size, g, m } = modelled();
566
+ return { size, g, made: frame(m, size) };
567
+ }
568
+ function modelled() {
315
569
  const size = guard.size(), at = clock();
316
570
  const listing = (state.view === "help" ? state.back : state.view) === "switcher";
317
571
  const r = listing ? { notice: null, note: null, observed: true } : roster(state, at);
318
- const g = layout(r.notice, size, { observed: r.observed, note: r.note, ascii: state.ascii, outcome: listing ? null : state.outcome });
319
- const m = { ...model(state, { page: g.page, now: now(), at, cols: g.listCols }), screen: screenNow };
320
- return { size, g, made: frame(m, size) };
572
+ const g = layout(r.notice, size, { observed: r.observed, note: r.note, ascii: state.ascii, outcome: listing ? null : outcomeOf(state), terminal: state.tabs.length > 0 });
573
+ const m = { ...model(state, { page: g.page, now: now(), at, cols: g.listCols }), screen: screens.get(state.terminal?.id) ?? null, screens };
574
+ return { size, g, m };
575
+ }
576
+ /** Where the panel stands for the state and the size now, as the Instances view gives it with
577
+ * the terminal's focus (views/frame.mjs panelPlace): measured whatever is drawn over it, and
578
+ * while no frame can be written. */
579
+ function placed() {
580
+ const { size, m } = modelled();
581
+ return panelPlace(m, size);
321
582
  }
322
- /** Whether what is typed goes to the agent: the open terminal has the focus. */
323
- const typing = () => state.terminal?.focus === "terminal" && state.view === "instances";
583
+ /** Whether what is typed goes to the agent: the open terminal has the focus, and the leader
584
+ * does not wait for its key (docs/tui.md, "The leader"). */
585
+ const typing = () => state.terminal?.focus === "terminal" && state.view === "instances" && state.leader?.waiting !== true && state.palette === null && state.spawn === null;
324
586
  /** Bytes typed while the terminal has the focus: to the agent as they came, a paste as a paste,
325
- * and the back key to the store, which gives the focus to the list; what came after the back key
326
- * in the same read is read as keys, by a parser that starts afresh. */
587
+ * and the leader to the store, which waits for the key after it: from the next read on, the
588
+ * bytes are read as keys, by a parser that starts afresh. What came after the leader in its own
589
+ * read is dropped: it cancels the leader (a paste), and it is not the agent's either. */
327
590
  function typed(events) {
328
591
  for (const event of events) {
329
- if (event.input) panel.input(event.input);
330
- else if (event.paste !== undefined) panel.paste(event.paste);
592
+ if (event.input) { if (keysReady()) panel.input(event.input); }
593
+ else if (event.paste !== undefined) { if (keysReady()) panel.paste(event.paste); }
331
594
  else if (event.back) {
332
595
  parser = createKeyParser({ now });
333
- if (took(reduce(state, { back: true }, keymap))) return;
334
- if (event.rest.length) act(parser.feed(event.rest)); else guard.draw();
335
- watchEscape();
596
+ if (took(reduce(state, { back: true, read: ++reads, rest: event.rest.length > 0 }, keymap))) return;
597
+ guard.draw();
336
598
  }
337
599
  }
338
600
  watchThrough();
339
601
  }
602
+ /** Whether the keys typed now reach the agent the state gives them to, the focused group's shown
603
+ * tab: the panel is fitted to the state first when it was not, also while no frame is written
604
+ * (the output blocked), so a tab or a group switched to takes what is typed after the switch,
605
+ * never the one before it. A tab whose window is still being made takes nothing (round 1 of
606
+ * T3's review). */
607
+ function keysReady() {
608
+ const v = state.terminal === null ? undefined : viewers.get(state.terminal.id);
609
+ if (v === undefined || v.panel === null) return false;
610
+ const ready = () => keysTo === v.panel && displayed.has(v.panel);
611
+ if (!ready()) fitPanel(composed().made);
612
+ return ready();
613
+ }
340
614
  /** A beginning of the back key that nothing has followed for the parser's timeout is the agent's. */
341
615
  function watchThrough() {
342
616
  if (throughTimer !== null) { clearTimer(throughTimer); throughTimer = null; }
@@ -348,9 +622,17 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
348
622
  frame() {
349
623
  const { size, g, made } = composed();
350
624
  drawn = { page: made.page, extent: made.extent, room: made.room, cols: g.listCols };
351
- fitPanel(made.terminal);
625
+ fitPanel(made);
352
626
  const bytes = screen.render(made.rows, size, { full, cursor: made.cursor });
353
627
  full = false;
628
+ // This frame is written (the guard makes one only to write it): a ready preview on it is
629
+ // seen, and Enter on Spawn is taken from the next read of input on (the paste guard).
630
+ if (made.armed && state.spawn !== null) state = reduce(state, { spawnDrawn: { n: state.spawn.n, read: reads } }, keymap).state;
631
+ // The preview's window as painted, which keeps a focused fold in sight: the store's `top`
632
+ // from now on, so the next movement key goes on from what is on the screen.
633
+ if (made.drawnTop !== undefined && state.spawn !== null) state = reduce(state, { spawnTop: { n: state.spawn.n, top: made.drawnTop } }, keymap).state;
634
+ // The capability detail's window as painted, which keeps the marked soul in sight: the same.
635
+ if (made.capabilitiesTop !== undefined) state = reduce(state, { capabilitiesTop: made.capabilitiesTop }, keymap).state;
354
636
  return bytes;
355
637
  },
356
638
  onInput(bytes) {
@@ -360,7 +642,7 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
360
642
  },
361
643
  onResize() { full = true; guard.draw(); },
362
644
  // Ctrl+L and the return from a stop: the whole screen, and the open terminal captured afresh.
363
- onRedraw() { full = true; if (viewing !== null) panel.refresh(); guard.draw(); },
645
+ onRedraw() { full = true; if (viewers.size) panel.refresh(); guard.draw(); },
364
646
  // A cycle in flight when the process stops is no evidence about the deployment (lib/read.mjs):
365
647
  // it is dropped before the stop, and again after a stop nobody here asked for; the return
366
648
  // reads at once.
@@ -368,15 +650,15 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
368
650
  // timeout. The person opens the agent again.
369
651
  // The open terminal's server and viewer live on through a stop; the panel stops sending output
370
652
  // while nothing reads it, and captures afresh on the way back.
371
- onStop() { stopPreflight(); dropReads(); if (viewing !== null) panel.pause(); },
372
- onResume(asked) { if (!asked) { stopPreflight(); dropReads(); } if (viewing !== null) panel.resume(); refresh({ live: true }); },
653
+ onStop() { stopPreflight(); dropReads(); if (viewers.size) panel.pause(); },
654
+ onResume(asked) { if (!asked) { stopPreflight(); dropReads(); } if (viewers.size) panel.resume(); refresh({ live: true }); },
373
655
  // On the way out the confirmation is closed, the private tmux server is ended (its viewer with
374
656
  // it) and the reads end; a change in flight is let go, never signalled (lib/read.mjs
375
657
  // changeExec), and named after the screen is left.
376
658
  // The run's directory goes last, made for whichever of the two needed it first: the reader
377
659
  // removes it only when it wrote a change there, and one it cannot remove (a change still
378
660
  // writing) stays.
379
- onEnd() { ended = true; dismiss(confirmation?.n); panel.end(); reader.stop(); if (dir !== null) { try { effects.removeDir(dir); } catch { /* not empty, or gone */ } } },
661
+ onEnd() { ended = true; spawnTimers.end(); dismiss(confirmation?.n); panel.end(); reader.stop(); if (dir !== null) { try { effects.removeDir(dir); } catch { /* not empty, or gone */ } } },
380
662
  });
381
663
  function refresh(how) { Promise.resolve(reader.request(how)).catch(() => {}); }
382
664
  /** A preflight under way when the process stops: given up, and the store told. */
@@ -396,7 +678,7 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
396
678
  function act(events) {
397
679
  const read = ++reads;
398
680
  for (const event of events) {
399
- if (took(reduce(state, "paste" in event ? { paste: event.paste } : { key: keyId(event), ...(typeof event.text === "string" && !event.alt ? { text: event.text } : {}), read, ...drawn }, keymap))) return;
681
+ if (took(reduce(state, "paste" in event ? { paste: event.paste, read } : { key: keyId(event), ...(typeof event.text === "string" && !event.alt ? { text: event.text } : {}), read, ...drawn, panel: placed()?.panel ?? null }, keymap))) return;
400
682
  if (typing()) {
401
683
  if (escTimer !== null) { clearTimer(escTimer); escTimer = null; }
402
684
  through = createThrough({ sequences: backKey, now });