@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
@@ -10,6 +10,8 @@ import {
10
10
  hasInstanceChildren, heldHome, rosterSections, deploymentState, rowStale, primaryDeployment, isMultiDeployment, runtimeState, runtimeCounts,
11
11
  waitingClaim, waitingLabel, waitedText, waitingClock, waitingBelowText, instanceActs,
12
12
  identityMemory, viewModel, workspaceChoices, workspaceChoiceRows, choiceMatches, UNMATCHED_SECTION, shortPath,
13
+ openAct, deployments as heldDeployments, detachKeySupported, hostDetachKeySupported, attachExit, preflightFailure, kernelLines,
14
+ startGate, launchFlagIgnored, flagIgnoredNotice, retainedStartMessage,
13
15
  } from "./client.mjs";
14
16
  import { shownLines } from "./term/text.mjs";
15
17
  import { textWidth } from "./term/width.mjs";
@@ -155,7 +157,13 @@ function build(state, at) {
155
157
  // Whether a list stands under the header: not for a deployment of this machine that was never
156
158
  // observed, nor for a machine that is not live and has no row kept. Each has only its reason.
157
159
  const observed = panel !== null && !gone && (local ? status === "observed" : live || instances.length > 0);
160
+ // Whether each other machine's OATS has the key that leaves a viewer, by the deployment its rows
161
+ // are tagged with (the shared panel's `row.deployment.id`; the TUI builds no deployment id).
162
+ // Worked out here, once for what the roster is made from, so a paint reads no machine again.
163
+ const opens = new Map();
164
+ if (panel !== null) for (const d of heldDeployments(heldOf(state, at))) if (d.remote) opens.set(d.id, hostDetachKeySupported(state.cli, d.group));
158
165
  return {
166
+ opens,
159
167
  panel, gone, instances, deployments, multi, parts, rows, filtering, stale, section, live, observed,
160
168
  below: waitingRollup(instances, state.collapsed, state.open, { filtering, stale, section }),
161
169
  status,
@@ -252,12 +260,117 @@ function listRow(state, r, item) {
252
260
  };
253
261
  }
254
262
 
263
+ /** A text the TUI did not write, as the detail and the outcome line draw it, or null when it has
264
+ * nothing to show. Who made it is the shared home's to say: after the words originLead gives for
265
+ * `origin` when it names a speaker; as it is when the shared home vouches for it (`vouched`: it
266
+ * is a sentence of the shared home's own); else in quotation marks, naming nobody. A missing mark
267
+ * is never read as "the shared home wrote this".
268
+ * The filter is asked about the text alone, before anything is put around it, so the words in
269
+ * front are never why a text is shown. What it withholds goes to the view as it came, which
270
+ * draws the withheld word and nothing else. (The view asks again about the whole value: words in
271
+ * front never change the answer; a closing quotation mark can, for a text that ends in a
272
+ * secret's name and its sign, and that text is then withheld.) */
273
+ function spoken(value, origin, vouched) {
274
+ const line = displayLine(value);
275
+ if (line === null) return null;
276
+ if (line === DETAIL_WITHHELD) return value;
277
+ const lead = originLead(origin, TERMS);
278
+ return lead !== null ? `${lead} ${line}` : vouched ? line : `"${line}"`;
279
+ }
280
+
281
+ /** A reason of the shared home's (a held row's, an act's), as `spoken` says it: its sentence is
282
+ * vouched for when it carries no mark. */
283
+ const reasonSpoken = (reason) => spoken(reason.sentence, reason.origin, reason.origin === undefined);
284
+
285
+ /** The TUI's own words around opening an agent's terminal (docs/tui.md, "Opening an agent").
286
+ * Each is a list of parts: `{ own }` is the TUI's, `{ shown }` text from outside (a name, a
287
+ * machine's name), drawn through the display filter on its own. `<id>` and `<home>` in the
288
+ * command are the TUI's placeholders: nothing of the row is in them. */
289
+ export const OPEN_WORDS = Object.freeze({
290
+ left: (name) => [{ own: "You left " }, { shown: name }, { own: ". It keeps running." }],
291
+ failed: (name) => [{ shown: name }, { own: " could not be opened." }],
292
+ link: (machine) => [{ own: "The connection to " }, { shown: machine }, { own: " ended." }],
293
+ unknown: (name) => [{ own: "The viewer of " }, { shown: name }, { own: " ended without saying why." }],
294
+ notRunning: (name) => [{ shown: name }, { own: " is not running, so it has no terminal to open." }],
295
+ stateUnknown: (name) => [{ own: "Whether " }, { shown: name }, { own: " runs is not known, so it is not opened." }],
296
+ noKey: (machine) => [machine === null ? { own: "This machine" } : { shown: machine }, { own: "'s OATS has no key to leave a viewer (it needs OATS 0.51.0 or later), so it is not opened from here. `oats session attach --server <id> --home <home>` opens it, and only closing the terminal leaves it." }],
297
+ });
298
+ /** A sentence from outside (a reason of the shared home's, the preflight table's), as a text
299
+ * under the line: drawn as the detail draws a reason, wrapped on the reason's rows, never as one
300
+ * unbroken part (a part is a name). */
301
+ const outside = (value) => (value === null ? [] : [value]);
302
+
303
+ /** Whether a row is of another machine: the shared home names its server on it. */
304
+ const elsewhere = (row) => typeof row.server === "string" && row.server !== "";
305
+
306
+ /** Whether `row`'s terminal can be opened from here, and what Enter does: `acts` is the row's
307
+ * instanceActs answer (computed once per selected row, for the detail too).
308
+ * { open: true, id, name, machine, target, routed } the kernel's viewer can be started:
309
+ * `target` is what the shared sessionAttachArgv and prepareRemoteTerm take, `routed` true
310
+ * for a row of another machine (its preflight runs first)
311
+ * { open: false, said: { said, under } } opens nothing, and this says why
312
+ * Whether a row can be opened is the shared openAct's, switched on its reason's code, never on a
313
+ * sentence; the TUI adds only the two feature gates on top of an enabled answer. */
314
+ export function openDecision(state, row, acts) {
315
+ const name = row.instance, id = instanceId(row);
316
+ const machine = elsewhere(row) ? row.deployment?.machine ?? row.server : null;
317
+ const no = (said, under = []) => ({ open: false, said: { said, under } });
318
+ const act = openAct(row);
319
+ if (act === null) {
320
+ const held = acts.blocked ?? acts.limited;
321
+ return no([], outside(reasonSpoken(held)));
322
+ }
323
+ if (!act.enabled) {
324
+ if (act.reason.code === "not-running") return no(OPEN_WORDS.notRunning(name));
325
+ if (act.reason.code === "state-unknown") return no(OPEN_WORDS.stateUnknown(name));
326
+ return no([], outside(reasonSpoken(act.reason)));
327
+ }
328
+ if (!elsewhere(row)) {
329
+ return detachKeySupported(state.cli) ? { open: true, id, name, machine, target: { home: row.home }, routed: false } : no(OPEN_WORDS.noKey(null));
330
+ }
331
+ if (roster(state).opens.get(row.deployment?.id) !== true) return no(OPEN_WORDS.noKey(machine));
332
+ return { open: true, id, name, machine, target: { serverId: row.server, instance: row.instance, home: row.home }, routed: true };
333
+ }
334
+
335
+ /** The line after the viewer returned, or null when the TUI says nothing of its own (the viewer
336
+ * ended without the key: the list shows the agent as the kernel now reports it). `status` is the
337
+ * child's exit status as Node reports it; the shared attachExit reads it, the TUI compares no
338
+ * number. What the viewer printed on stderr stands under a failure, once, as one text in
339
+ * quotation marks naming nobody: OATS, tmux and ssh all print there, and nothing is compared
340
+ * with it. */
341
+ export function returnedLine({ name, machine, routed }, status, stderr) {
342
+ const word = attachExit(status, { keyed: true, routed });
343
+ if (word === "ended") return null;
344
+ if (word === "left") return { said: OPEN_WORDS.left(name), under: [] };
345
+ if (word === "unknown") return { said: OPEN_WORDS.unknown(name), under: [] };
346
+ const line = displayLine(stderr);
347
+ const under = line === null ? [] : [line === DETAIL_WITHHELD ? DETAIL_WITHHELD : `"${line}"`];
348
+ return { said: word === "link" ? OPEN_WORDS.link(machine) : OPEN_WORDS.failed(name), under };
349
+ }
350
+
351
+ /** The line after a preflight that failed, or null when there is nothing to say: the person's own
352
+ * Esc, or a row that went away (E_TERM_CONTEXT_CHANGED). Else the shared table's sentence, and
353
+ * under it what the kernel said, when it said something (kernelLines). */
354
+ export function preflightLine({ machine }, error) {
355
+ const failure = preflightFailure(error, machine);
356
+ if (failure.code === "E_TERM_CONTEXT_CHANGED") return null;
357
+ return { said: [], under: [...outside(failure.sentence), ...(failure.said === null ? [] : kernelLines(failure.said.message, failure.said.fix, TERMS))] };
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
+
255
368
  /** The facts of one instance, a label and a value per line; a fact that is absent is left out.
256
369
  * `form`: `line` (one row), `wrap` (a sentence, on as many rows as it needs), `end` (read from
257
370
  * its end: a path). A fact with no label continues the one above it. Every value is text the
258
371
  * TUI did not write, or holds some: the view draws all of them through shown(). `now` is the
259
372
  * time of the paint, so the waited time is right whenever the screen is drawn. */
260
- function detailOf(state, r, item, now) {
373
+ function detailOf(state, r, item, now, acts) {
261
374
  const row = item.row, facts = [];
262
375
  const add = (label, value, form = "line") => { if (text(value)) facts.push({ label, value, form }); };
263
376
  add("soul", row.agent);
@@ -270,7 +383,7 @@ function detailOf(state, r, item, now) {
270
383
  if (said && said.key !== "live") add("", said.detail, "wrap");
271
384
  }
272
385
  add("state", heldHome(row)?.state ?? stateWord(row)); // the word of its list row, harness apart
273
- const acts = instanceActs(row), held = acts.blocked ?? acts.limited;
386
+ const held = acts.blocked ?? acts.limited;
274
387
  // The row's own text stands under its state, in the form that says who made it. Who made it is
275
388
  // the shared home's to say, in two ways, and the TUI writes no word and no sentence of its own
276
389
  // for either: the row's mark, which originLead turns into the words that go before the text;
@@ -283,13 +396,7 @@ function detailOf(state, r, item, now) {
283
396
  // draws the withheld word and nothing else. (The view asks again about the whole value: words
284
397
  // in front never change the answer; a closing quotation mark can, for a text that ends in a
285
398
  // secret's name and its sign, and that text is then withheld.)
286
- const line = displayLine(row.runtimeError);
287
- if (line === DETAIL_WITHHELD) add("", row.runtimeError, "wrap");
288
- else if (line !== null) {
289
- const lead = originLead(row.runtimeErrorOrigin, TERMS);
290
- const vouched = [acts.blocked, acts.limited, ...acts.acts.map((act) => act.reason)].some((reason) => reason && reason.origin === undefined && reason.sentence === row.runtimeError);
291
- add("", lead !== null ? `${lead} ${line}` : vouched ? line : `"${line}"`, "wrap");
292
- }
399
+ add("", rowText(row, acts), "wrap");
293
400
  // What holds the row, when that is a sentence of the shared home's and not the row's text: a
294
401
  // reason with an `origin` is the row's text, and so is one whose sentence is that text. Either
295
402
  // stands once, under the state.
@@ -359,9 +466,11 @@ export function model(state, { page, now, at, cols }) {
359
466
  view: state.view, focus: state.focus, ascii: state.ascii, actions: state.actions, filter: state.filter,
360
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,
361
468
  detailTop: state.detailTop, helpTop: state.helpTop, open: state.open !== null,
469
+ detachKey: state.detachKey, opening: state.opening, outcome: state.outcome, openable: false, actable: [],
470
+ act: state.view === "act" && state.act ? actView(state) : null,
362
471
  };
363
- // The view under the help decides what the header says.
364
- 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;
365
474
  if (under === "switcher") {
366
475
  const s = switcher(state, at);
367
476
  const at_ = s.selected === null ? -1 : s.items.findIndex((item) => item.key === s.selected);
@@ -371,7 +480,7 @@ export function model(state, { page, now, at, cols }) {
371
480
  return {
372
481
  ...common, under, list: [], above: 0, below: 0, wordWidth: 0, detail: null,
373
482
  // Nothing of a workspace stands in the header while the switcher is shown.
374
- workspace: "", machines: 0, here: false, machine: null, counts: [], readAt: null, notice: null, note: null, empty: null, observed: true,
483
+ workspace: "", machines: 0, here: false, machine: null, counts: [], readAt: null, notice: null, note: null, empty: null, observed: true, outcome: null,
375
484
  filter: Object.freeze({ editing: state.switcher.editing, query: state.switcher.query }),
376
485
  switcher: {
377
486
  rows: s.items.slice(win.top, win.top + win.size).map((item) => (item.key === undefined ? item : { ...item, selected: item.key === s.selected })),
@@ -380,13 +489,206 @@ export function model(state, { page, now, at, cols }) {
380
489
  };
381
490
  }
382
491
  const selected = state.selected === null ? -1 : r.index.get(state.selected) ?? -1;
492
+ // What the detail, the footer and Enter read of the selected row is worked out once per paint.
493
+ const row = selected >= 0 ? r.items[selected].row : null, acts = row ? instanceActs(row) : null;
494
+ const decision = row ? openDecision(state, row, acts) : null;
383
495
  // The window holds the selection, unless the list was scrolled away from it on purpose.
384
496
  const win = windowOf({ top: state.top, count: r.items.length, height: page, keep: state.loose ? -1 : selected });
385
497
  return {
386
498
  ...common, under,
387
499
  list: r.items.slice(win.top, win.top + win.size).map((item) => (item?.id !== undefined ? { kind: "row", ...listRow(state, r, item) } : item)),
388
500
  above: win.above, below: win.below, wordWidth: r.wordWidth,
389
- detail: selected >= 0 ? detailOf(state, r, r.items[selected], now) : null,
501
+ detail: selected >= 0 ? detailOf(state, r, r.items[selected], now, acts) : null,
502
+ // Enter opens the selected agent's terminal now: the footer names the key that returns.
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) : [],
390
507
  switcher: null,
391
508
  };
392
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
+ }
@@ -0,0 +1,45 @@
1
+ // Opening an agent's terminal: the one child of the TUI that is not a read. It is the kernel's own
2
+ // viewer (`oats session attach … --detach-key <key>`), whose arguments the shared home builds
3
+ // (client.mjs sessionAttachArgv, prepareRemoteTerm): nothing here names an argument, a tmux
4
+ // server or an exit status. The TUI builds no viewer and runs no tmux command.
5
+ //
6
+ // UNLIKE EVERY READ (lib/read.mjs), THE VIEWER IS NOT STARTED IN A SESSION OF ITS OWN. It needs
7
+ // the terminal as its controlling terminal and must be in the foreground process group, so the
8
+ // terminal's signals reach it as they reach the TUI. It is the loop's child, never the reader's:
9
+ // the reader ends only the reads it started, and nothing of its clean-up can reach a viewer.
10
+ import { spawn as nodeSpawn } from "node:child_process";
11
+
12
+ /** The most of the viewer's stderr that is kept, in bytes: the last ones. */
13
+ export const STDERR_KEPT = 4096;
14
+
15
+ /** Start the viewer: `node <bin> <args…>` with stdin and stdout on the terminal (inherited) and
16
+ * stderr on a pipe; no shell, the TUI's own environment (the instance variables were removed at
17
+ * the start; the kernel's viewer drops TMUX for its own child). Answers `{ closed, end, release }`:
18
+ * `closed` resolves once the child has closed, never rejects, with `{ status, stderr }`: `status`
19
+ * the exit status as Node reports it (null when a signal ended it, or when it did not start),
20
+ * `stderr` the last STDERR_KEPT bytes it printed, as text. `end()` asks it to end (SIGTERM to the
21
+ * child alone: the kernel closes its viewer on it); after it has closed, end() does nothing.
22
+ * `release()` lets go of a viewer that did not end when asked: its stderr pipe is destroyed and
23
+ * its handle no longer holds the process, which can then exit while the viewer lives on. */
24
+ export function startViewer(bin, args, { env = process.env, spawn = nodeSpawn } = {}) {
25
+ let child, over = false;
26
+ const closed = new Promise((resolve) => {
27
+ let kept = Buffer.alloc(0);
28
+ const done = (status) => { if (!over) { over = true; resolve({ status, stderr: kept.toString("utf8") }); } };
29
+ try {
30
+ child = spawn(process.execPath, [bin, ...args], { stdio: ["inherit", "inherit", "pipe"], env, shell: false });
31
+ } catch { return done(null); }
32
+ child.stderr?.on("error", () => {});
33
+ child.stderr?.on("data", (chunk) => {
34
+ kept = Buffer.concat([kept, chunk]);
35
+ if (kept.length > STDERR_KEPT) kept = kept.subarray(kept.length - STDERR_KEPT);
36
+ });
37
+ child.on("error", () => { if (!child.pid) done(null); });
38
+ child.once("close", (code) => done(Number.isInteger(code) ? code : null));
39
+ });
40
+ return {
41
+ closed,
42
+ end() { if (!over && child) { try { child.kill("SIGTERM"); } catch { /* gone */ } } },
43
+ release() { if (!over && child) { child.stderr?.destroy(); child.unref(); } },
44
+ };
45
+ }