@awebai/oats 0.56.0 → 0.57.1

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 (64) hide show
  1. package/bin/oats.mjs +18 -10
  2. package/docs/configuration.md +17 -27
  3. package/docs/desktop-cli-api.md +59 -3
  4. package/docs/desktop.md +25 -4
  5. package/docs/execution-targets.md +6 -1
  6. package/docs/implementation.md +106 -5
  7. package/docs/integrations.md +8 -4
  8. package/docs/knowledge.md +93 -38
  9. package/docs/official-catalog.md +3 -3
  10. package/docs/packages.md +12 -12
  11. package/docs/release-notes/v0.57.0.md +283 -0
  12. package/docs/release-notes/v0.57.1.md +275 -0
  13. package/docs/schedules.md +8 -3
  14. package/docs/servers.md +18 -0
  15. package/docs/souls-and-instances.md +126 -15
  16. package/docs/tui.md +333 -95
  17. package/docs/workspaces.md +2 -2
  18. package/lib/core.mjs +439 -126
  19. package/lib/instance-lifecycle.mjs +45 -9
  20. package/lib/session-viewer.mjs +29 -4
  21. package/lib/worktree.mjs +23 -2
  22. package/package-catalog.json +2 -2
  23. package/package.json +1 -1
  24. package/packages/client/cli-adapter.mjs +9 -7
  25. package/packages/client/cli-locator.mjs +2 -2
  26. package/packages/client/composed-gate.mjs +34 -0
  27. package/packages/client/inspect-boundary.mjs +157 -0
  28. package/packages/client/inspect-cache.mjs +86 -0
  29. package/packages/client/instance-lifecycle.mjs +10 -3
  30. package/packages/client/keyed-catalog.mjs +132 -0
  31. package/packages/client/launch-prompt-outcome.mjs +1 -1
  32. package/packages/client/launch-view.mjs +46 -0
  33. package/packages/client/session-attach.mjs +7 -5
  34. package/packages/client/soul-catalog.mjs +77 -0
  35. package/packages/client/soul-colors.mjs +31 -0
  36. package/packages/client/soul-facts.mjs +85 -0
  37. package/packages/client/soul-rows.mjs +48 -0
  38. package/packages/client/spawn-apply-cli.mjs +11 -6
  39. package/packages/client/spawn-apply.mjs +212 -0
  40. package/packages/client/spawn-messages.mjs +131 -85
  41. package/packages/client/spawn-preview-contract.mjs +3 -0
  42. package/packages/client/spawn-preview-facts.mjs +119 -0
  43. package/packages/client/spawn-preview.mjs +152 -0
  44. package/packages/client/spawn-transaction.mjs +136 -0
  45. package/packages/tui/README.md +43 -13
  46. package/packages/tui/lib/actions.mjs +18 -2
  47. package/packages/tui/lib/client.mjs +4 -0
  48. package/packages/tui/lib/config.mjs +9 -14
  49. package/packages/tui/lib/main.mjs +241 -55
  50. package/packages/tui/lib/model.mjs +230 -29
  51. package/packages/tui/lib/panel.mjs +955 -0
  52. package/packages/tui/lib/read.mjs +134 -24
  53. package/packages/tui/lib/store.mjs +184 -31
  54. package/packages/tui/lib/term/capture.mjs +260 -0
  55. package/packages/tui/lib/term/screen.mjs +44 -8
  56. package/packages/tui/lib/term/style.mjs +78 -6
  57. package/packages/tui/lib/term/text.mjs +24 -4
  58. package/packages/tui/lib/term/through.mjs +213 -0
  59. package/packages/tui/lib/term/tty.mjs +7 -60
  60. package/packages/tui/lib/views/act.mjs +85 -0
  61. package/packages/tui/lib/views/frame.mjs +153 -37
  62. package/packages/tui/lib/views/help.mjs +22 -14
  63. package/skills/oats-getting-started/SKILL.md +4 -3
  64. package/packages/tui/lib/open.mjs +0 -45
@@ -1,18 +1,37 @@
1
1
  // The effects of the TUI: finding the deployment, the kernel's record, one exec for every kernel
2
2
  // call, the observer of every served deployment, the roster of other machines, the refresh loop,
3
3
  // the liveness collector, and the two looks at the file system the switcher needs.
4
- // Nothing here changes a deployment, and nothing writes a file: every child of this module is a
5
- // read. (Opening an agent's terminal starts the kernel's viewer, which is not a read and is not
6
- // started here: lib/open.mjs.)
4
+ // Every child of this module is a read, except the changes (a stop or retire apply, a start or a
5
+ // restart) that the shared callers start through `changeExec`: those are never ended by the TUI,
6
+ // and their output goes to two files of the run's own private directory, the only files this
7
+ // module writes. (Opening an agent's terminal starts the kernel's viewer, which is not a read and
8
+ // is not started here: it runs in a pane of the panel's private tmux server, lib/panel.mjs.)
7
9
  // No function of this module decodes a kernel answer. Each one passes values between the shared
8
10
  // functions (client.mjs), which decide what a roster, a row and a failed read are, once, for both
9
11
  // clients: the TUI never writes "stopped" for a row and never builds the collector's input by hand.
10
12
  import { execFile as nodeExecFile, spawn as nodeSpawn } from "node:child_process";
11
- import { lstatSync, opendirSync, realpathSync, statSync } from "node:fs";
13
+ import { closeSync, fstatSync, lstatSync, mkdtempSync, openSync, opendirSync, readSync, realpathSync, rmdirSync, statSync, unlinkSync } from "node:fs";
14
+ import { tmpdir } from "node:os";
12
15
  import { basename, dirname, join } from "node:path";
