@awebai/oats 0.55.1 → 0.57.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 (82) hide show
  1. package/bin/oats.mjs +96 -72
  2. package/docs/capabilities.md +67 -3
  3. package/docs/design/2026-09-23-workspace-module-contracts.md +27 -3
  4. package/docs/desktop-cli-api.md +375 -37
  5. package/docs/desktop-instance-start.md +105 -12
  6. package/docs/desktop.md +65 -11
  7. package/docs/execution-targets.md +184 -9
  8. package/docs/harness-trust.md +128 -11
  9. package/docs/implementation.md +153 -11
  10. package/docs/integrations.md +5 -3
  11. package/docs/knowledge.md +117 -43
  12. package/docs/official-catalog.md +3 -3
  13. package/docs/packages.md +12 -12
  14. package/docs/release-lane.md +26 -1
  15. package/docs/release-notes/v0.56.0.md +699 -0
  16. package/docs/release-notes/v0.57.0.md +283 -0
  17. package/docs/schedules.md +8 -3
  18. package/docs/servers.md +21 -5
  19. package/docs/souls-and-instances.md +134 -19
  20. package/docs/tui.md +215 -31
  21. package/docs/upgrading.md +4 -1
  22. package/docs/workspaces.md +26 -6
  23. package/lib/automations.mjs +3 -4
  24. package/lib/bounded-read.mjs +18 -0
  25. package/lib/capability-show.mjs +13 -2
  26. package/lib/claim.mjs +3 -4
  27. package/lib/core.mjs +919 -278
  28. package/lib/errors.mjs +39 -0
  29. package/lib/harness-trust-write.mjs +119 -40
  30. package/lib/harness-trust.mjs +31 -18
  31. package/lib/instance-inspect.mjs +160 -11
  32. package/lib/instance-lifecycle.mjs +90 -37
  33. package/lib/packages.mjs +8 -5
  34. package/lib/pi-bridge.mjs +18 -19
  35. package/lib/remote.mjs +88 -51
  36. package/lib/retire-output.mjs +9 -4
  37. package/lib/schedule.mjs +3 -4
  38. package/lib/servers.mjs +39 -6
  39. package/lib/session-viewer.mjs +25 -1
  40. package/lib/triggers.mjs +3 -4
  41. package/lib/workspace.mjs +6 -6
  42. package/lib/worktree.mjs +33 -8
  43. package/lib/write-through-private-file.mjs +26 -0
  44. package/package-catalog.json +2 -2
  45. package/package.json +1 -1
  46. package/packages/client/cli-adapter.mjs +108 -13
  47. package/packages/client/cli-locator.mjs +16 -14
  48. package/packages/client/deployment-panel.mjs +4 -3
  49. package/packages/client/display-text.mjs +2 -1
  50. package/packages/client/instance-events-contract.mjs +4 -3
  51. package/packages/client/instance-lifecycle.mjs +235 -0
  52. package/packages/client/instance-presentation.mjs +9 -0
  53. package/packages/client/instance-tree.mjs +10 -8
  54. package/packages/client/kernel-lines.mjs +3 -3
  55. package/packages/client/launch-contract.mjs +11 -0
  56. package/packages/client/launch-prompt-outcome.mjs +1 -1
  57. package/packages/client/lifecycle-cli.mjs +12 -6
  58. package/packages/client/lifecycle-confirmation.mjs +407 -0
  59. package/packages/client/lifecycle-contract.mjs +6 -2
  60. package/packages/client/own-codes.mjs +1 -0
  61. package/packages/client/panel-views.mjs +39 -2
  62. package/packages/client/readiness-contract.mjs +2 -2
  63. package/packages/client/remote-roster.mjs +50 -5
  64. package/packages/client/roster-sections.mjs +3 -3
  65. package/packages/client/session-start.mjs +98 -0
  66. package/packages/client/start-gate.mjs +46 -0
  67. package/packages/client/start-messages.mjs +17 -0
  68. package/packages/client/workspace-views.mjs +2 -2
  69. package/packages/tui/README.md +21 -8
  70. package/packages/tui/lib/actions.mjs +11 -2
  71. package/packages/tui/lib/client.mjs +9 -2
  72. package/packages/tui/lib/config.mjs +39 -9
  73. package/packages/tui/lib/main.mjs +168 -20
  74. package/packages/tui/lib/model.mjs +315 -13
  75. package/packages/tui/lib/open.mjs +45 -0
  76. package/packages/tui/lib/read.mjs +171 -16
  77. package/packages/tui/lib/store.mjs +171 -10
  78. package/packages/tui/lib/term/tty.mjs +71 -12
  79. package/packages/tui/lib/views/act.mjs +85 -0
  80. package/packages/tui/lib/views/frame.mjs +145 -33
  81. package/packages/tui/lib/views/help.mjs +46 -11
  82. package/skills/oats-getting-started/SKILL.md +6 -3
