@awebai/oats 0.55.1 → 0.56.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 (78) hide show
  1. package/bin/oats.mjs +78 -62
  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 +317 -35
  5. package/docs/desktop-instance-start.md +105 -12
  6. package/docs/desktop.md +54 -7
  7. package/docs/execution-targets.md +184 -9
  8. package/docs/harness-trust.md +128 -11
  9. package/docs/implementation.md +54 -7
  10. package/docs/integrations.md +1 -1
  11. package/docs/knowledge.md +35 -16
  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/servers.md +21 -5
  17. package/docs/souls-and-instances.md +8 -4
  18. package/docs/tui.md +99 -26
  19. package/docs/upgrading.md +4 -1
  20. package/docs/workspaces.md +26 -6
  21. package/lib/automations.mjs +3 -4
  22. package/lib/bounded-read.mjs +18 -0
  23. package/lib/capability-show.mjs +13 -2
  24. package/lib/claim.mjs +3 -4
  25. package/lib/core.mjs +480 -152
  26. package/lib/errors.mjs +39 -0
  27. package/lib/harness-trust-write.mjs +119 -40
  28. package/lib/harness-trust.mjs +31 -18
  29. package/lib/instance-inspect.mjs +160 -11
  30. package/lib/instance-lifecycle.mjs +47 -30
  31. package/lib/packages.mjs +8 -5
  32. package/lib/pi-bridge.mjs +18 -19
  33. package/lib/remote.mjs +88 -51
  34. package/lib/retire-output.mjs +9 -4
  35. package/lib/schedule.mjs +3 -4
  36. package/lib/servers.mjs +39 -6
  37. package/lib/session-viewer.mjs +25 -1
  38. package/lib/triggers.mjs +3 -4
  39. package/lib/workspace.mjs +6 -6
  40. package/lib/worktree.mjs +10 -6
  41. package/lib/write-through-private-file.mjs +26 -0
  42. package/package-catalog.json +2 -2
  43. package/package.json +1 -1
  44. package/packages/client/cli-adapter.mjs +108 -13
  45. package/packages/client/cli-locator.mjs +16 -14
  46. package/packages/client/deployment-panel.mjs +4 -3
  47. package/packages/client/display-text.mjs +2 -1
  48. package/packages/client/instance-events-contract.mjs +4 -3
  49. package/packages/client/instance-lifecycle.mjs +228 -0
  50. package/packages/client/instance-presentation.mjs +9 -0
  51. package/packages/client/instance-tree.mjs +10 -8
  52. package/packages/client/kernel-lines.mjs +3 -3
  53. package/packages/client/launch-contract.mjs +11 -0
  54. package/packages/client/lifecycle-cli.mjs +12 -6
  55. package/packages/client/lifecycle-confirmation.mjs +407 -0
  56. package/packages/client/lifecycle-contract.mjs +6 -2
  57. package/packages/client/own-codes.mjs +1 -0
  58. package/packages/client/panel-views.mjs +39 -2
  59. package/packages/client/readiness-contract.mjs +2 -2
  60. package/packages/client/remote-roster.mjs +50 -5
  61. package/packages/client/roster-sections.mjs +3 -3
  62. package/packages/client/session-start.mjs +98 -0
  63. package/packages/client/start-gate.mjs +46 -0
  64. package/packages/client/start-messages.mjs +17 -0
  65. package/packages/client/workspace-views.mjs +2 -2
  66. package/packages/tui/README.md +10 -6
  67. package/packages/tui/lib/actions.mjs +4 -2
  68. package/packages/tui/lib/client.mjs +5 -2
  69. package/packages/tui/lib/config.mjs +39 -9
  70. package/packages/tui/lib/main.mjs +83 -13
  71. package/packages/tui/lib/model.mjs +116 -11
  72. package/packages/tui/lib/open.mjs +45 -0
  73. package/packages/tui/lib/read.mjs +46 -10
  74. package/packages/tui/lib/store.mjs +64 -9
  75. package/packages/tui/lib/term/tty.mjs +71 -12
  76. package/packages/tui/lib/views/frame.mjs +115 -33
  77. package/packages/tui/lib/views/help.mjs +37 -8
  78. package/skills/oats-getting-started/SKILL.md +6 -3
@@ -1,13 +1,15 @@
1
1
  // `oats tui` (preview): the loop. Events from the keyboard and from the reader go through one
2
2
  // pure reduce(state, event); what only the loop can do comes back as an effect; the frame is
3
3
  // drawn from the state. This version shows a workspace's instances, on this machine and on the