13
16
  import { fileURLToPath } from "node:url";
14
17
  import { COLLECTOR, INSTANCE_VARIABLES, MAX_DEPLOYMENT_OBSERVATIONS, acceptProbe, cliDeploymentRead, cliReadsRemotes, cliRecord, cliRemoteRoster, createDeploymentObserver, createRefreshLoop, deploymentsInside, failedEntry, livenessAnswers, livenessInput, mapBounded, observeIdentities, observedEntry, panelInstances, parseProbeStdout, remoteRosterState, rosterRows, validateWorkspace } from "./client.mjs";
15
18
 
19
+ /** A path made canonical: what the shared start rule checks a local home with (session-start.mjs
20
+ * verifiedLocalHome). Throws for a path that cannot be resolved; the rule answers that as no home. */
21
+ export const realpath = (path) => realpathSync(path);
22
+
23
+ /** Whether a line may be written to `stream` on the way out: only when it is a terminal (a
24
+ * character device the stream says is one) or a file, by fstat of its descriptor. A closed
25
+ * descriptor, a pipe, a socket or anything else gets nothing. Never throws. */
26
+ export function tellable(stream) {
27
+ try {
28
+ const fd = stream?.fd;
29
+ if (!Number.isInteger(fd) || fd < 0) return false;
30
+ const stat = fstatSync(fd);
31
+ return stat.isFile() || (stat.isCharacterDevice() && stream.isTTY === true);
32
+ } catch { return false; }
33
+ }
34
+
16
35
  /** The kernel this TUI shipped with: the absolute path of the install's own bin/oats.mjs, found by
17
36
  * URL from this file. Every kernel call is `node <this path> …`, so the TUI depends on no shebang,
18
37
  * no execute bit and no `PATH`, and never talks to another install's kernel. */
@@ -147,6 +166,29 @@ export function probeKernel({ bin = KERNEL_BIN, env = process.env, execFile = no
147
166
  });
148
167
  }
149
168
 
169
+ /** Where a change's output goes (createReader `files`). `dir()` makes the run's private directory
170
+ * (mkdtemp: mode 0700, under the OS temp dir); `open` makes one file in it for the child alone
171
+ * (0600, refused if it is there); `read(path, max)` reads back at most `max` bytes and one more,
172
+ * only to say whether there was more (`over`). Exported for the tests, which find the directory by it. */
173
+ export const CHANGE_FILES = Object.freeze({
174
+ dir: () => mkdtempSync(join(tmpdir(), "oats-tui-")),
175
+ open: (path) => openSync(path, "wx", 0o600),
176
+ close: (fd) => closeSync(fd),
177
+ unlink: (path) => unlinkSync(path),
178
+ remove: (dir) => rmdirSync(dir),
179
+ read: (path, max) => {
180
+ const fd = openSync(path, "r");
181
+ try {
182
+ const size = fstatSync(fd).size, room = Number.isFinite(max) ? Math.min(size, max + 1) : size;
183
+ const buffer = Buffer.alloc(room);
184
+ let got = 0;
185
+ while (got < room) { const n = readSync(fd, buffer, got, room - got, got); if (n === 0) break; got += n; }
186
+ const over = got > max;
187
+ return { text: buffer.subarray(0, over ? max : got).toString("utf8"), over };
188
+ } finally { quietly(() => closeSync(fd)); }
189
+ },
190
+ });
191
+
150
192
  /** A child that did not end well, as execFile reports one: the facts on an Error, and no text of the child's. */
151
193
  const failure = (facts) => Object.assign(new Error("the child did not end with an answer"), facts);
152
194
  /** A child the reader ended itself: its time limit, or the reader giving it up. As execFile's timeout. */
@@ -156,7 +198,7 @@ const said = (error) => String(error?.message ?? error);
156
198
 
