@awebai/oats 0.56.0 → 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.
@@ -11,6 +11,7 @@ import {
11
11
  waitingClaim, waitingLabel, waitedText, waitingClock, waitingBelowText, instanceActs,
12
12
  identityMemory, viewModel, workspaceChoices, workspaceChoiceRows, choiceMatches, UNMATCHED_SECTION, shortPath,
13
13
  openAct, deployments as heldDeployments, detachKeySupported, hostDetachKeySupported, attachExit, preflightFailure, kernelLines,
14
+ startGate, launchFlagIgnored, flagIgnoredNotice, retainedStartMessage,
14
15
  } from "./client.mjs";
15
16
  import { shownLines } from "./term/text.mjs";
16
17
  import { textWidth } from "./term/width.mjs";
@@ -356,6 +357,14 @@ export function preflightLine({ machine }, error) {
356
357
  return { said: [], under: [...outside(failure.sentence), ...(failure.said === null ? [] : kernelLines(failure.said.message, failure.said.fix, TERMS))] };
357
358
  }
358
359
 
360
+ /** The row's own text (its `runtimeError`), in the form that says who made it (see detailOf), or
361
+ * null. `acts` is the row's instanceActs answer: a reason of it that carries no `origin` and is
362
+ * this very text vouches for it. */
363
+ function rowText(row, acts) {
364
+ const vouched = [acts.blocked, acts.limited, ...acts.acts.map((act) => act.reason)].some((reason) => reason && reason.origin === undefined && reason.sentence === row.runtimeError);
365
+ return spoken(row.runtimeError, row.runtimeErrorOrigin, vouched);
366
+ }
367
+
359
368
  /** The facts of one instance, a label and a value per line; a fact that is absent is left out.
360
369
  * `form`: `line` (one row), `wrap` (a sentence, on as many rows as it needs), `end` (read from
361
370
  * its end: a path). A fact with no label continues the one above it. Every value is text the
@@ -387,8 +396,7 @@ function detailOf(state, r, item, now, acts) {
387
396
  // draws the withheld word and nothing else. (The view asks again about the whole value: words
388
397
  // in front never change the answer; a closing quotation mark can, for a text that ends in a
389
398
  // secret's name and its sign, and that text is then withheld.)
390
- const vouched = [acts.blocked, acts.limited, ...acts.acts.map((act) => act.reason)].some((reason) => reason && reason.origin === undefined && reason.sentence === row.runtimeError);
391
- add("", spoken(row.runtimeError, row.runtimeErrorOrigin, vouched), "wrap");
399
+ add("", rowText(row, acts), "wrap");
392
400
  // What holds the row, when that is a sentence of the shared home's and not the row's text: a
393
401
  // reason with an `origin` is the row's text, and so is one whose sentence is that text. Either
394
402
  // stands once, under the state.
@@ -458,10 +466,11 @@ export function model(state, { page, now, at, cols }) {
458
466
  view: state.view, focus: state.focus, ascii: state.ascii, actions: state.actions, filter: state.filter,
459
467
  workspace: r.workspace, machines: r.machines, here: r.here, machine: r.machine, counts: r.counts, readAt: r.readAt, notice: r.notice, note: r.note, empty: r.empty, observed: r.observed,
460
468
  detailTop: state.detailTop, helpTop: state.helpTop, open: state.open !== null,
461
- detachKey: state.detachKey, opening: state.opening, outcome: state.outcome, openable: false,
469
+ detachKey: state.detachKey, opening: state.opening, outcome: state.outcome, openable: false, actable: [],
470
+ act: state.view === "act" && state.act ? actView(state) : null,
462
471
  };
463
- // The view under the help decides what the header says.
464
- const under = state.view === "help" ? state.back : state.view;
472
+ // The view under the help, or under a confirmation, decides what the header says.
473
+ const under = state.view === "help" || state.view === "act" ? state.back : state.view;
465
474
  if (under === "switcher") {
466
475
  const s = switcher(state, at);
467
476
  const at_ = s.selected === null ? -1 : s.items.findIndex((item) => item.key === s.selected);
@@ -492,6 +501,194 @@ export function model(state, { page, now, at, cols }) {
492
501
  detail: selected >= 0 ? detailOf(state, r, r.items[selected], now, acts) : null,
493
502
  // Enter opens the selected agent's terminal now: the footer names the key that returns.
494
503
  openable: decision?.open === true && state.opening === null,
504
+ // The acts whose key opens a confirmation now, read from the same instanceActs answer: the
505
+ // footer names them. A key not named still answers, with the line that says why.
506
+ actable: row && state.opening === null ? ACT_VERBS.filter((verb) => actDecision(state, row, acts, verb).open) : [],
495
507
  switcher: null,
496
508
  };
497
509
  }
510
+
511
+ /** The shared home's rows of deployment `id` as the state holds them, unfiltered: the rows the list
512
+ * draws for it, found by the deployment and never by the view that is open. */
513
+ const rowsOf = (held, id) => panelData(held, id, TERMS).instances.filter((row) => row.deployment?.id === id);
514
+ /** Where a routed command runs from (its `localCwd`): the open deployment when it is this
515
+ * machine's, else the first served, else the home. */
516
+ export const actCwd = (state) => (state.ctxs.includes(state.open) ? state.open : state.ctxs[0] ?? state.home);
517
+ /** What the lifecycle boundary admits a request of deployment `id` against (its `getContext()`),
518
+ * asked at every admission: the deployment as the shared `deployments` lists it (a machine's with
519
+ * its roster group), the kernel record, `actCwd`, and that deployment's rows now. */
520
+ export function actContext(state, id, at) {
521
+ const held = heldOf(state, at);
522
+ const workspace = heldDeployments(held).find((w) => w.id === id) ?? null;
523
+ return { workspace, cli: state.cli, localCwd: actCwd(state), instances: workspace ? rowsOf(held, id) : [] };
524
+ }
525
+ /** This machine's deployments and their rows, for the shared start rule's home check
526
+ * (session-start.mjs verifiedLocalHome). */
527
+ export function localDeployments(state, at) {
528
+ const held = heldOf(state, at);
529
+ return heldDeployments(held).filter((w) => !w.remote).map((w) => ({ id: w.id, remote: false, instances: rowsOf(held, w.id) }));
530
+ }
531
+
532
+ /** The four acts on an instance, in the order the help, the footer and the keys know them. */
533
+ export const ACT_VERBS = Object.freeze(["stop", "retire", "start", "restart"]);
534
+ const DONE = Object.freeze({ stop: "stopped", retire: "retired", start: "started", restart: "restarted" });
535
+ /** The TUI's own words around the acts (docs/tui.md, "Stopping, starting, restarting and
536
+ * retiring"), as parts the way OPEN_WORDS are: `{ own }` the TUI's, `{ shown }` a name. A
537
+ * lifecycle sentence the shared home has is never written here: the confirmation's view says it. */
538
+ export const ACT_WORDS = Object.freeze({
539
+ notHere: (name, verb) => [{ shown: name }, { own: ` can't be ${DONE[verb]} here.` }],
540
+ stillStarting: (name, verb) => [{ own: `The ${verb} of ` }, { shown: name }, { own: " is still running." }],
541
+ /** The line on stderr after the TUI has left, one per change still running. */
542
+ leaving: (verb, name) => `oats: the ${verb} of ${name} is still running; \`oats status\` shows its result.`,
543
+ question: (name, verb) => [{ own: verb === "restart" ? "Restart " : "Start " }, { shown: name }, { own: "?" }],
544
+ what: (verb) => (verb === "restart"
545
+ ? "Its session is ended and started again: what it is doing is interrupted. Save any work in progress first."
546
+ : "It starts with the launch settings recorded for it."),
547
+ starting: (name, verb) => [{ own: verb === "restart" ? "Restarting " : "Starting " }, { shown: name }, { own: "…" }],
548
+ started: (name, verb) => [{ shown: name }, { own: ` ${DONE[verb]}.` }],
549
+ unconfirmed: (name) => [{ own: "OATS didn't confirm the start of " }, { shown: name }, { own: ". It may still be running: the list shows it when it is." }],
550
+ waiting: "Esc stops waiting.",
551
+ details: "Details:",
552
+ since: "Started at",
553
+ next: Object.freeze({
554
+ "retire-with-force": (name) => [{ own: "Check the process it names, then retire it with `oats retire " }, { shown: name }, { own: " --force`." }],
555
+ "check-roster": () => [{ own: "The list shows its result when it is done." }],
556
+ }),
557
+ });
558
+ /** The labels of the buttons, the TUI's own, by the confirmation's offer (and the phase it is in). */
559
+ export function buttonLabel(offer, verb, phase) {
560
+ if (offer === "close") {
561
+ if (phase === "reading" || phase === "review") return "Cancel";
562
+ if (phase === "applying" || phase === "starting") return `Close (the ${verb} goes on)`;
563
+ return "Close";
564
+ }
565
+ if (offer === "refresh") return "Review again";
566
+ if (offer === "check-again") return "Check again";
567
+ return { stop: "Stop", retire: "Retire", start: "Start", restart: "Restart" }[verb];
568
+ }
569
+ /** The order the buttons stand in, whatever order the offers come in: the first has the focus. */
570
+ export const BUTTON_ORDER = Object.freeze(["close", "refresh", "check-again", "apply"]);
571
+
572
+ /** Whether an act key on `row` opens a confirmation, and what the line says when it does not.
573
+ * `acts` is the row's instanceActs answer, read once per paint (the footer) or per key, as
574
+ * openDecision reads it; nothing here decides which acts a row has.
575
+ * { open: true, verb, id, name, kind, machine, label, home } a confirmation opens: `kind`
576
+ * "lifecycle" for stop and retire (the shared confirmation), "start" for the TUI's own
577
+ * { open: false, said: { said, under } } nothing opens, and this says why
578
+ * In order: a start or restart of this row from this TUI still running (Done 7); the verb listed
579
+ * and enabled (start and restart also asked of the shared startGate); listed and not enabled
580
+ * (its own reason); not listed (the row's blocked or limited reason, else the TUI's words). */
581
+ export function actDecision(state, row, acts, verb) {
582
+ const name = row.instance, id = instanceId(row);
583
+ const no = (said, under = []) => ({ open: false, said: { said, under } });
584
+ const running = state.starting?.get(id);
585
+ if (running) return no(ACT_WORDS.stillStarting(name, running.verb));
586
+ const act = acts.acts.find((each) => each.verb === verb);
587
+ if (!act) {
588
+ const held = acts.blocked ?? acts.limited;
589
+ return held ? no([], outside(reasonSpoken(held))) : no(ACT_WORDS.notHere(name, verb));
590
+ }
591
+ if (!act.enabled) return no([], outside(reasonSpoken(act.reason)));
592
+ const lifecycle = verb === "stop" || verb === "retire";
593
+ if (!lifecycle) {
594
+ const refused = startGate(state.cli, row, { restart: verb === "restart" }, TERMS);
595
+ // The gate's `detail` is the row's own text: said as the detail says it, with its speaker.
596
+ if (refused) return no([], [refused.sentence, ...outside(refused.detail ? rowText(row, acts) : null)]);
597
+ }
598
+ const machine = elsewhere(row) ? row.deployment?.machine ?? row.server : null;
599
+ return { open: true, verb, id, name, kind: lifecycle ? "lifecycle" : "start", machine, label: machine, home: row.home ?? null };
600
+ }
601
+
602
+ /** What a start's or a restart's answer (the shared startInstance's) shows, as the act view's
603
+ * lines: `{ said }` the TUI's own sentence in parts, `{ text }` a shared sentence or the kernel's
604
+ * line (each already as the shared home words it). Chosen by the answer's fields and codes, never
605
+ * by its words. */
606
+ export function startOutcome(name, verb, answer) {
607
+ const lines = [];
608
+ const kernel = (detail) => (detail ? kernelLines(detail, undefined, TERMS).map((text) => ({ text })) : []);
609
+ if (answer?.ok === true) {
610
+ const fact = launchFlagIgnored(answer.result), notice = fact ? flagIgnoredNotice(name, fact) : null;
611
+ if (notice) return [{ text: notice.headline, look: "bold" }, ...(notice.detail ? notice.detail.split("\n").map((text) => ({ text })) : [])];
612
+ return [{ said: ACT_WORDS.started(name, verb), look: "bold" }];
613
+ }
614
+ if (answer?.outcome === "refused") {
615
+ lines.push({ text: answer.sentence, look: "bold" });
616
+ // A refusal before the CLI ran (the gate, the home check) carries the row's own text, if any.
617
+ if (answer.ran) lines.push(...kernel(answer.detail));
618
+ else if (answer.detail) lines.push({ text: answer.detail });
619
+ return lines;
620
+ }
621
+ // The end of the wait for a start that goes on: the code the shared rule leaves to each client to
622
+ // word. No answer at all (the call itself was refused by the loop) is no more than that either.
623
+ if (!answer || answer.code === "E_START_UNCONFIRMED") return [{ said: ACT_WORDS.unconfirmed(name), look: "bold" }];
624
+ if (answer.incomplete) return [{ text: retainedStartMessage(name, answer.incomplete), look: "bold" }, ...kernel(answer.detail)];
625
+ return [{ text: answer.sentence ?? answer.code, look: "bold" }, ...kernel(answer.detail)];
626
+ }
627
+
628
+ /** An ISO-less clock time, `14:03`, of milliseconds since the epoch, or null. */
629
+ const hourMinute = (ms) => { const at = new Date(ms); return Number.isFinite(ms) && Number.isFinite(at.getTime()) ? `${pad(at.getHours())}:${pad(at.getMinutes())}` : null; };
630
+
631
+ /** The act view's content for the open confirmation (`state.act`), top to bottom, each part only
632
+ * when it has something: { title, lines, buttons }. A line is `{ text, look?, path? }` (a shared
633
+ * sentence or the kernel's text, drawn through the display filter; `path` after it, shortened),
634
+ * `{ said, look? }` (the TUI's own sentence, in parts), `{ pair: [label, value] }` (a state row: both from outside, the plan's label a target's name among them),
635
+ * `{ choice: { id, sentence, value } }` or `{ gap: true }`. `look`: "bold", "dim". */
636
+ export function actView(state) {
637
+ const a = state.act;
638
+ const lines = [];
639
+ const gap = () => { if (lines.length && !lines.at(-1).gap) lines.push({ gap: true }); };
640
+ const short = (path) => shortPath(path, { home: a.machine === null ? state.home : null });
641
+ let title;
642
+ if (a.kind === "start") {
643
+ title = { said: ACT_WORDS.question(a.name, a.verb) };
644
+ if (a.phase === "review") {
645
+ lines.push({ own: ACT_WORDS.what(a.verb) });
646
+ gap();
647
+ if (a.machine !== null) lines.push({ pair: ["machine", a.machine] });
648
+ if (a.home) lines.push({ pair: ["home", short(a.home)] });
649
+ } else if (a.phase === "starting") lines.push({ said: ACT_WORDS.starting(a.name, a.verb) });
650
+ else lines.push(...startOutcome(a.name, a.verb, a.answer));
651
+ } else {
652
+ const view = a.view ?? {}, plan = a.plan;
653
+ title = { text: plan && (a.phase === "review" || view.kind === "reading") ? plan.question : view.title ?? "" };
654
+ if (a.notice?.sentence) lines.push({ text: a.notice.sentence, look: "bold" });
655
+ if (view.kind === "reading" || view.kind === "applying") {
656
+ lines.push({ text: view.message });
657
+ if (view.kind === "reading") lines.push({ own: ACT_WORDS.waiting, look: "dim" });
658
+ }
659
+ if (plan && (a.phase === "review" || view.kind === "reading")) {
660
+ gap();
661
+ for (const h of plan.happening) lines.push({ text: h.text, ...(h.path ? { path: short(h.path) } : {}), ...(h.tone === "attention" ? { look: "bold" } : h.tone === "note" ? { look: "dim" } : {}) });
662
+ if (plan.state.rows.length || plan.state.notes.length) gap();
663
+ for (const row of plan.state.rows) lines.push({ pair: [row.label, row.value] });
664
+ for (const note of plan.state.notes) lines.push({ text: note.text, ...(note.tone === "attention" ? { look: "bold" } : note.tone === "note" ? { look: "dim" } : {}) });
665
+ if (plan.warning) lines.push({ text: plan.warning, look: "bold" });
666
+ const offered = plan.choices.filter((choice) => choice.offered);
667
+ if (offered.length) gap();
668
+ for (const choice of offered) lines.push({ choice: { id: choice.id, sentence: choice.sentence, value: choice.value } });
669
+ if (plan.notice?.sentence) lines.push({ text: plan.notice.sentence, look: "bold" });
670
+ }
671
+ if (a.phase === "settled" && view.status) {
672
+ gap();
673
+ lines.push({ text: view.status.headline, look: "bold" });
674
+ for (const more of view.status.more ?? []) {
675
+ if (more.quote !== undefined) lines.push(...kernelLines(more.quote, undefined, TERMS).map((text) => ({ text })));
676
+ else lines.push({ text: more.text });
677
+ }
678
+ if (view.status.next && ACT_WORDS.next[view.status.next]) lines.push({ said: ACT_WORDS.next[view.status.next](a.name) });
679
+ for (const block of view.blocks ?? []) {
680
+ if (block.type === "details") {
681
+ lines.push({ said: [{ own: `${ACT_WORDS.details} ` }, { shown: block.reason?.code ?? "" }], look: "dim" });
682
+ lines.push(...kernelLines(block.reason?.detail, undefined, TERMS).map((text) => ({ text })));
683
+ } else if (block.type === "quote") lines.push(...kernelLines(block.text, undefined, TERMS).map((text) => ({ text })));
684
+ else if (block.type === "note") lines.push({ text: block.text });
685
+ else if (block.type === "rows") for (const row of block.rows) { lines.push({ text: row.text }); if (row.quote) lines.push(...kernelLines(row.quote, undefined, TERMS).map((text) => ({ text }))); }
686
+ else if (block.type === "lines") for (const line of block.lines) lines.push({ text: line.text, ...(line.path ? { path: short(line.path) } : {}) });
687
+ }
688
+ }
689
+ const since = a.running ? hourMinute(a.running.since) : null;
690
+ if (since) lines.push({ own: `${ACT_WORDS.since} ${since}.`, look: "dim" });
691
+ }
692
+ const buttons = a.offers.map((offer) => ({ id: offer, label: buttonLabel(offer, a.verb, a.phase), focused: offer === a.focus }));
693
+ return { title, lines, buttons, top: a.top };
694
+ }
@@ -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: lib/open.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. */
@@ -188,17 +230,26 @@ 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 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.
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
@@ -319,6 +370,64 @@ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onR
319
370
  }