@@ -1,16 +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
- // This version of the TUI ONLY READS: nothing here changes a deployment, and nothing writes a file.
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: lib/open.mjs.)
5
9
  // No function of this module decodes a kernel answer. Each one passes values between the shared
6
10
  // functions (client.mjs), which decide what a roster, a row and a failed read are, once, for both
7
11
  // clients: the TUI never writes "stopped" for a row and never builds the collector's input by hand.
8
12
  import { execFile as nodeExecFile, spawn as nodeSpawn } from "node:child_process";
9
- 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";
10
15
  import { basename, dirname, join } from "node:path";
11
16
  import { fileURLToPath } from "node:url";
12
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";
13
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
+
14
35
  /** The kernel this TUI shipped with: the absolute path of the install's own bin/oats.mjs, found by
15
36
  * URL from this file. Every kernel call is `node <this path> …`, so the TUI depends on no shebang,
16
37
  * no execute bit and no `PATH`, and never talks to another install's kernel. */
@@ -145,6 +166,29 @@ export function probeKernel({ bin = KERNEL_BIN, env = process.env, execFile = no
145
166
  });
146
167
  }
147
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
+
148
192
  /** A child that did not end well, as execFile reports one: the facts on an Error, and no text of the child's. */
149
193
  const failure = (facts) => Object.assign(new Error("the child did not end with an answer"), facts);
150
194
  /** A child the reader ended itself: its time limit, or the reader giving it up. As execFile's timeout. */
@@ -154,7 +198,7 @@ const said = (error) => String(error?.message ?? error);
154
198
 