157
199
  /** The reader of a run: its cycles over every served deployment, the roster of other machines,
158
200
  * their children, and the way out.
159
- * -> { start(), request({ live }), touch(), voidInFlight(), hold(), release(), exec, stop(), children() }
201
+ * -> { start(), request({ live }), touch(), voidInFlight(), exec, stop(), children() }
160
202
  *
161
203
  * `cli` is probeKernel's record (`cli.bin` the absolute path of bin/oats.mjs). The reader keeps no
162
204
  * answer of its own: what a run holds is the caller's store, asked for when it is needed.
@@ -188,24 +230,31 @@ const said = (error) => String(error?.message ?? error);
188
230
  * list of options, `detached` is not one of them, and a child it starts stays in the TUI's group
189
231
  * whatever it is asked. `run` below is the part of execFile's contract the shared readers use.
190
232
  *
191
- * ENDING A CHILD holds because every child the reader starts is a read: the viewer of an opened
192
- * agent is lib/open.mjs's, and no child of the reader. A KERNEL CALL THAT CHANGES SOMETHING MUST
193
- * NEVER BE KILLED BY THE TUI: a killed stop or start leaves a marker that refuses every later one.
194
- * So every child is remembered with its kind, only kind "read" is ever signalled, and a later
195
- * version's writing calls get a kind of their own.
233
+ * ENDING A CHILD: only a read is ever ended. The viewer of an opened agent runs in the panel's
234
+ * private tmux server (lib/panel.mjs), and is no child of the reader. A KERNEL CALL THAT CHANGES SOMETHING (kind "change", `changeExec`) IS
235
+ * NEVER SIGNALLED BY THE TUI: a stop killed while it waits leaves a marker that refuses every
236
+ * later stop, and a killed start leaves its lock (#889, #890). So every child is remembered with
237
+ * its kind, and only kind "read" is ever signalled.
196
238
  *
197
- * `timers` are the loop's, the idle timer's and the children's time limits (for tests). */
198
- export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onRoster, env = process.env, clock = () => new Date().toISOString(), now = Date.now, spawn = nodeSpawn, timers = { setTimeout, clearTimeout }, collector = COLLECTOR, idleMs = 600_000, focusedMs = 5000, blurredMs = 30_000, rosterMs = 15_000 }) {
199
- /** child -> { kind, exited, giveUp, asked }: every child that has not ended and was not ended.
200
- * `asked`: a read the loop asked for itself (the preflight of an open), which no cycle owns. */
239
+ * `timers` are the loop's, the idle timer's and the children's time limits (for tests). `files`
240
+ * is where a change's output is written (for tests): `files.dir()` makes the run's private
241
+ * directory. */
242
+ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onRoster, env = process.env, clock = () => new Date().toISOString(), now = Date.now, spawn = nodeSpawn, timers = { setTimeout, clearTimeout }, collector = COLLECTOR, idleMs = 600_000, focusedMs = 5000, blurredMs = 30_000, rosterMs = 15_000, files = CHANGE_FILES }) {
243
+ /** child -> { kind, exited, giveUp, asked } for a read, { kind: "change", label, letGo } for a
244
+ * change: every child that has not ended and was not ended (a read) or let go (a change).
245
+ * `asked`: a read the loop asked for itself (the preflight of an open, a plan read), which no
246
+ * cycle owns. */
201
247
  const remembered = new Map();
248
+ /** The changes still running, whether or not this run still waits for them: child -> label. A
249
+ * change leaves it when it exits, and stays in it after stop() let it go. */
250
+ const running = new Map();
251
+ /** The run's private directory for the output of its changes, made at the first one. */
252
+ let changeDir = null, changeCount = 0;
202
253
  let started = false, stopped = false, idleTimer = null;
203
254
  /** `counter` numbers the cycles. `epoch` moves when the cycles in flight are made void; `flight`
204
255
  * is the epoch the cycle now running began in (the loop runs one at a time). `served` is what
205
256
  * getServed() answered at the start of that cycle. */
206
257
  let counter = 0, epoch = 0, flight = 0, served = [];
207
- /** The terminal is lent (hold()): no cycle and no roster read starts until release(). */
208
- let held = false;
209
258
  /** The roster of other machines. `rosterFlight` is the read in flight (a token of its own, so an
210
259
  * answer knows whether it is still awaited), or null. `rosterEnded` is now() when the last read
211
260
  * that was not given up ended, or null while none has. `gatedSaid`: a kernel that reads no
@@ -319,6 +368,64 @@ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onR
319
368
  }
320
369
  return child;
321
370
  }
371
+ /** THE EXEC OF A CHANGE: a stop or retire apply (the boundary's call with `detached: true`), a
372
+ * start or a restart (the shared cliStart's). execFile's signature for `node <bin> <argv…>`, in
373
+ * a session of its own, outside every cycle: it is never made void by voidInFlight() and never
374
+ * signalled, not by `sever`, not by stop(), not at a time limit (a `timeout` given is not
375
+ * armed: the shared callers end their wait, never the child). `options.label` is the caller's
376
+ * `{ verb, name }`, kept for the line after leaving (`changes()`), and is not passed on.
377
+ * ITS OUTPUT GOES TO FILES, NEVER TO A PIPE. Before the spawn two files are opened in the run's
378
+ * private directory (made once, mode 0700, under the OS temp dir) and given to the child as its
379
+ * stdout and stderr; stdin is `ignore`. The TUI's own copies are closed after the spawn. So
380
+ * whatever the TUI does (quits, is stopped, loses its terminal) the child can always write, and
381
+ * nothing it writes meets EPIPE or SIGPIPE. When the child closes, both files are read back,
382
+ * each bounded by `maxBuffer` (over it: ERR_CHILD_PROCESS_STDIO_MAXBUFFER, as a read answers),
383
+ * deleted, and the callback is called as execFile calls it, with text (UTF-8).
384
+ * It throws after stop(): nothing new starts on the way out. Returns the child. */
385
+ function changeExec(bin, argv, { label = null, timeout: _never, maxBuffer = Infinity, encoding: _utf8, ...options }, callback) {
386
+ if (stopped) throw new Error("the reader has stopped");
387
+ if (changeDir === null) changeDir = files.dir();
388
+ const number = ++changeCount, paths = { stdout: join(changeDir, `${number}.out`), stderr: join(changeDir, `${number}.err`) };
389
+ const fds = {};
390
+ try {
391
+ for (const name of ["stdout", "stderr"]) fds[name] = files.open(paths[name]);
392
+ } catch (error) {
393
+ for (const name of ["stdout", "stderr"]) if (fds[name] !== undefined) { quietly(() => files.close(fds[name])); quietly(() => files.unlink(paths[name])); }
394
+ throw error;
395
+ }
396
+ let child;
397
+ try {
398
+ child = spawn(process.execPath, [bin, ...argv], { ...(options.env === undefined ? { ...options, env } : options), stdio: ["ignore", fds.stdout, fds.stderr], detached: true });
399
+ } finally {
400
+ for (const name of ["stdout", "stderr"]) quietly(() => files.close(fds[name]));
401
+ }
402
+ const record = { kind: "change", label, letGo: false };
403
+ let over = false;
404
+ const forget = () => { for (const name of ["stdout", "stderr"]) quietly(() => files.unlink(paths[name])); };
405
+ function finish(error) {
406
+ if (over) return;
407
+ over = true;
408
+ remembered.delete(child);
409
+ if (record.letGo) return; // stop() let it go: nobody waits for its answer any more
410
+ const read = {};
411
+ let verdict = error;
412
+ for (const name of ["stdout", "stderr"]) {
413
+ const taken = quietly(() => files.read(paths[name], maxBuffer));
414
+ read[name] = taken?.text ?? "";
415
+ if (taken?.over && verdict == null) verdict = failure({ code: "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" });
416
+ }
417
+ forget();
418
+ callback(verdict ?? null, read.stdout, read.stderr);
419
+ }
420
+ child.once("exit", () => { running.delete(child); });
421
+ child.once("close", (code, signal) => finish(code === 0 && signal === null ? null : failure({ code, signal, killed: false })));
422
+ child.on("error", (error) => { if (!child.pid) { running.delete(child); finish(error); } });
423
+ record.letItGo = () => { record.letGo = true; quietly(() => child.unref()); forget(); remembered.delete(child); };
424
+ remembered.set(child, record);
425
+ if (Number.isInteger(child.pid)) running.set(child, label);
426
+ return child;
427
+ }
428
+
322
429
  /** The shared observer, with the shared reader over this exec and no reader of the TUI's own: a
323
430
  * failed read has the same reasons here as in the Desktop. It admits a deployment of the cycle
324
431
  * now running and no other. */
@@ -417,7 +524,7 @@ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onR
417
524
  * started beside two would be refused as busy and never read). The cycle is over when its