4
- // machines registered here, and follows them; it changes nothing (docs/tui.md).
4
+ // machines registered here, follows them, and opens an agent's terminal with the kernel's own
5
+ // viewer; it changes nothing in a deployment (docs/tui.md).
5
6
  import { homedir } from "node:os";
6
7
  import { resolve } from "node:path";
7
8
  import { bindings } from "./actions.mjs";
8
- import { displayLine, pendingEntry } from "./client.mjs";
9
+ import { displayLine, pendingEntry, prepareRemoteTerm, sessionAttachArgv } from "./client.mjs";
9
10
  import { loadConfig } from "./config.mjs";
10
11
  import { model, roster } from "./model.mjs";
12
+ import { startViewer } from "./open.mjs";
11
13
  import { admitDeployment, createReader, findDeployment, leaveInstance, offeredDeployments, probeKernel } from "./read.mjs";
12
14
  import { initialState, reduce } from "./store.mjs";
13
15
  import { createKeyParser, keyId } from "./term/keys.mjs";
@@ -21,8 +23,9 @@ const HELP = `Usage:
21
23
  ${USAGE}
22
24
 
23
25
  The OATS terminal client (preview): a full-screen view of a workspace's instances,
24
- on this machine and on the machines registered here. It follows them and changes
25
- nothing. Keys: ? help, w workspaces, q quit.
26
+ on this machine and on the machines registered here. It follows them, opens an
27
+ agent's terminal with Enter, and changes nothing in a deployment.
28
+ Keys: ? help, Enter open, w workspaces, q quit.
26
29
  docs/tui.md has the rest.
27
30
 
28
31
  --dir <path> the deployment, or a directory inside one (default: where you are)
@@ -59,7 +62,7 @@ function errorLines(error) {
59
62
  }
60
63
 
61
64
  /** What the loop does outside the terminal, each replaceable by a test. */
62
- const EFFECTS = Object.freeze({ loadConfig, findDeployment, probeKernel, createReader, offeredDeployments, admitDeployment });
65
+ const EFFECTS = Object.freeze({ loadConfig, findDeployment, probeKernel, createReader, offeredDeployments, admitDeployment, prepareRemoteTerm, startViewer });
63
66
 
64
67
  /** Run. Resolves with the exit status; never calls process.exit, so what was written drains.
65
68
  * Before the alternate screen, in this order, each failure one line on stderr and status 1:
@@ -86,14 +89,17 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
86
89
  const clock = () => new Date(now()).toISOString();
87
90
  const look = glyphs(env, { ascii: options.ascii || config.ascii });
88
91
  const screen = createScreen({ ...look, color: colorEnabled(env) });
89
- const parser = createKeyParser({ now });
90
- let state = initialState({ deployment: found.ok ? found.deployment : null, cli: probe.cli, home, entry: found.ok ? pendingEntry(null, clock()) : null, actions: config.actions, ascii: look.ascii });
92
+ let parser = createKeyParser({ now });
93
+ let state = initialState({ deployment: found.ok ? found.deployment : null, cli: probe.cli, home, entry: found.ok ? pendingEntry(null, clock()) : null, actions: config.actions, ascii: look.ascii, detachKey: config.detachKey });
91
94
  const keymap = bindings(state.actions);
92
95
  if (offered) state = reduce(state, { offered }, keymap).state;
93
96
  // What the last frame drew, for the store: how tall the list pane is and how far the other
94
97
  // pane scrolls. The store holds no size of its own.
95
98
  let drawn = { page: 1, extent: 0, room: 1, cols: 1 };
96
99
  let full = true, escTimer = null, ended = false;
100
+ /** The preflight of another machine's agent under way: `{ id, controller, prepared }`, where
101
+ * `prepared` is what it answered (`{ binary, args }`) once it has; or null. */
102
+ let preflight = null;
97
103
 
98
104
  // What the reader reads for, it asks of the state at that moment: the served deployments, the
99
105
  // entry a failed read keeps, and the roster and the memory the next outcome is made from.
@@ -121,39 +127,103 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
121
127
  const admitted = effects.admitDeployment(effect.admit);
122
128
  took(reduce(state, admitted.ok ? { admitted: admitted.deployment, at: clock() } : { refused: effect.admit }, keymap));
123
129
  }
130
+ if (effect.abandon) giveUpPreflight();
131
+ if (effect.open) open(effect.open);
132
+ if (effect.lend !== undefined) {
133
+ const ready = preflight;
134
+ preflight = null;
135
+ if (ready?.id === effect.lend && ready.prepared) lendTo(effect.lend, ready.prepared.binary, ready.prepared.args);
136
+ }
124
137
  if (effect.refresh) refresh(effect.refresh);
125
138
  return false;
126
139
  }
140
+
141
+ /** Open the agent the store decided on (lib/model.mjs openDecision). On this machine the
142
+ * terminal is lent at once. On another, the shared preflight runs first over the reader's exec
143
+ * (a read like any other, ended on every way out), and what it prepared waits for the store's
144
+ * `lend`, which comes only if the open was not given up and the row is still there. */
145
+ function open(decision) {
146
+ if (!decision.routed) {
147
+ let args;
148
+ // A target the shared home refuses (no absolute home) starts nothing; the line after says
149
+ // the viewer ended without saying why.
150
+ try { args = sessionAttachArgv(probe.cli, decision.target, { detachKey: state.detachKey }); } catch { return void heard({ returned: { id: decision.id, status: null, stderr: "" } }); }
151
+ return lendTo(decision.id, probe.cli.bin, args);
152
+ }
153
+ giveUpPreflight();
154
+ const mine = preflight = { id: decision.id, controller: new AbortController(), prepared: null };
155
+ Promise.resolve()
156
+ .then(() => effects.prepareRemoteTerm(probe.cli, decision.target, { exec: reader.exec, signal: mine.controller.signal, detachKey: state.detachKey }))
157
+ .then((prepared) => { if (preflight === mine) { mine.prepared = prepared; heard({ prepared: { id: mine.id } }); } },
158
+ (error) => { if (preflight === mine) { preflight = null; heard({ prepared: { id: mine.id, error } }); } });
159
+ }
160
+ /** The preflight under way, given up: its child is ended through the signal, and whatever it
161
+ * answers is dropped. */
162
+ function giveUpPreflight() {
163
+ if (preflight === null) return;
164
+ preflight.controller.abort();
165
+ preflight = null;
166
+ }
167
+ /** Lend the terminal to the kernel's viewer (lib/open.mjs) and take it back when it closes.
168
+ * Before: every read in flight is void and none starts while it has the terminal, as at a
169
+ * stop. After: reads begin again, and the store says what happened and asks for a live read. */
170
+ function lendTo(id, bin, args) {
171
+ dropReads();
172
+ reader.hold();
173
+ let viewer = null;
174
+ guard.lend(() => { viewer = effects.startViewer(bin, args, { env }); return viewer.closed; }, { end: () => viewer?.end(), release: () => viewer?.release() }).then((outcome) => {
175
+ // The keys are read anew: what was typed before the viewer started (behind the Enter, in the
176
+ // same chunk) and a sequence begun then are gone, so none of it acts or joins a later key.
177
+ if (escTimer !== null) { clearTimer(escTimer); escTimer = null; }
178
+ parser = createKeyParser({ now });
179
+ reader.release();
180
+ const { status = null, stderr = "" } = outcome.value ?? {};
181
+ heard({ returned: { id, status, stderr } });
182
+ });
183
+ }
127
184
  const guard = createGuard({
128
185
  stdin, stdout, proc, setTimer, clearTimer,
129
186
  frame() {
130
187
  const size = guard.size(), at = clock();
131
188
  // The layout first: the model's window is as tall, and its sentences as wide, as the list
132
189
  // pane it gives. The switcher takes the whole body and has no notice of a deployment.
133
- const r = (state.view === "help" ? state.back : state.view) === "switcher" ? { notice: null, note: null, observed: true } : roster(state, at);
134
- const g = layout(r.notice, size, { observed: r.observed, note: r.note, ascii: state.ascii });
190
+ const listing = (state.view === "help" ? state.back : state.view) === "switcher";
191
+ const r = listing ? { notice: null, note: null, observed: true } : roster(state, at);
192
+ const g = layout(r.notice, size, { observed: r.observed, note: r.note, ascii: state.ascii, outcome: listing ? null : state.outcome });
135
193
  const made = frame(model(state, { page: g.page, now: now(), at, cols: g.listCols }), size);
136
194
  drawn = { page: made.page, extent: made.extent, room: made.room, cols: g.listCols };
137
195
  const bytes = screen.render(made.rows, size, { full });
138
196
  full = false;
139
197
  return bytes;
140
198
  },
141
- onInput(bytes) { reader.touch(); act(parser.feed(bytes)); watchEscape(); },
199
+ onInput(bytes) { if (guard.lent) return; reader.touch(); act(parser.feed(bytes)); watchEscape(); },
142
200
  onResize() { full = true; guard.draw(); },
143
201
  onRedraw() { full = true; guard.draw(); },
144
202
  // A cycle in flight when the process stops is no evidence about the deployment (lib/read.mjs):
145
203
  // it is dropped before the stop, and again after a stop nobody here asked for; the return
146
204
  // reads at once.
147
- onStop() { dropReads(); },
148
- onResume(asked) { if (!asked) dropReads(); refresh({ live: true }); },
205
+ // A preflight is given up first, by the TUI itself: ended as a read it would answer as a
206
+ // timeout. The person opens the agent again.
207
+ onStop() { stopPreflight(); dropReads(); },
208
+ onResume(asked) { if (!asked) { stopPreflight(); dropReads(); } refresh({ live: true }); },
149
209
  onEnd() { ended = true; reader.stop(); },
150
210
  });
151
211
  function refresh(how) { Promise.resolve(reader.request(how)).catch(() => {}); }
212
+ /** A preflight under way when the process stops: given up, and the store told. */
213
+ function stopPreflight() {
214
+ if (preflight === null) return;
215
+ giveUpPreflight();
216
+ state = reduce(state, { given: true }, keymap).state;
217
+ }
152
218
  /** Every read in flight is void (lib/read.mjs), the roster's with them: the reader says nothing
153
219
  * for a void read, so the state is told here that none is in flight. */
154
220
  function dropReads() { reader.voidInFlight(); state = reduce(state, { collecting: false }, keymap).state; }
221
+ /** The events of one batch of input, in order. Once one of them lent the terminal, the rest are
222
+ * dropped: they were typed before the viewer started, and none may act while it has the
223
+ * terminal (a `q` behind the Enter would end the run under a live viewer). */
155
224
  function act(events) {
156
225
  for (const event of events) {
226
+ if (guard.lent) return;
157
227
  if (took(reduce(state, "paste" in event ? { paste: event.paste } : { key: keyId(event), ...(typeof event.text === "string" && !event.alt ? { text: event.text } : {}), ...drawn }, keymap))) return;
158
228
  }
159
229
  guard.draw();
@@ -162,7 +232,7 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
162
232
  function watchEscape() {
163
233
  if (escTimer !== null) { clearTimer(escTimer); escTimer = null; }
164
234
  const due = parser.timeoutAt();
165
- if (due !== null) escTimer = setTimer(() => { escTimer = null; guard.attempt(() => { act(parser.expire()); watchEscape(); }); }, Math.max(0, due - now()));
235
+ if (due !== null) escTimer = setTimer(() => { escTimer = null; if (!guard.lent) guard.attempt(() => { act(parser.expire()); watchEscape(); }); }, Math.max(0, due - now()));
166
236
  }
167
237
 
168
238
  guard.start();
@@ -10,6 +10,7 @@ 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,
13
14
  } from "./client.mjs";
14
15
  import { shownLines } from "./term/text.mjs";
15
16
  import { textWidth } from "./term/width.mjs";
@@ -155,7 +156,13 @@ function build(state, at) {
155
156
  // Whether a list stands under the header: not for a deployment of this machine that was never
156
157
  // observed, nor for a machine that is not live and has no row kept. Each has only its reason.
157
158
  const observed = panel !== null && !gone && (local ? status === "observed" : live || instances.length > 0);
159
+ // Whether each other machine's OATS has the key that leaves a viewer, by the deployment its rows
160
+ // are tagged with (the shared panel's `row.deployment.id`; the TUI builds no deployment id).
161
+ // Worked out here, once for what the roster is made from, so a paint reads no machine again.
162
+ const opens = new Map();
163
+ if (panel !== null) for (const d of heldDeployments(heldOf(state, at))) if (d.remote) opens.set(d.id, hostDetachKeySupported(state.cli, d.group));
158
164
  return {
165
+ opens,
159
166
  panel, gone, instances, deployments, multi, parts, rows, filtering, stale, section, live, observed,
160
167
  below: waitingRollup(instances, state.collapsed, state.open, { filtering, stale, section }),
161
168
  status,
@@ -252,12 +259,109 @@ function listRow(state, r, item) {
252
259
  };
253
260
  }
254
261
 
262
+ /** A text the TUI did not write, as the detail and the outcome line draw it, or null when it has
263
+ * nothing to show. Who made it is the shared home's to say: after the words originLead gives for
264
+ * `origin` when it names a speaker; as it is when the shared home vouches for it (`vouched`: it
265
+ * is a sentence of the shared home's own); else in quotation marks, naming nobody. A missing mark
266
+ * is never read as "the shared home wrote this".
267
+ * The filter is asked about the text alone, before anything is put around it, so the words in
268
+ * front are never why a text is shown. What it withholds goes to the view as it came, which
269
+ * draws the withheld word and nothing else. (The view asks again about the whole value: words in
270
+ * front never change the answer; a closing quotation mark can, for a text that ends in a
271
+ * secret's name and its sign, and that text is then withheld.) */
272
+ function spoken(value, origin, vouched) {
273
+ const line = displayLine(value);
274
+ if (line === null) return null;
275
+ if (line === DETAIL_WITHHELD) return value;
276
+ const lead = originLead(origin, TERMS);
277
+ return lead !== null ? `${lead} ${line}` : vouched ? line : `"${line}"`;
278
+ }
279
+
280
+ /** A reason of the shared home's (a held row's, an act's), as `spoken` says it: its sentence is
281
+ * vouched for when it carries no mark. */
282
+ const reasonSpoken = (reason) => spoken(reason.sentence, reason.origin, reason.origin === undefined);
283
+
284
+ /** The TUI's own words around opening an agent's terminal (docs/tui.md, "Opening an agent").
285
+ * Each is a list of parts: `{ own }` is the TUI's, `{ shown }` text from outside (a name, a
286
+ * machine's name), drawn through the display filter on its own. `<id>` and `<home>` in the
287
+ * command are the TUI's placeholders: nothing of the row is in them. */
288
+ export const OPEN_WORDS = Object.freeze({
289
+ left: (name) => [{ own: "You left " }, { shown: name }, { own: ". It keeps running." }],
290
+ failed: (name) => [{ shown: name }, { own: " could not be opened." }],
291
+ link: (machine) => [{ own: "The connection to " }, { shown: machine }, { own: " ended." }],
292
+ unknown: (name) => [{ own: "The viewer of " }, { shown: name }, { own: " ended without saying why." }],
293
+ notRunning: (name) => [{ shown: name }, { own: " is not running, so it has no terminal to open." }],
294
+ stateUnknown: (name) => [{ own: "Whether " }, { shown: name }, { own: " runs is not known, so it is not opened." }],
295
+ 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." }],
296
+ });
297
+ /** A sentence from outside (a reason of the shared home's, the preflight table's), as a text
298
+ * under the line: drawn as the detail draws a reason, wrapped on the reason's rows, never as one
299
+ * unbroken part (a part is a name). */
300
+ const outside = (value) => (value === null ? [] : [value]);
301
+
302
+ /** Whether a row is of another machine: the shared home names its server on it. */
303
+ const elsewhere = (row) => typeof row.server === "string" && row.server !== "";
304
+
305
+ /** Whether `row`'s terminal can be opened from here, and what Enter does: `acts` is the row's
306
+ * instanceActs answer (computed once per selected row, for the detail too).
307
+ * { open: true, id, name, machine, target, routed } the kernel's viewer can be started:
308
+ * `target` is what the shared sessionAttachArgv and prepareRemoteTerm take, `routed` true
309
+ * for a row of another machine (its preflight runs first)
310
+ * { open: false, said: { said, under } } opens nothing, and this says why
311
+ * Whether a row can be opened is the shared openAct's, switched on its reason's code, never on a
312
+ * sentence; the TUI adds only the two feature gates on top of an enabled answer. */
313
+ export function openDecision(state, row, acts) {
314
+ const name = row.instance, id = instanceId(row);
315
+ const machine = elsewhere(row) ? row.deployment?.machine ?? row.server : null;
316
+ const no = (said, under = []) => ({ open: false, said: { said, under } });
317
+ const act = openAct(row);
318
+ if (act === null) {
319
+ const held = acts.blocked ?? acts.limited;
320
+ return no([], outside(reasonSpoken(held)));
321
+ }
322
+ if (!act.enabled) {
323
+ if (act.reason.code === "not-running") return no(OPEN_WORDS.notRunning(name));
324
+ if (act.reason.code === "state-unknown") return no(OPEN_WORDS.stateUnknown(name));
325
+ return no([], outside(reasonSpoken(act.reason)));
326
+ }
327
+ if (!elsewhere(row)) {
328
+ return detachKeySupported(state.cli) ? { open: true, id, name, machine, target: { home: row.home }, routed: false } : no(OPEN_WORDS.noKey(null));
329
+ }
330
+ if (roster(state).opens.get(row.deployment?.id) !== true) return no(OPEN_WORDS.noKey(machine));
331
+ return { open: true, id, name, machine, target: { serverId: row.server, instance: row.instance, home: row.home }, routed: true };
332
+ }
333
+
334
+ /** The line after the viewer returned, or null when the TUI says nothing of its own (the viewer
335
+ * ended without the key: the list shows the agent as the kernel now reports it). `status` is the
336
+ * child's exit status as Node reports it; the shared attachExit reads it, the TUI compares no
337
+ * number. What the viewer printed on stderr stands under a failure, once, as one text in
338
+ * quotation marks naming nobody: OATS, tmux and ssh all print there, and nothing is compared
339
+ * with it. */
340
+ export function returnedLine({ name, machine, routed }, status, stderr) {
341
+ const word = attachExit(status, { keyed: true, routed });
342
+ if (word === "ended") return null;
343
+ if (word === "left") return { said: OPEN_WORDS.left(name), under: [] };
344
+ if (word === "unknown") return { said: OPEN_WORDS.unknown(name), under: [] };
345
+ const line = displayLine(stderr);
346
+ const under = line === null ? [] : [line === DETAIL_WITHHELD ? DETAIL_WITHHELD : `"${line}"`];
347
+ return { said: word === "link" ? OPEN_WORDS.link(machine) : OPEN_WORDS.failed(name), under };
348
+ }
349
+
350
+ /** The line after a preflight that failed, or null when there is nothing to say: the person's own
351
+ * Esc, or a row that went away (E_TERM_CONTEXT_CHANGED). Else the shared table's sentence, and
352
+ * under it what the kernel said, when it said something (kernelLines). */
353
+ export function preflightLine({ machine }, error) {
354
+ const failure = preflightFailure(error, machine);
355
+ if (failure.code === "E_TERM_CONTEXT_CHANGED") return null;
356
+ return { said: [], under: [...outside(failure.sentence), ...(failure.said === null ? [] : kernelLines(failure.said.message, failure.said.fix, TERMS))] };
357
+ }
358
+
255
359
  /** The facts of one instance, a label and a value per line; a fact that is absent is left out.
256
360
  * `form`: `line` (one row), `wrap` (a sentence, on as many rows as it needs), `end` (read from
257
361
  * its end: a path). A fact with no label continues the one above it. Every value is text the
258
362
  * TUI did not write, or holds some: the view draws all of them through shown(). `now` is the
259
363
  * time of the paint, so the waited time is right whenever the screen is drawn. */
260
- function detailOf(state, r, item, now) {
364
+ function detailOf(state, r, item, now, acts) {
261
365
  const row = item.row, facts = [];
262
366
  const add = (label, value, form = "line") => { if (text(value)) facts.push({ label, value, form }); };
263
367
  add("soul", row.agent);
@@ -270,7 +374,7 @@ function detailOf(state, r, item, now) {
270
374
  if (said && said.key !== "live") add("", said.detail, "wrap");
271
375
  }
272
376
  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;
377
+ const held = acts.blocked ?? acts.limited;
274
378
  // The row's own text stands under its state, in the form that says who made it. Who made it is
275
379
  // the shared home's to say, in two ways, and the TUI writes no word and no sentence of its own
276
380
  // for either: the row's mark, which originLead turns into the words that go before the text;
@@ -283,13 +387,8 @@ function detailOf(state, r, item, now) {
283
387
  // draws the withheld word and nothing else. (The view asks again about the whole value: words
284
388
  // in front never change the answer; a closing quotation mark can, for a text that ends in a
285
389
  // 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
- }
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");
293
392
  // What holds the row, when that is a sentence of the shared home's and not the row's text: a
294
393
  // reason with an `origin` is the row's text, and so is one whose sentence is that text. Either
295
394
  // stands once, under the state.
@@ -359,6 +458,7 @@ export function model(state, { page, now, at, cols }) {
359
458
  view: state.view, focus: state.focus, ascii: state.ascii, actions: state.actions, filter: state.filter,
360
459
  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
460
  detailTop: state.detailTop, helpTop: state.helpTop, open: state.open !== null,
461
+ detachKey: state.detachKey, opening: state.opening, outcome: state.outcome, openable: false,
362
462
  };
363
463
  // The view under the help decides what the header says.
364
464
  const under = state.view === "help" ? state.back : state.view;
@@ -371,7 +471,7 @@ export function model(state, { page, now, at, cols }) {
371
471
  return {
372
472
  ...common, under, list: [], above: 0, below: 0, wordWidth: 0, detail: null,
373
473
  // 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,
474
+ workspace: "", machines: 0, here: false, machine: null, counts: [], readAt: null, notice: null, note: null, empty: null, observed: true, outcome: null,
375
475
  filter: Object.freeze({ editing: state.switcher.editing, query: state.switcher.query }),
376
476
  switcher: {
377
477
  rows: s.items.slice(win.top, win.top + win.size).map((item) => (item.key === undefined ? item : { ...item, selected: item.key === s.selected })),
@@ -380,13 +480,18 @@ export function model(state, { page, now, at, cols }) {
380
480
  };
381
481
  }
382
482
  const selected = state.selected === null ? -1 : r.index.get(state.selected) ?? -1;
483
+ // What the detail, the footer and Enter read of the selected row is worked out once per paint.
484
+ const row = selected >= 0 ? r.items[selected].row : null, acts = row ? instanceActs(row) : null;
485
+ const decision = row ? openDecision(state, row, acts) : null;
383
486
  // The window holds the selection, unless the list was scrolled away from it on purpose.
384
487
  const win = windowOf({ top: state.top, count: r.items.length, height: page, keep: state.loose ? -1 : selected });
385
488
  return {
386
489
  ...common, under,
387
490
  list: r.items.slice(win.top, win.top + win.size).map((item) => (item?.id !== undefined ? { kind: "row", ...listRow(state, r, item) } : item)),
388
491
  above: win.above, below: win.below, wordWidth: r.wordWidth,
389
- detail: selected >= 0 ? detailOf(state, r, r.items[selected], now) : null,
492
+ detail: selected >= 0 ? detailOf(state, r, r.items[selected], now, acts) : null,
493
+ // Enter opens the selected agent's terminal now: the footer names the key that returns.
494
+ openable: decision?.open === true && state.opening === null,
390
495
  switcher: null,
391
496
  };
392
497
  }
@@ -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
+ }
@@ -1,7 +1,9 @@
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
+ // 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.)
5
7
  // No function of this module decodes a kernel answer. Each one passes values between the shared
6
8
  // functions (client.mjs), which decide what a roster, a row and a failed read are, once, for both
7
9
  // clients: the TUI never writes "stopped" for a row and never builds the collector's input by hand.
@@ -154,7 +156,7 @@ const said = (error) => String(error?.message ?? error);
154
156
 
155
157
  /** The reader of a run: its cycles over every served deployment, the roster of other machines,
156
158
  * their children, and the way out.
157
- * -> { start(), request({ live }), touch(), voidInFlight(), stop(), children() }
159
+ * -> { start(), request({ live }), touch(), voidInFlight(), hold(), release(), exec, stop(), children() }
158
160
  *
159
161
  * `cli` is probeKernel's record (`cli.bin` the absolute path of bin/oats.mjs). The reader keeps no
160
162
  * answer of its own: what a run holds is the caller's store, asked for when it is needed.
@@ -186,20 +188,24 @@ const said = (error) => String(error?.message ?? error);
186
188
  * list of options, `detached` is not one of them, and a child it starts stays in the TUI's group
187
189
  * whatever it is asked. `run` below is the part of execFile's contract the shared readers use.
188
190
  *
189
- * ENDING A CHILD holds because this version only reads. A KERNEL CALL THAT CHANGES SOMETHING MUST
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
190
193
  * NEVER BE KILLED BY THE TUI: a killed stop or start leaves a marker that refuses every later one.
191
194
  * So every child is remembered with its kind, only kind "read" is ever signalled, and a later
192
195
  * version's writing calls get a kind of their own.
193
196
  *
194
197
  * `timers` are the loop's, the idle timer's and the children's time limits (for tests). */
195
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 }) {
196
- /** child -> { kind, exited, giveUp }: every child that has not ended and was not ended. */
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. */
197
201
  const remembered = new Map();
198
202
  let started = false, stopped = false, idleTimer = null;
199
203
  /** `counter` numbers the cycles. `epoch` moves when the cycles in flight are made void; `flight`
200
204
  * is the epoch the cycle now running began in (the loop runs one at a time). `served` is what
201
205
  * getServed() answered at the start of that cycle. */
202
206
  let counter = 0, epoch = 0, flight = 0, served = [];
207
+ /** The terminal is lent (hold()): no cycle and no roster read starts until release(). */
208
+ let held = false;
203
209
  /** The roster of other machines. `rosterFlight` is the read in flight (a token of its own, so an
204
210
  * answer knows whether it is still awaited), or null. `rosterEnded` is now() when the last read
205
211
  * that was not given up ended, or null while none has. `gatedSaid`: a kernel that reads no
@@ -214,9 +220,9 @@ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onR
214
220
  * other options go to spawn as they are, with `detached: true` added. Returns the child.
215
221
  * The child is forgotten when it ends: `close`, `error` for one that did not start, or the
216
222
  * moment the reader ends it. */
217
- function run(kind, args, { timeout = 0, maxBuffer = Infinity, encoding = "utf8", ...rest }, callback) {
223
+ function run(kind, args, { timeout = 0, maxBuffer = Infinity, encoding = "utf8", ...rest }, callback, { asked = false } = {}) {
218
224
  const child = spawn(process.execPath, args, { ...rest, detached: true });
219
- const printed = { stdout: "", stderr: "" }, record = { kind, exited: false, giveUp };
225
+ const printed = { stdout: "", stderr: "" }, record = { kind, exited: false, giveUp, asked };
220
226
  let over = false, severed = false, verdict = null, timer = null;
221
227
  function finish(error) {
222
228
  if (over) return;
@@ -281,8 +287,9 @@ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onR
281
287
  remembered.set(child, record);
282
288
  return child;
283
289
  }
284
- function endReads() {
285
- for (const record of [...remembered.values()]) if (record.kind === "read") record.giveUp(ended());
290
+ /** End the reads remembered: every one, or (`cycles`) only those a cycle or the roster started. */
291
+ function endReads({ cycles = false } = {}) {
292
+ for (const record of [...remembered.values()]) if (record.kind === "read" && !(cycles && record.asked)) record.giveUp(ended());
286
293
  }
287
294
 
288
295
  /** The exec handed to the shared readers: execFile's signature, for `node <bin> <argv…>` (see
@@ -294,6 +301,24 @@ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onR
294
301
  if (stopped || flight !== epoch) throw new Error("this read was given up before it started");
295
302
  return run("read", [bin, ...argv], options.env === undefined ? { ...options, env } : options, callback);
296
303
  }
304
+ /** The exec of a read the loop asks for itself, outside every cycle: the preflight of an agent
305
+ * on another machine (`oats session inspect`, through the shared prepareRemoteTerm). The same
306
+ * child as a cycle's (kind "read", a session of its own, the reader's environment where the
307
+ * options name none, ended on every way out), not made void by voidInFlight(): the loop ends it
308
+ * through `signal`, which ends the child's whole group as the reader's own giving up does. A
309
+ * `signal` already aborted starts nothing. It throws after stop(). */
310
+ function askedExec(bin, argv, { signal, ...options }, callback) {
311
+ if (stopped) throw new Error("the reader has stopped");
312
+ if (signal?.aborted) throw new Error("this read was given up before it started");
313
+ const child = run("read", [bin, ...argv], options.env === undefined ? { ...options, env } : options, callback, { asked: true });
314
+ if (signal) {
315
+ const record = remembered.get(child);
316
+ const abandon = () => record?.giveUp(ended());
317
+ signal.addEventListener("abort", abandon, { once: true });
318
+ child.once("close", () => signal.removeEventListener("abort", abandon));
319
+ }
320
+ return child;
321
+ }
297
322
  /** The shared observer, with the shared reader over this exec and no reader of the TUI's own: a
298
323
  * failed read has the same reasons here as in the Desktop. It admits a deployment of the cycle
299
324
  * now running and no other. */
@@ -392,7 +417,7 @@ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onR
392
417
  * started beside two would be refused as busy and never read). The cycle is over when its
393
418
  * deployments are; with none served it reads nothing local. */
394
419
  async function cycle({ live }) {
395
- if (stopped) return;
420
+ if (stopped || held) return;
396
421
  flight = epoch;
397
422
  const mine = epoch, number = ++counter, at = clock();
398
423
  const over = () => stopped || mine !== epoch;
@@ -444,6 +469,8 @@ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onR
444
469
  * children remembered are ended as stop() ends them. The reader stays usable: the loop goes
445
470
  * on, and the next cycle (the caller requests a live one on the return) emits with the next
446
471
  * number. A cycle requested but not begun is not in flight: it runs after the return.
472
+ * A read the loop asked for itself (the preflight, `exec`) is not a cycle's: it is left as it
473
+ * is, and the loop gives it up through its signal.
447
474
  * THE SAME HOLDS FOR A ROSTER READ IN FLIGHT, which is not part of a cycle and may outlive
448
475
  * the one that began it: its child is ended, whatever it answers is dropped (no onRoster; the
449
476
  * caller tells its store that nothing is being collected), and it is no longer in flight, so
@@ -453,8 +480,17 @@ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onR
453
480
  voidInFlight() {
454
481
  epoch++;
455
482
  rosterFlight = null;
456
- endReads();
483
+ endReads({ cycles: true });
457
484
  },
485
+ /** The terminal is lent to the kernel's viewer: from now until release() no cycle begins and
486
+ * no roster read starts (a cycle the loop's timer or a request would begin does nothing and
487
+ * emits nothing). What is in flight is not touched here: the caller made it void first, as at
488
+ * a stop. Idempotent. */
489
+ hold() { held = true; },
490
+ /** The terminal is back: cycles begin again. The caller asks for a live one. */
491
+ release() { held = false; },
492
+ /** See askedExec. */
493
+ exec: askedExec,
458
494
  /** Leave: synchronous and idempotent, safe before start(). The loop and the idle timer are
459
495
  * stopped, the observer disposed and every reading child ended (see `sever`), the roster's
460
496
  * included. A cycle in flight ends without emitting and without starting anything, and so