155
199
  /** The reader of a run: its cycles over every served deployment, the roster of other machines,
156
200
  * their children, and the way out.
157
- * -> { start(), request({ live }), touch(), voidInFlight(), stop(), children() }
201
+ * -> { start(), request({ live }), touch(), voidInFlight(), hold(), release(), exec, stop(), children() }
158
202
  *
159
203
  * `cli` is probeKernel's record (`cli.bin` the absolute path of bin/oats.mjs). The reader keeps no
160
204
  * answer of its own: what a run holds is the caller's store, asked for when it is needed.
@@ -186,20 +230,33 @@ const said = (error) => String(error?.message ?? error);
186
230
  * list of options, `detached` is not one of them, and a child it starts stays in the TUI's group
187
231
  * whatever it is asked. `run` below is the part of execFile's contract the shared readers use.
188
232
  *
189
- * ENDING A CHILD holds because this version only reads. A KERNEL CALL THAT CHANGES SOMETHING MUST
190
- * NEVER BE KILLED BY THE TUI: a killed stop or start leaves a marker that refuses every later one.
191
- * So every child is remembered with its kind, only kind "read" is ever signalled, and a later
192
- * 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 is lib/open.mjs's, and
234
+ * 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.
193
238
  *
194
- * `timers` are the loop's, the idle timer's and the children's time limits (for tests). */
195
- 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 }) {
196
- /** child -> { kind, exited, giveUp }: every child that has not ended and was not ended. */
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. */
197
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;
198
253
  let started = false, stopped = false, idleTimer = null;
199
254
  /** `counter` numbers the cycles. `epoch` moves when the cycles in flight are made void; `flight`
200
255
  * is the epoch the cycle now running began in (the loop runs one at a time). `served` is what
201
256
  * getServed() answered at the start of that cycle. */
202
257
  let counter = 0, epoch = 0, flight = 0, served = [];
258
+ /** The terminal is lent (hold()): no cycle and no roster read starts until release(). */
259
+ let held = false;
203
260
  /** The roster of other machines. `rosterFlight` is the read in flight (a token of its own, so an
204
261
  * answer knows whether it is still awaited), or null. `rosterEnded` is now() when the last read
205
262
  * that was not given up ended, or null while none has. `gatedSaid`: a kernel that reads no
@@ -214,9 +271,9 @@ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onR
214
271
  * other options go to spawn as they are, with `detached: true` added. Returns the child.
215
272
  * The child is forgotten when it ends: `close`, `error` for one that did not start, or the
216
273
  * moment the reader ends it. */
217
- function run(kind, args, { timeout = 0, maxBuffer = Infinity, encoding = "utf8", ...rest }, callback) {
274
+ function run(kind, args, { timeout = 0, maxBuffer = Infinity, encoding = "utf8", ...rest }, callback, { asked = false } = {}) {
218
275
  const child = spawn(process.execPath, args, { ...rest, detached: true });
219
- const printed = { stdout: "", stderr: "" }, record = { kind, exited: false, giveUp };
276
+ const printed = { stdout: "", stderr: "" }, record = { kind, exited: false, giveUp, asked };
220
277
  let over = false, severed = false, verdict = null, timer = null;
221
278
  function finish(error) {
222
279
  if (over) return;
@@ -281,8 +338,9 @@ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onR
281
338
  remembered.set(child, record);
282
339
  return child;
283
340
  }
284
- function endReads() {
285
- for (const record of [...remembered.values()]) if (record.kind === "read") record.giveUp(ended());
341
+ /** End the reads remembered: every one, or (`cycles`) only those a cycle or the roster started. */
342
+ function endReads({ cycles = false } = {}) {
343
+ for (const record of [...remembered.values()]) if (record.kind === "read" && !(cycles && record.asked)) record.giveUp(ended());
286
344
  }
287
345
 
288
346
  /** The exec handed to the shared readers: execFile's signature, for `node <bin> <argv…>` (see
@@ -294,6 +352,82 @@ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onR
294
352
  if (stopped || flight !== epoch) throw new Error("this read was given up before it started");
295
353
  return run("read", [bin, ...argv], options.env === undefined ? { ...options, env } : options, callback);
296
354
  }
355
+ /** The exec of a read the loop asks for itself, outside every cycle: the preflight of an agent
356
+ * on another machine (`oats session inspect`, through the shared prepareRemoteTerm). The same
357
+ * child as a cycle's (kind "read", a session of its own, the reader's environment where the
358
+ * options name none, ended on every way out), not made void by voidInFlight(): the loop ends it
359
+ * through `signal`, which ends the child's whole group as the reader's own giving up does. A
360
+ * `signal` already aborted starts nothing. It throws after stop(). */
361
+ function askedExec(bin, argv, { signal, ...options }, callback) {
362
+ if (stopped) throw new Error("the reader has stopped");
363
+ if (signal?.aborted) throw new Error("this read was given up before it started");
364
+ const child = run("read", [bin, ...argv], options.env === undefined ? { ...options, env } : options, callback, { asked: true });
365
+ if (signal) {
366
+ const record = remembered.get(child);
367
+ const abandon = () => record?.giveUp(ended());
368
+ signal.addEventListener("abort", abandon, { once: true });
369
+ child.once("close", () => signal.removeEventListener("abort", abandon));
370
+ }
371
+ return child;
372
+ }
373
+ /** THE EXEC OF A CHANGE: a stop or retire apply (the boundary's call with `detached: true`), a
374
+ * start or a restart (the shared cliStart's). execFile's signature for `node <bin> <argv…>`, in
375
+ * a session of its own, outside every cycle: it is never made void by voidInFlight() and never
376
+ * signalled, not by `sever`, not by stop(), not at a time limit (a `timeout` given is not
377
+ * armed: the shared callers end their wait, never the child). `options.label` is the caller's
378
+ * `{ verb, name }`, kept for the line after leaving (`changes()`), and is not passed on.
379
+ * ITS OUTPUT GOES TO FILES, NEVER TO A PIPE. Before the spawn two files are opened in the run's
380
+ * private directory (made once, mode 0700, under the OS temp dir) and given to the child as its
381
+ * stdout and stderr; stdin is `ignore`. The TUI's own copies are closed after the spawn. So
382
+ * whatever the TUI does (quits, is stopped, loses its terminal) the child can always write, and
383
+ * nothing it writes meets EPIPE or SIGPIPE. When the child closes, both files are read back,
384
+ * each bounded by `maxBuffer` (over it: ERR_CHILD_PROCESS_STDIO_MAXBUFFER, as a read answers),
385
+ * deleted, and the callback is called as execFile calls it, with text (UTF-8).
386
+ * It throws after stop(): nothing new starts on the way out. Returns the child. */
387
+ function changeExec(bin, argv, { label = null, timeout: _never, maxBuffer = Infinity, encoding: _utf8, ...options }, callback) {
388
+ if (stopped) throw new Error("the reader has stopped");
389
+ if (changeDir === null) changeDir = files.dir();
390
+ const number = ++changeCount, paths = { stdout: join(changeDir, `${number}.out`), stderr: join(changeDir, `${number}.err`) };
391
+ const fds = {};
392
+ try {
393
+ for (const name of ["stdout", "stderr"]) fds[name] = files.open(paths[name]);
394
+ } catch (error) {
395
+ for (const name of ["stdout", "stderr"]) if (fds[name] !== undefined) { quietly(() => files.close(fds[name])); quietly(() => files.unlink(paths[name])); }
396
+ throw error;
397
+ }
398
+ let child;
399
+ try {
400
+ child = spawn(process.execPath, [bin, ...argv], { ...(options.env === undefined ? { ...options, env } : options), stdio: ["ignore", fds.stdout, fds.stderr], detached: true });
401
+ } finally {
402
+ for (const name of ["stdout", "stderr"]) quietly(() => files.close(fds[name]));
403
+ }
404
+ const record = { kind: "change", label, letGo: false };
405
+ let over = false;
406
+ const forget = () => { for (const name of ["stdout", "stderr"]) quietly(() => files.unlink(paths[name])); };
407
+ function finish(error) {
408
+ if (over) return;
409
+ over = true;
410
+ remembered.delete(child);
411
+ if (record.letGo) return; // stop() let it go: nobody waits for its answer any more
412
+ const read = {};
413
+ let verdict = error;
414
+ for (const name of ["stdout", "stderr"]) {
415
+ const taken = quietly(() => files.read(paths[name], maxBuffer));
416
+ read[name] = taken?.text ?? "";
417
+ if (taken?.over && verdict == null) verdict = failure({ code: "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" });
418
+ }
419
+ forget();
420
+ callback(verdict ?? null, read.stdout, read.stderr);
421
+ }
422
+ child.once("exit", () => { running.delete(child); });
423
+ child.once("close", (code, signal) => finish(code === 0 && signal === null ? null : failure({ code, signal, killed: false })));
424
+ child.on("error", (error) => { if (!child.pid) { running.delete(child); finish(error); } });
425
+ record.letItGo = () => { record.letGo = true; quietly(() => child.unref()); forget(); remembered.delete(child); };
426
+ remembered.set(child, record);
427
+ if (Number.isInteger(child.pid)) running.set(child, label);
428
+ return child;
429
+ }
430
+
297
431
  /** The shared observer, with the shared reader over this exec and no reader of the TUI's own: a
298
432
  * failed read has the same reasons here as in the Desktop. It admits a deployment of the cycle
299
433
  * now running and no other. */
@@ -392,7 +526,7 @@ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onR
392
526
  * started beside two would be refused as busy and never read). The cycle is over when its
393
527
  * deployments are; with none served it reads nothing local. */
394
528
  async function cycle({ live }) {
395
- if (stopped) return;
529
+ if (stopped || held) return;
396
530
  flight = epoch;
397
531
  const mine = epoch, number = ++counter, at = clock();
398
532
  const over = () => stopped || mine !== epoch;
@@ -444,6 +578,8 @@ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onR
444
578
  * children remembered are ended as stop() ends them. The reader stays usable: the loop goes
445
579
  * on, and the next cycle (the caller requests a live one on the return) emits with the next
446
580
  * number. A cycle requested but not begun is not in flight: it runs after the return.
581
+ * A read the loop asked for itself (the preflight, `exec`) is not a cycle's: it is left as it
582
+ * is, and the loop gives it up through its signal.
447
583
  * THE SAME HOLDS FOR A ROSTER READ IN FLIGHT, which is not part of a cycle and may outlive
448
584
  * the one that began it: its child is ended, whatever it answers is dropped (no onRoster; the
449
585
  * caller tells its store that nothing is being collected), and it is no longer in flight, so
@@ -453,8 +589,22 @@ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onR
453
589
  voidInFlight() {
454
590
  epoch++;
455
591
  rosterFlight = null;
456
- endReads();
592
+ endReads({ cycles: true });
457
593
  },
594
+ /** The terminal is lent to the kernel's viewer: from now until release() no cycle begins and
595
+ * no roster read starts (a cycle the loop's timer or a request would begin does nothing and
596
+ * emits nothing). What is in flight is not touched here: the caller made it void first, as at
597
+ * a stop. Idempotent. */
598
+ hold() { held = true; },
599
+ /** The terminal is back: cycles begin again. The caller asks for a live one. */
600
+ release() { held = false; },
601
+ /** See askedExec. */
602
+ exec: askedExec,
603
+ /** See changeExec. */
604
+ changeExec,
605
+ /** The changes still running, `[{ pid, label }]` (label: what the caller gave), whether or not
606
+ * this run still waits for them: for the line after leaving. Answers after stop() too. */
607
+ changes() { return [...running].map(([child, label]) => ({ pid: child.pid, label })); },
458
608
  /** Leave: synchronous and idempotent, safe before start(). The loop and the idle timer are
459
609
  * stopped, the observer disposed and every reading child ended (see `sever`), the roster's
460
610
  * included. A cycle in flight ends without emitting and without starting anything, and so
@@ -466,6 +616,11 @@ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onR
466
616
  observer.dispose();
467
617
  clearIdle();
468
618
  endReads();
619
+ // Every change is LET GO, never signalled: its handle no longer holds the process, and its two
620
+ // files are unlinked (the child goes on writing to them, and nothing is left behind). The
621
+ // private directory goes when it is empty.
622
+ for (const record of [...remembered.values()]) if (record.kind === "change") record.letItGo();
623
+ if (changeDir !== null) quietly(() => files.remove(changeDir));
469
624
  },
470
625
  /** The pids of the children remembered now (for tests). */
471
626
  children() { return [...remembered.keys()].map((child) => child.pid).filter((pid) => Number.isInteger(pid)); },
@@ -10,8 +10,9 @@
10
10
  // Selection is an identity (the shared `instanceId`), never an index, so it survives every read;
11
11
  // the rows it moves among are the model's, in drawn order.
12
12
  import { ACTIONS, bindings } from "./actions.mjs";
13
- import { collapseKey, displayLine, instanceId, pendingEntry } from "./client.mjs";
14
- import { disclosure, roster, switcher } from "./model.mjs";
13
+ import { collapseKey, displayLine, instanceActs, instanceId, pendingEntry } from "./client.mjs";
14
+ import { DETACH_KEY } from "./config.mjs";
15
+ import { BUTTON_ORDER, actDecision, disclosure, openDecision, preflightLine, returnedLine, roster, switcher } from "./model.mjs";
15
16
  import { windowOf } from "./views/scroll.mjs";
16
17
 
17
18
  /** The longest filter, in UTF-16 units. */
@@ -33,8 +34,21 @@ const NO_FILTER = Object.freeze({ editing: false, query: "" });
33
34
  * on purpose (see `scrolledList`); the switcher has its own.
34
35
  * `selected`, `top`, `detailTop` are the open view's; `places` keeps them for
35
36
  * the views left behind, and `collapsed` holds every view's keys (each carries its `open`).
36
- * `back`: the view under the help. `offered`: the deployments of `~/Agents` not served. */
37
- export function initialState({ deployment = null, cli, home, entry = null, actions = ACTIONS, ascii = false }) {
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
+ * `act`: the confirmation open in the act view (see `actOpened`), or null; `acted` counts the
45
+ * confirmations opened in this run, so an answer for one that was closed is told apart.
46
+ * `starting`: id -> `{ verb, since }` of this run's starts and restarts whose child is still
47
+ * alive, whether or not the TUI still waits for its answer (the loop says when one is spawned and
48
+ * when it closes): no act opens on such a row.
49
+ * The roster is made from none of `opening`, `outcome`, `act`, `acted` and `starting`
50
+ * (lib/model.mjs MADE_FROM). */
51
+ export function initialState({ deployment = null, cli, home, entry = null, actions = ACTIONS, ascii = false, detachKey = DETACH_KEY }) {
38
52
  return Object.freeze({
39
53
  view: deployment === null ? "switcher" : "instances", back: deployment === null ? "switcher" : "instances",
40
54
  ctxs: Object.freeze(deployment === null ? [] : [deployment]), open: deployment,
@@ -44,7 +58,7 @@ export function initialState({ deployment = null, cli, home, entry = null, actio
44
58
  selected: null, collapsed: new Set(), filter: NO_FILTER, focus: "list", top: 0, loose: false, detailTop: 0, places: new Map(), unread: new Map(),
45
59
  switcher: Object.freeze({ editing: false, query: "", selected: null, top: 0, loose: false, line: null, refused: null }),
46
60
  offered: Object.freeze({ offered: Object.freeze([]), limited: false }),
47
- helpTop: 0, actions, ascii,
61
+ helpTop: 0, actions, ascii, detachKey, opening: null, outcome: null, act: null, acted: 0, starting: new Map(),
48
62
  });
49
63
  }
50
64
 
@@ -116,7 +130,9 @@ function settled(state, taken) {
116
130
  const now = roster(taken);
117
131
  if (taken.open !== null && now.gone) {
118
132
  const places = new Map(taken.places); places.delete(taken.open);
119
- 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 } };
133
+ // A confirmation open over that view is closed with it: what it sent goes on.
134
+ const dismiss = taken.act !== null ? { dismiss: taken.act.n } : {};
135
+ 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 } };
120
136
  }
121
137
  const before = roster(state);
122
138
  const unknown = new Set([...taken.unread.values()].flatMap((ids) => [...ids]));
@@ -262,7 +278,7 @@ function switched(state, action, page) {
262
278
  const top = windowOf({ top: key === s.keys[0] ? 0 : key === s.keys.at(-1) ? count : drawn, count, height, keep: at }).top;
263
279
  return { state: put({ selected: key, top, loose: false }), effect: null };
264
280
  }
265
- case "open-workspace": {
281
+ case "open": {
266
282
  const item = s.items.find((each) => each.key !== undefined && each.key === s.selected);
267
283
  if (!item) return stay;
268
284
  if (item.path !== undefined) return { state: put({ refused: null }), effect: { admit: item.path } };
@@ -281,11 +297,152 @@ function switched(state, action, page) {
281
297
  * (one outcome of the roster read), `{ collecting }`, `{ offered: { offered, limited } }` (the
282
298
  * deployments of `~/Agents` not served), `{ admitted: <deployment>, at }` and `{ refused: <path> }`
283
299
  * (what a picked folder turned out to be).
300
+ * Opening an agent gives three more: `{ prepared: { id, error? } }` (the preflight of another
301
+ * machine's agent ended: `error` is what the shared prepareRemoteTerm threw), `{ given: true }`
302
+ * (the loop gave the preflight up itself: a suspend) and `{ returned: { id, status, stderr } }`
303
+ * (the viewer closed: its exit status as Node reports it, and the stderr it kept).
284
304
  * An effect is something only the loop can do: "quit", "suspend", "redraw", or an object with
285
- * any of `refresh: { live }` (read now), `offer: true` (list `~/Agents` again) and
286
- * `admit: <path>` (ask whether a picked folder is a deployment); or null. */
305
+ * any of `refresh: { live }` (read now), `offer: true` (list `~/Agents` again),
306
+ * `admit: <path>` (ask whether a picked folder is a deployment), `open: <decision>` (open the
307
+ * agent's terminal: the model's openDecision, with its target), `lend: <id>` (the preflight is
308
+ * over: start the viewer it prepared) and `abandon: true` (give the preflight up); or null.
309
+ * The line after an open stands until the next key that is bound to an action: a key bound to
310
+ * nothing (a stray detach key is no key at all) leaves it. */
287
311
  export function reduce(state, event, keymap = bindings(state.actions)) {
312
+ if (state.outcome !== null && typeof event.key === "string" && keymap.has(event.key)) state = next(state, { outcome: null });
313
+ return reduced(state, event, keymap);
314
+ }
315
+
316
+ /** The preflight of another machine's agent ended. Given up meanwhile (Esc, a suspend, a second
317
+ * open): dropped. Failed: the line that says so, unless it is the person's own giving up. Else
318
+ * the viewer is started, unless the row it is for has gone from the roster since. */
319
+ function prepared(state, { id, error }) {
320
+ const opening = state.opening;
321
+ if (opening === null || opening.id !== id || opening.phase !== "preflight") return { state, effect: null };
322
+ if (error !== undefined) return { state: next(state, { opening: null, outcome: preflightLine(opening, error) }), effect: null };
323
+ if (!roster(state).instances.some((row) => instanceId(row) === id)) return { state: next(state, { opening: null }), effect: null };
324
+ return { state: next(state, { opening: Object.freeze({ ...opening, phase: "lent" }) }), effect: { lend: id } };
325
+ }
326
+
327
+ /** The viewer closed: the line that says what happened, and the instances read again at once
328
+ * (an exit status says nothing of the agent but that it was left by the key). */
329
+ function returned(state, { id, status, stderr }) {
330
+ const opening = state.opening;
331
+ if (opening === null || opening.id !== id) return { state, effect: null };
332
+ return { state: next(state, { opening: null, outcome: returnedLine(opening, status, stderr) }), effect: { refresh: { live: true } } };
333
+ }
334
+
335
+ /** Enter in the list of instances: the selected agent's terminal, or the line that says why not.
336
+ * Nothing while an open is under way. */
337
+ function openAgent(state, r, at) {
338
+ if (state.opening !== null || at < 0) return { state, effect: null };
339
+ const row = r.items[at].row, decision = openDecision(state, row, instanceActs(row));
340
+ if (!decision.open) return { state: next(state, { outcome: decision.said }), effect: null };
341
+ const opening = Object.freeze({ id: decision.id, phase: decision.routed ? "preflight" : "lent", name: decision.name, machine: decision.machine, routed: decision.routed });
342
+ return { state: next(state, { opening, outcome: null }), effect: { open: decision } };
343
+ }
344
+
345
+ /** The keys of the act view that are not the action table's: the focus moves with these and with
346
+ * no printable key, so nothing typed or pasted as text reaches a button. */
347
+ const FOCUS_KEYS = Object.freeze({ left: -1, "shift+tab": -1, right: 1, tab: 1 });
348
+
349
+ /** An act key in the list of instances: the confirmation it opens, or the line that says why not
350
+ * (lib/model.mjs actDecision, over the row's instanceActs answer read now). A stop or a retire
351
+ * asks the loop for the shared confirmation (`act`), which reads the plan; a start or a restart
352
+ * opens the TUI's own confirmation, and nothing is asked of the loop until it is pressed. The
353
+ * focus starts on the first button, Cancel. Nothing while an open is under way. */
354
+ function actOn(state, r, at, verb) {
355
+ if (state.opening !== null || at < 0) return { state, effect: null };
356
+ const row = r.items[at].row, decision = actDecision(state, row, instanceActs(row), verb);
357
+ if (!decision.open) return { state: next(state, { outcome: decision.said }), effect: null };
358
+ const n = state.acted + 1;
359
+ 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 };
360
+ const act = decision.kind === "start"
361
+ ? Object.freeze({ ...base, phase: "review", offers: Object.freeze(["close", "apply"]), answer: null })
362
+ : Object.freeze({ ...base, phase: "reading", offers: Object.freeze(["close"]), outcome: null, notice: null, running: null, view: null, plan: null });
363
+ 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 } } };
364
+ }
365
+
366
+ /** The confirmation closed by the person (Esc, or its Cancel or Close pressed): the view goes, and
367
+ * the loop is told; a plan read, an apply or a start it sent goes on. */
368
+ const actClosed = (state) => ({ state: next(state, { view: "instances", back: "instances", act: null }), effect: { dismiss: state.act.n } });
369
+
370
+ /** A key in the act view. Left/Right and Tab/Shift+Tab move the focus among the buttons, Enter
371
+ * presses the one that has it, Esc closes, Space sets the plan's choice, the movement keys scroll
372
+ * the content; quit, suspend and redraw keep their actions; every other key does nothing.
373
+ * A press of the act's own button in the same read of input as the move that put the focus on
374
+ * it is ignored (`read`): a paste, with bracketed paste unsupported, cannot both move and press. */
375
+ function inAct(state, event, action) {
376
+ const a = state.act, stay = { state, effect: null };
377
+ if (action === "quit" || action === "suspend" || action === "redraw") return { state, effect: action };
378
+ if (event.key === "escape" || action === "close") return actClosed(state);
379
+ const put = (changes) => next(state, { act: Object.freeze({ ...a, ...changes }) });
380
+ if (Object.hasOwn(FOCUS_KEYS, event.key)) {
381
+ 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);
382
+ const focus = a.offers[to];
383
+ return focus === a.focus ? stay : { state: put({ focus, movedIn: focus === "apply" ? event.read ?? null : null }), effect: null };
384
+ }
385
+ if (event.key === "enter") {
386
+ if (a.focus === "apply" && event.read !== undefined && a.movedIn === event.read) return stay;
387
+ if (a.focus === "close") return actClosed(state);
388
+ if (a.kind === "start") {
389
+ if (a.focus !== "apply" || a.phase !== "review") return stay;
390
+ const row = roster(state).instances.find((each) => instanceId(each) === a.id) ?? null;
391
+ 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 } } };
392
+ }
393
+ const call = { apply: "apply", refresh: "refresh", "check-again": "checkAgain" }[a.focus];
394
+ return call ? { state, effect: { call: { n: a.n, method: call } } } : stay;
395
+ }
396
+ if (event.key === "space" || event.text === " ") {
397
+ const choice = a.kind === "lifecycle" && (a.phase === "review" || a.phase === "reading") ? a.plan?.choices.find((each) => each.offered) : null;
398
+ return choice ? { state, effect: { call: { n: a.n, method: "setChoice", args: [choice.id, !choice.value] } } } : stay;
399
+ }
400
+ if (MOVES.includes(action)) {
401
+ const count = event.extent ?? 0, height = event.room ?? 1;
402
+ const from = windowOf({ top: a.top, count, height }).top;
403
+ return { state: put({ top: windowOf({ top: moved(action, from, count, height), count, height }).top }), effect: null };
404
+ }
405
+ return stay;
406
+ }
407
+
408
+ /** What the loop says of the confirmation and of a start (`{ acted }`):
409
+ * { n, confirmation: { phase, outcome, offers, notice, running, view } } the shared
410
+ * confirmation's state() and view() after each step it told (stop, retire);
411
+ * { n, answer } a start's or restart's answer (the shared startInstance's): shown when its
412
+ * confirmation is still open, and the rows are read again (live) whatever it was;
413
+ * { spawned: { id, verb }, at } a start's child began (`at`: ms since the epoch);
414
+ * { closed: id } that child closed: the row takes acts again, and is read again (live).
415
+ * An answer for a confirmation that was closed (another `n`) changes nothing on screen. When the
416
+ * buttons change, the focus goes back to the first. */
417
+ function acted(state, event) {
418
+ const a = state.act, mine = a !== null && event.n === a.n;
419
+ 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 };
420
+ if (event.closed !== undefined) {
421
+ if (!state.starting.has(event.closed)) return { state, effect: { refresh: { live: true } } };
422
+ const starting = new Map(state.starting); starting.delete(event.closed);
423
+ return { state: next(state, { starting }), effect: { refresh: { live: true } } };
424
+ }
425
+ if (event.answer !== undefined) {
426
+ 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;
427
+ return { state: shown, effect: { refresh: { live: true } } };
428
+ }
429
+ if (event.confirmation !== undefined && mine && a.kind === "lifecycle") {
430
+ const c = event.confirmation, view = c.view ?? null;
431
+ const plan = view && typeof view.question === "string" ? view : view?.kind === "reading" && view.kept ? a.plan : null;
432
+ const offers = Object.freeze(BUTTON_ORDER.filter((offer) => (c.offers ?? []).includes(offer)));
433
+ const same = offers.length === a.offers.length && offers.every((offer, i) => offer === a.offers[i]);
434
+ 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,
435
+ ...(same ? {} : { focus: offers[0] ?? "close", movedIn: null }) }) }), effect: null };
436
+ }
437
+ return { state, effect: null };
438
+ }
439
+
440
+ function reduced(state, event, keymap) {
288
441
  const stay = { state, effect: null };
442
+ if (event.acted !== undefined) return acted(state, event.acted);
443
+ if (event.prepared !== undefined) return prepared(state, event.prepared);
444
+ if (event.given !== undefined) return state.opening?.phase === "preflight" ? { state: next(state, { opening: null }), effect: null } : stay;
445
+ if (event.returned !== undefined) return returned(state, event.returned);
289
446
  if (event.entry !== undefined) return took(state, event);
290
447
  if (event.roster !== undefined) return heard(state, event.roster);
291
448
  if (event.collecting !== undefined) return { state: event.collecting === state.collecting ? state : next(state, { collecting: event.collecting === true }), effect: null };
@@ -298,6 +455,7 @@ export function reduce(state, event, keymap = bindings(state.actions)) {
298
455
  if (typeof event.key !== "string") return stay;
299
456
  const action = keymap.get(event.key);
300
457
  if (field) return edited(state, field, event, action);
458
+ if (state.view === "act" && state.act !== null) return inAct(state, event, action);
301
459
  const page = Math.max(1, Number.isInteger(event.page) ? event.page : 1);
302
460
  // A pane that scrolls on its own (the help, the detail) moves from where it is DRAWN: the top
303
461
  // the state holds may lie past the end since the terminal grew, and the view shows it corrected.
@@ -323,7 +481,8 @@ export function reduce(state, event, keymap = bindings(state.actions)) {
323
481
  if (state.view === "switcher") return switched(state, action, page);
324
482
 
325
483
  if (action === "close") {
326
- // In this order: a kept filter, the detail.
484
+ // In this order: an open under way (another machine is asked first), a kept filter, the detail.
485
+ if (state.opening?.phase === "preflight") return { state: next(state, { opening: null }), effect: { abandon: true } };
327
486
  if (state.filter.query !== "") return { state: queried(state, ""), effect: null };
328
487
  return state.focus === "detail" ? { state: next(state, { focus: "list" }), effect: null } : stay;
329
488
  }
@@ -331,6 +490,8 @@ export function reduce(state, event, keymap = bindings(state.actions)) {
331
490
  const at = indexOf(r, state.selected);
332
491
  switch (action) {
333
492
  case "filter": return { state: next(state, { focus: "list", filter: Object.freeze({ ...state.filter, editing: true }) }), effect: null };
493
+ case "open": return openAgent(state, r, at);
494
+ case "stop": case "retire": case "start": case "restart": return actOn(state, r, at, action);
334
495
  case "detail": return at < 0 ? stay : { state: next(state, { focus: state.focus === "detail" ? "list" : "detail" }), effect: null };
335
496
  case "up": case "down": case "top": case "bottom": case "page-up": case "page-down": {
336
497
  if (state.focus === "detail") return { state: next(state, { detailTop: scrolled(state.detailTop) }), effect: null };