418
525
  * deployments are; with none served it reads nothing local. */
419
526
  async function cycle({ live }) {
420
- if (stopped || held) return;
527
+ if (stopped) return;
421
528
  flight = epoch;
422
529
  const mine = epoch, number = ++counter, at = clock();
423
530
  const over = () => stopped || mine !== epoch;
@@ -482,15 +589,13 @@ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onR
482
589
  rosterFlight = null;
483
590
  endReads({ cycles: true });
484
591
  },
485
- /** The terminal is lent to the kernel's viewer: from now until release() no cycle begins and
486
- * no roster read starts (a cycle the loop's timer or a request would begin does nothing and
487
- * emits nothing). What is in flight is not touched here: the caller made it void first, as at
488
- * a stop. Idempotent. */
489
- hold() { held = true; },
490
- /** The terminal is back: cycles begin again. The caller asks for a live one. */
491
- release() { held = false; },
492
592
  /** See askedExec. */
493
593
  exec: askedExec,
594
+ /** See changeExec. */
595
+ changeExec,
596
+ /** The changes still running, `[{ pid, label }]` (label: what the caller gave), whether or not
597
+ * this run still waits for them: for the line after leaving. Answers after stop() too. */
598
+ changes() { return [...running].map(([child, label]) => ({ pid: child.pid, label })); },
494
599
  /** Leave: synchronous and idempotent, safe before start(). The loop and the idle timer are
495
600
  * stopped, the observer disposed and every reading child ended (see `sever`), the roster's
496
601
  * included. A cycle in flight ends without emitting and without starting anything, and so
@@ -502,6 +607,11 @@ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onR
502
607
  observer.dispose();
503
608
  clearIdle();
504
609
  endReads();
610
+ // Every change is LET GO, never signalled: its handle no longer holds the process, and its two
611
+ // files are unlinked (the child goes on writing to them, and nothing is left behind). The
612
+ // private directory goes when it is empty.
613
+ for (const record of [...remembered.values()]) if (record.kind === "change") record.letItGo();
614
+ if (changeDir !== null) quietly(() => files.remove(changeDir));
505
615
  },
506
616
  /** The pids of the children remembered now (for tests). */
507
617
  children() { return [...remembered.keys()].map((child) => child.pid).filter((pid) => Number.isInteger(pid)); },
@@ -12,7 +12,7 @@
12
12
  import { ACTIONS, bindings } from "./actions.mjs";
13
13
  import { collapseKey, displayLine, instanceActs, instanceId, pendingEntry } from "./client.mjs";
14
14
  import { DETACH_KEY } from "./config.mjs";
15
- import { disclosure, openDecision, preflightLine, returnedLine, roster, switcher } from "./model.mjs";
15
+ import { BUTTON_ORDER, NOT_BUILT, actDecision, disclosure, openDecision, preflightLine, returnedLine, roster, switcher } from "./model.mjs";
16
16
  import { windowOf } from "./views/scroll.mjs";
17
17
 
18
18
  /** The longest filter, in UTF-16 units. */
@@ -35,13 +35,24 @@ const NO_FILTER = Object.freeze({ editing: false, query: "" });
35
35
  * `selected`, `top`, `detailTop` are the open view's; `places` keeps them for
36
36
  * the views left behind, and `collapsed` holds every view's keys (each carries its `open`).
37
37
  * `back`: the view under the help. `offered`: the deployments of `~/Agents` not served.