320
371
  return child;
321
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
+
322
431
  /** The shared observer, with the shared reader over this exec and no reader of the TUI's own: a
323
432
  * failed read has the same reasons here as in the Desktop. It admits a deployment of the cycle
324
433
  * now running and no other. */
@@ -491,6 +600,11 @@ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onR
491
600
  release() { held = false; },
492
601
  /** See askedExec. */
493
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 })); },
494
608
  /** Leave: synchronous and idempotent, safe before start(). The loop and the idle timer are
495
609
  * stopped, the observer disposed and every reading child ended (see `sever`), the roster's
496
610
  * included. A cycle in flight ends without emitting and without starting anything, and so
@@ -502,6 +616,11 @@ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onR
502
616
  observer.dispose();
503
617
  clearIdle();
504
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));
505
624
  },
506
625
  /** The pids of the children remembered now (for tests). */
507
626
  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, 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. */
@@ -41,7 +41,13 @@ const NO_FILTER = Object.freeze({ editing: false, query: "" });
41
41
  * as it was when Enter was pressed, for the line after. `outcome`: that line (the model's
42
42
  * `{ said, under }`), shown above the panes until the next key bound to an action, or null.
43
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). */
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). */
45
51
  export function initialState({ deployment = null, cli, home, entry = null, actions = ACTIONS, ascii = false, detachKey = DETACH_KEY }) {
46
52
  return Object.freeze({
47
53
  view: deployment === null ? "switcher" : "instances", back: deployment === null ? "switcher" : "instances",
@@ -52,7 +58,7 @@ export function initialState({ deployment = null, cli, home, entry = null, actio
52
58
  selected: null, collapsed: new Set(), filter: NO_FILTER, focus: "list", top: 0, loose: false, detailTop: 0, places: new Map(), unread: new Map(),
53
59
  switcher: Object.freeze({ editing: false, query: "", selected: null, top: 0, loose: false, line: null, refused: null }),
54
60
  offered: Object.freeze({ offered: Object.freeze([]), limited: false }),
55
- helpTop: 0, actions, ascii, detachKey, opening: null, outcome: null,
61
+ helpTop: 0, actions, ascii, detachKey, opening: null, outcome: null, act: null, acted: 0, starting: new Map(),
56
62
  });
57
63
  }
58
64
 
@@ -124,7 +130,9 @@ function settled(state, taken) {
124
130
  const now = roster(taken);
125
131
  if (taken.open !== null && now.gone) {
126
132
  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 } };
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 } };
128
136
  }