38
- * `opening`: the agent whose terminal is being opened, or null: `{ id, phase, name, machine,
39
- * routed }`, `phase` "preflight" while another machine is asked whether its session is there and
40
- * "lent" while the kernel's viewer has the terminal; `name`, `machine` and `routed` are the row's
41
- * as it was when Enter was pressed, for the line after. `outcome`: that line (the model's
42
- * `{ said, under }`), shown above the panes until the next key bound to an action, or null.
43
- * `detachKey`: tui.json's `open.detachKey`, the key that leaves an agent's terminal.
44
- * The roster is made from none of the three (lib/model.mjs MADE_FROM). */
38
+ * `opening`: the agent of another machine whose terminal is being opened, or null:
39
+ * `{ id, phase: "preflight", name, machine, routed }` while that machine is asked whether its
40
+ * session is there; `name`, `machine` and `routed` are the row's as it was when Enter was
41
+ * pressed, for the line after. `terminal`: the open terminal, or null (one at a time):
42
+ * `{ id, name, machine, routed, focus, zoom, status }`, `id` the row's instanceId and the next
43
+ * three the row's as it was when it was opened; `focus` "terminal" while what is typed goes to
44
+ * the agent and "list" while the TUI reads keys; `zoom` true while it has the whole body (only
45
+ * with the terminal's focus); `status` "starting" until the panel has its window, then "open".
46
+ * `outcome`: the line after an open (the model's `{ said, under }`), shown above the panes until
47
+ * the next key bound to an action, or null.
48
+ * `detachKey`: tui.json's `open.detachKey`, the back key: it takes the focus from the terminal.
49
+ * `act`: the confirmation open in the act view (see `actOpened`), or null; `acted` counts the
50
+ * confirmations opened in this run, so an answer for one that was closed is told apart.
51
+ * `starting`: id -> `{ verb, since }` of this run's starts and restarts whose child is still
52
+ * alive, whether or not the TUI still waits for its answer (the loop says when one is spawned and
53
+ * when it closes): no act opens on such a row.
54
+ * The roster is made from none of `opening`, `terminal`, `outcome`, `act`, `acted` and `starting`
55
+ * (lib/model.mjs MADE_FROM). */
45
56
  export function initialState({ deployment = null, cli, home, entry = null, actions = ACTIONS, ascii = false, detachKey = DETACH_KEY }) {
46
57
  return Object.freeze({
47
58
  view: deployment === null ? "switcher" : "instances", back: deployment === null ? "switcher" : "instances",
@@ -52,7 +63,7 @@ export function initialState({ deployment = null, cli, home, entry = null, actio
52
63
  selected: null, collapsed: new Set(), filter: NO_FILTER, focus: "list", top: 0, loose: false, detailTop: 0, places: new Map(), unread: new Map(),
53
64
  switcher: Object.freeze({ editing: false, query: "", selected: null, top: 0, loose: false, line: null, refused: null }),
54
65
  offered: Object.freeze({ offered: Object.freeze([]), limited: false }),
55
- helpTop: 0, actions, ascii, detachKey, opening: null, outcome: null,
66
+ helpTop: 0, actions, ascii, detachKey, opening: null, terminal: null, outcome: null, act: null, acted: 0, starting: new Map(),
56
67
  });
57
68
  }
58
69
 
@@ -124,7 +135,9 @@ function settled(state, taken) {
124
135
  const now = roster(taken);
125
136
  if (taken.open !== null && now.gone) {
126
137
  const places = new Map(taken.places); places.delete(taken.open);
127
- return { state: toSwitcher(next(taken, { open: null, places, selected: null, top: 0, loose: false, detailTop: 0, focus: "list", filter: NO_FILTER, back: "switcher" }), "gone"), effect: { offer: true } };
138
+ // A confirmation open over that view is closed with it: what it sent goes on.
139
+ const dismiss = taken.act !== null ? { dismiss: taken.act.n } : {};
140
+ return { state: toSwitcher(next(taken, { open: null, places, selected: null, top: 0, loose: false, detailTop: 0, focus: "list", filter: NO_FILTER, back: "switcher", act: null }), "gone"), effect: { offer: true, ...dismiss } };
128
141
  }
129
142
  const before = roster(state);
130
143
  const unknown = new Set([...taken.unread.values()].flatMap((ids) => [...ids]));
@@ -289,56 +302,191 @@ function switched(state, action, page) {
289
302
  * (one outcome of the roster read), `{ collecting }`, `{ offered: { offered, limited } }` (the
290
303
  * deployments of `~/Agents` not served), `{ admitted: <deployment>, at }` and `{ refused: <path> }`
291
304
  * (what a picked folder turned out to be).
292
- * Opening an agent gives three more: `{ prepared: { id, error? } }` (the preflight of another
305
+ * Opening an agent gives five more: `{ prepared: { id, error? } }` (the preflight of another
293
306
  * machine's agent ended: `error` is what the shared prepareRemoteTerm threw), `{ given: true }`
294
- * (the loop gave the preflight up itself: a suspend) and `{ returned: { id, status, stderr } }`
295
- * (the viewer closed: its exit status as Node reports it, and the stderr it kept).
307
+ * (the loop gave the preflight up itself: a suspend), `{ shown: { id } }` (the panel has the
308
+ * viewer's window), `{ returned: { id, status, stderr, asked, refused } }` (the viewer ended: what
309
+ * its pane wrote of its exit status and stderr, whether it was closed because the TUI asked, and
310
+ * the panel's refusal when it started none: model.mjs returnedLine) and
311
+ * `{ back: true }` (the back key was typed in the terminal).
296
312
  * An effect is something only the loop can do: "quit", "suspend", "redraw", or an object with
297
313
  * any of `refresh: { live }` (read now), `offer: true` (list `~/Agents` again),
298
- * `admit: <path>` (ask whether a picked folder is a deployment), `open: <decision>` (open the
299
- * agent's terminal: the model's openDecision, with its target), `lend: <id>` (the preflight is
300
- * over: start the viewer it prepared) and `abandon: true` (give the preflight up); or null.
314
+ * `admit: <path>` (ask whether a picked folder is a deployment), `close: <id>` (close the open
315
+ * terminal; when an `open` comes with it, before that open), `open: <decision>` (open the agent's
316
+ * terminal: the model's openDecision, with its target), `panel: <id>` (the preflight is over:
317
+ * start the viewer it prepared in the panel) and `abandon: true` (give the preflight up); or null.
301
318
  * The line after an open stands until the next key that is bound to an action: a key bound to
302
- * nothing (a stray detach key is no key at all) leaves it. */
319
+ * nothing (a stray back key is no key at all) leaves it. */
303
320
  export function reduce(state, event, keymap = bindings(state.actions)) {
304
321
  if (state.outcome !== null && typeof event.key === "string" && keymap.has(event.key)) state = next(state, { outcome: null });
305
- return reduced(state, event, keymap);
322
+ const step = reduced(state, event, keymap);
323
+ // The terminal has the focus only while the list of instances is shown: anything that shows
324
+ // another view (a workspace gone, which shows the switcher) gives the focus back to the list.
325
+ const t = step.state.terminal;
326
+ if (t?.focus !== "terminal") return step;
327
+ if (step.state.view !== "instances") return { ...step, state: next(step.state, { terminal: Object.freeze({ ...t, focus: "list", zoom: false }) }) };
328
+ // While it has the focus, what lies under it is the list: the back key returns there, never to
329
+ // the detail. A filter field open when the focus came (a preflight that ended while it was
330
+ // typed in) is settled, its text kept as Enter keeps it: no key goes to it any more.
331
+ const under = step.state.focus !== "list" || step.state.filter.editing;
332
+ return under ? { ...step, state: next(step.state, { focus: "list", filter: Object.freeze({ ...step.state.filter, editing: false }) }) } : step;
306
333
  }
307
334
 
335
+ /** The terminal of an open decision (the model's openDecision), starting, with the focus. */
336
+ const startingTerminal = ({ id, name, machine, routed }) => Object.freeze({ id, name, machine, routed, focus: "terminal", zoom: false, status: "starting" });
337
+ /** The open terminal with what changes of it. */
338
+ const terminalWith = (state, changes) => next(state, { terminal: Object.freeze({ ...state.terminal, ...changes }) });
339
+
308
340
  /** The preflight of another machine's agent ended. Given up meanwhile (Esc, a suspend, a second
309
341
  * open): dropped. Failed: the line that says so, unless it is the person's own giving up. Else
310
- * the viewer is started, unless the row it is for has gone from the roster since. */
342
+ * the viewer is started in the panel, unless the row it is for has gone from the roster since. */
311
343
  function prepared(state, { id, error }) {
312
344
  const opening = state.opening;
313
345
  if (opening === null || opening.id !== id || opening.phase !== "preflight") return { state, effect: null };
314
346
  if (error !== undefined) return { state: next(state, { opening: null, outcome: preflightLine(opening, error) }), effect: null };
315
347
  if (!roster(state).instances.some((row) => instanceId(row) === id)) return { state: next(state, { opening: null }), effect: null };
316
- return { state: next(state, { opening: Object.freeze({ ...opening, phase: "lent" }) }), effect: { lend: id } };
348
+ return { state: next(state, { opening: null, terminal: startingTerminal(opening) }), effect: { panel: id } };
317
349
  }
318
350
 
319
- /** The viewer closed: the line that says what happened, and the instances read again at once
320
- * (an exit status says nothing of the agent but that it was left by the key). */
321
- function returned(state, { id, status, stderr }) {
322
- const opening = state.opening;
323
- if (opening === null || opening.id !== id) return { state, effect: null };
324
- return { state: next(state, { opening: null, outcome: returnedLine(opening, status, stderr) }), effect: { refresh: { live: true } } };
351
+ /** The viewer of the open terminal ended: the right side is the detail's again, the focus the
352
+ * list's, the line says what happened (nothing, when the person closed it), and the instances are
353
+ * read again at once. It is never opened again on its own: Enter opens it. An end of a terminal
354
+ * that is no longer the open one (closed by the person, then reported) changes nothing. */
355
+ function returned(state, { id, status, stderr, asked = false, refused = null }) {
356
+ const t = state.terminal;
357
+ if (t === null || t.id !== id) return { state, effect: null };
358
+ return { state: next(state, { terminal: null, outcome: returnedLine(t, status, stderr, { asked, refused }) }), effect: { refresh: { live: true } } };
325
359
  }
326
360
 
327
- /** Enter in the list of instances: the selected agent's terminal, or the line that says why not.
328
- * Nothing while an open is under way. */
361
+ /** Enter in the list of instances: on the row whose terminal is open, the focus goes to it; on
362
+ * another, the selected agent's terminal is opened (the open one is closed first: one at a time),
363
+ * or the line says why not. Nothing while another machine is asked first. */
329
364
  function openAgent(state, r, at) {
330
365
  if (state.opening !== null || at < 0) return { state, effect: null };
331
- const row = r.items[at].row, decision = openDecision(state, row, instanceActs(row));
366
+ const row = r.items[at].row, t = state.terminal;
367
+ if (t !== null && t.id === instanceId(row)) return { state: terminalWith(state, { focus: "terminal", zoom: false }), effect: null };
368
+ const decision = openDecision(state, row, instanceActs(row));
332
369
  if (!decision.open) return { state: next(state, { outcome: decision.said }), effect: null };
333
- const opening = Object.freeze({ id: decision.id, phase: decision.routed ? "preflight" : "lent", name: decision.name, machine: decision.machine, routed: decision.routed });
334
- return { state: next(state, { opening, outcome: null }), effect: { open: decision } };
370
+ const close = t === null ? {} : { close: t.id };
371
+ if (decision.routed) {
372
+ const opening = Object.freeze({ id: decision.id, phase: "preflight", name: decision.name, machine: decision.machine, routed: true });
373
+ return { state: next(state, { opening, terminal: null, outcome: null }), effect: { ...close, open: decision } };
374
+ }
375
+ return { state: next(state, { terminal: startingTerminal(decision), outcome: null }), effect: { ...close, open: decision } };
376
+ }
377
+
378
+ /** The keys of the open terminal from the list: zoom gives it the focus and the whole body, and
379
+ * close ends its viewer (the agent keeps running) and gives the right side back to the detail. */
380
+ function terminalKey(state, action) {
381
+ const t = state.terminal;
382
+ if (t === null) return { state, effect: null };
383
+ if (action === "zoom") return { state: terminalWith(state, { focus: "terminal", zoom: true }), effect: null };
384
+ return { state: next(state, { terminal: null }), effect: { close: t.id } };
385
+ }
386
+
387
+ /** The keys of the act view that are not the action table's: the focus moves with these and with
388
+ * no printable key, so nothing typed or pasted as text reaches a button. */
389
+ const FOCUS_KEYS = Object.freeze({ left: -1, "shift+tab": -1, right: 1, tab: 1 });
390
+
391
+ /** An act key in the list of instances: the confirmation it opens, or the line that says why not
392
+ * (lib/model.mjs actDecision, over the row's instanceActs answer read now). A stop or a retire
393
+ * asks the loop for the shared confirmation (`act`), which reads the plan; a start or a restart
394
+ * opens the TUI's own confirmation, and nothing is asked of the loop until it is pressed. The
395
+ * focus starts on the first button, Cancel. Nothing while an open is under way. */
396
+ function actOn(state, r, at, verb) {
397
+ if (state.opening !== null || at < 0) return { state, effect: null };
398
+ const row = r.items[at].row, decision = actDecision(state, row, instanceActs(row), verb);
399
+ if (!decision.open) return { state: next(state, { outcome: decision.said }), effect: null };
400
+ const n = state.acted + 1;
401
+ const base = { n, kind: decision.kind, verb, id: decision.id, name: decision.name, machine: decision.machine, home: decision.home, focus: "close", movedIn: null, top: 0 };
402
+ const act = decision.kind === "start"
403
+ ? Object.freeze({ ...base, phase: "review", offers: Object.freeze(["close", "apply"]), answer: null })
404
+ : Object.freeze({ ...base, phase: "reading", offers: Object.freeze(["close"]), outcome: null, notice: null, running: null, view: null, plan: null });
405
+ return { state: next(state, { view: "act", back: "instances", act, acted: n, outcome: null }), effect: decision.kind === "start" ? null : { act: { n, verb, id: decision.id, row, label: decision.label } } };
406
+ }
407
+
408
+ /** The confirmation closed by the person (Esc, or its Cancel or Close pressed): the view goes, and
409
+ * the loop is told; a plan read, an apply or a start it sent goes on. */
410
+ const actClosed = (state) => ({ state: next(state, { view: "instances", back: "instances", act: null }), effect: { dismiss: state.act.n } });
411
+
412
+ /** A key in the act view. Left/Right and Tab/Shift+Tab move the focus among the buttons, Enter
413
+ * presses the one that has it, Esc closes, Space sets the plan's choice, the movement keys scroll
414
+ * the content; quit, suspend and redraw keep their actions; every other key does nothing.
415
+ * A press of the act's own button in the same read of input as the move that put the focus on
416
+ * it is ignored (`read`): a paste, with bracketed paste unsupported, cannot both move and press. */
417
+ function inAct(state, event, action) {
418
+ const a = state.act, stay = { state, effect: null };
419
+ if (action === "quit" || action === "suspend" || action === "redraw") return { state, effect: action };
420
+ if (event.key === "escape" || action === "close") return actClosed(state);
421
+ const put = (changes) => next(state, { act: Object.freeze({ ...a, ...changes }) });
422
+ if (Object.hasOwn(FOCUS_KEYS, event.key)) {
423
+ const at = Math.max(0, a.offers.indexOf(a.focus)), to = Math.min(Math.max(0, at + FOCUS_KEYS[event.key]), a.offers.length - 1);
424
+ const focus = a.offers[to];
425
+ return focus === a.focus ? stay : { state: put({ focus, movedIn: focus === "apply" ? event.read ?? null : null }), effect: null };
426
+ }
427
+ if (event.key === "enter") {
428
+ if (a.focus === "apply" && event.read !== undefined && a.movedIn === event.read) return stay;
429
+ if (a.focus === "close") return actClosed(state);
430
+ if (a.kind === "start") {
431
+ if (a.focus !== "apply" || a.phase !== "review") return stay;
432
+ const row = roster(state).instances.find((each) => instanceId(each) === a.id) ?? null;
433
+ return { state: put({ phase: "starting", offers: Object.freeze(["close"]), focus: "close", movedIn: null }), effect: { start: { n: a.n, verb: a.verb, id: a.id, row } } };
434
+ }
435
+ const call = { apply: "apply", refresh: "refresh", "check-again": "checkAgain" }[a.focus];
436
+ return call ? { state, effect: { call: { n: a.n, method: call } } } : stay;
437
+ }
438
+ if (event.key === "space" || event.text === " ") {
439
+ const choice = a.kind === "lifecycle" && (a.phase === "review" || a.phase === "reading") ? a.plan?.choices.find((each) => each.offered) : null;
440
+ return choice ? { state, effect: { call: { n: a.n, method: "setChoice", args: [choice.id, !choice.value] } } } : stay;
441
+ }
442
+ if (MOVES.includes(action)) {
443
+ const count = event.extent ?? 0, height = event.room ?? 1;
444
+ const from = windowOf({ top: a.top, count, height }).top;
445
+ return { state: put({ top: windowOf({ top: moved(action, from, count, height), count, height }).top }), effect: null };
446
+ }
447
+ return stay;
448
+ }
449
+
450
+ /** What the loop says of the confirmation and of a start (`{ acted }`):
451
+ * { n, confirmation: { phase, outcome, offers, notice, running, view } } the shared
452
+ * confirmation's state() and view() after each step it told (stop, retire);
453
+ * { n, answer } a start's or restart's answer (the shared startInstance's): shown when its
454
+ * confirmation is still open, and the rows are read again (live) whatever it was;
455
+ * { spawned: { id, verb }, at } a start's child began (`at`: ms since the epoch);
456
+ * { closed: id } that child closed: the row takes acts again, and is read again (live).
457
+ * An answer for a confirmation that was closed (another `n`) changes nothing on screen. When the
458
+ * buttons change, the focus goes back to the first. */
459
+ function acted(state, event) {
460
+ const a = state.act, mine = a !== null && event.n === a.n;
461
+ if (event.spawned !== undefined) return { state: next(state, { starting: new Map(state.starting).set(event.spawned.id, Object.freeze({ verb: event.spawned.verb, since: event.at ?? null })) }), effect: null };
462
+ if (event.closed !== undefined) {
463
+ if (!state.starting.has(event.closed)) return { state, effect: { refresh: { live: true } } };
464
+ const starting = new Map(state.starting); starting.delete(event.closed);
465
+ return { state: next(state, { starting }), effect: { refresh: { live: true } } };
466
+ }
467
+ if (event.answer !== undefined) {
468
+ const shown = mine && a.kind === "start" ? next(state, { act: Object.freeze({ ...a, phase: "settled", offers: Object.freeze(["close"]), focus: "close", movedIn: null, answer: event.answer }) }) : state;
469
+ return { state: shown, effect: { refresh: { live: true } } };
470
+ }
471
+ if (event.confirmation !== undefined && mine && a.kind === "lifecycle") {
472
+ const c = event.confirmation, view = c.view ?? null;
473
+ const plan = view && typeof view.question === "string" ? view : view?.kind === "reading" && view.kept ? a.plan : null;
474
+ const offers = Object.freeze(BUTTON_ORDER.filter((offer) => (c.offers ?? []).includes(offer)));
475
+ const same = offers.length === a.offers.length && offers.every((offer, i) => offer === a.offers[i]);
476
+ return { state: next(state, { act: Object.freeze({ ...a, phase: c.phase, outcome: c.outcome ?? null, notice: c.notice ?? null, running: c.running ?? null, view, plan, offers,
477
+ ...(same ? {} : { focus: offers[0] ?? "close", movedIn: null }) }) }), effect: null };
478
+ }
479
+ return { state, effect: null };
335
480
  }
336
481
 
337
482
  function reduced(state, event, keymap) {
338
483
  const stay = { state, effect: null };
484
+ if (event.acted !== undefined) return acted(state, event.acted);
339
485
  if (event.prepared !== undefined) return prepared(state, event.prepared);
340
486
  if (event.given !== undefined) return state.opening?.phase === "preflight" ? { state: next(state, { opening: null }), effect: null } : stay;
341
487
  if (event.returned !== undefined) return returned(state, event.returned);
488
+ if (event.shown !== undefined) return state.terminal?.id === event.shown.id ? { state: terminalWith(state, { status: "open" }), effect: null } : stay;
489
+ if (event.back !== undefined) return state.terminal?.focus === "terminal" ? { state: terminalWith(state, { focus: "list", zoom: false }), effect: null } : stay;
342
490
  if (event.entry !== undefined) return took(state, event);
343
491
  if (event.roster !== undefined) return heard(state, event.roster);
344
492
  if (event.collecting !== undefined) return { state: event.collecting === state.collecting ? state : next(state, { collecting: event.collecting === true }), effect: null };
@@ -351,6 +499,7 @@ function reduced(state, event, keymap) {
351
499
  if (typeof event.key !== "string") return stay;
352
500
  const action = keymap.get(event.key);
353
501
  if (field) return edited(state, field, event, action);
502
+ if (state.view === "act" && state.act !== null) return inAct(state, event, action);
354
503
  const page = Math.max(1, Number.isInteger(event.page) ? event.page : 1);
355
504
  // A pane that scrolls on its own (the help, the detail) moves from where it is DRAWN: the top
356
505
  // the state holds may lie past the end since the terminal grew, and the view shows it corrected.
@@ -386,6 +535,10 @@ function reduced(state, event, keymap) {
386
535
  switch (action) {
387
536
  case "filter": return { state: next(state, { focus: "list", filter: Object.freeze({ ...state.filter, editing: true }) }), effect: null };
388
537
  case "open": return openAgent(state, r, at);
538
+ case "zoom": case "close-terminal": return terminalKey(state, action);
539
+ // The views not built yet: the line says what to run instead.
540
+ case "souls": case "capabilities": return { state: next(state, { outcome: NOT_BUILT[action] }), effect: null };
541
+ case "stop": case "retire": case "start": case "restart": return actOn(state, r, at, action);
389
542
  case "detail": return at < 0 ? stay : { state: next(state, { focus: state.focus === "detail" ? "list" : "detail" }), effect: null };
390
543
  case "up": case "down": case "top": case "bottom": case "page-up": case "page-down": {
391
544
  if (state.focus === "detail") return { state: next(state, { detailTop: scrolled(state.detailTop) }), effect: null };