129
137
  const before = roster(state);
130
138
  const unknown = new Set([...taken.unread.values()].flatMap((ids) => [...ids]));
@@ -334,8 +342,104 @@ function openAgent(state, r, at) {
334
342
  return { state: next(state, { opening, outcome: null }), effect: { open: decision } };
335
343
  }
336
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
+
337
440
  function reduced(state, event, keymap) {
338
441
  const stay = { state, effect: null };
442
+ if (event.acted !== undefined) return acted(state, event.acted);
339
443
  if (event.prepared !== undefined) return prepared(state, event.prepared);
340
444
  if (event.given !== undefined) return state.opening?.phase === "preflight" ? { state: next(state, { opening: null }), effect: null } : stay;
341
445
  if (event.returned !== undefined) return returned(state, event.returned);
@@ -351,6 +455,7 @@ function reduced(state, event, keymap) {
351
455
  if (typeof event.key !== "string") return stay;
352
456
  const action = keymap.get(event.key);
353
457
  if (field) return edited(state, field, event, action);
458
+ if (state.view === "act" && state.act !== null) return inAct(state, event, action);
354
459
  const page = Math.max(1, Number.isInteger(event.page) ? event.page : 1);
355
460
  // A pane that scrolls on its own (the help, the detail) moves from where it is DRAWN: the top
356
461
  // the state holds may lie past the end since the terminal grew, and the view shows it corrected.
@@ -386,6 +491,7 @@ function reduced(state, event, keymap) {
386
491
  switch (action) {
387
492
  case "filter": return { state: next(state, { focus: "list", filter: Object.freeze({ ...state.filter, editing: true }) }), effect: null };
388
493
  case "open": return openAgent(state, r, at);
494
+ case "stop": case "retire": case "start": case "restart": return actOn(state, r, at, action);
389
495
  case "detail": return at < 0 ? stay : { state: next(state, { focus: state.focus === "detail" ? "list" : "detail" }), effect: null };
390
496
  case "up": case "down": case "top": case "bottom": case "page-up": case "page-down": {
391
497
  if (state.focus === "detail") return { state: next(state, { detailTop: scrolled(state.detailTop) }), effect: null };