@awebai/oats 0.56.0 → 0.57.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/bin/oats.mjs +18 -10
  2. package/docs/configuration.md +17 -27
  3. package/docs/desktop-cli-api.md +59 -3
  4. package/docs/desktop.md +25 -4
  5. package/docs/execution-targets.md +6 -1
  6. package/docs/implementation.md +106 -5
  7. package/docs/integrations.md +8 -4
  8. package/docs/knowledge.md +93 -38
  9. package/docs/official-catalog.md +3 -3
  10. package/docs/packages.md +12 -12
  11. package/docs/release-notes/v0.57.0.md +283 -0
  12. package/docs/release-notes/v0.57.1.md +275 -0
  13. package/docs/schedules.md +8 -3
  14. package/docs/servers.md +18 -0
  15. package/docs/souls-and-instances.md +126 -15
  16. package/docs/tui.md +333 -95
  17. package/docs/workspaces.md +2 -2
  18. package/lib/core.mjs +439 -126
  19. package/lib/instance-lifecycle.mjs +45 -9
  20. package/lib/session-viewer.mjs +29 -4
  21. package/lib/worktree.mjs +23 -2
  22. package/package-catalog.json +2 -2
  23. package/package.json +1 -1
  24. package/packages/client/cli-adapter.mjs +9 -7
  25. package/packages/client/cli-locator.mjs +2 -2
  26. package/packages/client/composed-gate.mjs +34 -0
  27. package/packages/client/inspect-boundary.mjs +157 -0
  28. package/packages/client/inspect-cache.mjs +86 -0
  29. package/packages/client/instance-lifecycle.mjs +10 -3
  30. package/packages/client/keyed-catalog.mjs +132 -0
  31. package/packages/client/launch-prompt-outcome.mjs +1 -1
  32. package/packages/client/launch-view.mjs +46 -0
  33. package/packages/client/session-attach.mjs +7 -5
  34. package/packages/client/soul-catalog.mjs +77 -0
  35. package/packages/client/soul-colors.mjs +31 -0
  36. package/packages/client/soul-facts.mjs +85 -0
  37. package/packages/client/soul-rows.mjs +48 -0
  38. package/packages/client/spawn-apply-cli.mjs +11 -6
  39. package/packages/client/spawn-apply.mjs +212 -0
  40. package/packages/client/spawn-messages.mjs +131 -85
  41. package/packages/client/spawn-preview-contract.mjs +3 -0
  42. package/packages/client/spawn-preview-facts.mjs +119 -0
  43. package/packages/client/spawn-preview.mjs +152 -0
  44. package/packages/client/spawn-transaction.mjs +136 -0
  45. package/packages/tui/README.md +43 -13
  46. package/packages/tui/lib/actions.mjs +18 -2
  47. package/packages/tui/lib/client.mjs +4 -0
  48. package/packages/tui/lib/config.mjs +9 -14
  49. package/packages/tui/lib/main.mjs +241 -55
  50. package/packages/tui/lib/model.mjs +230 -29
  51. package/packages/tui/lib/panel.mjs +955 -0
  52. package/packages/tui/lib/read.mjs +134 -24
  53. package/packages/tui/lib/store.mjs +184 -31
  54. package/packages/tui/lib/term/capture.mjs +260 -0
  55. package/packages/tui/lib/term/screen.mjs +44 -8
  56. package/packages/tui/lib/term/style.mjs +78 -6
  57. package/packages/tui/lib/term/text.mjs +24 -4
  58. package/packages/tui/lib/term/through.mjs +213 -0
  59. package/packages/tui/lib/term/tty.mjs +7 -60
  60. package/packages/tui/lib/views/act.mjs +85 -0
  61. package/packages/tui/lib/views/frame.mjs +153 -37
  62. package/packages/tui/lib/views/help.mjs +22 -14
  63. package/skills/oats-getting-started/SKILL.md +4 -3
  64. package/packages/tui/lib/open.mjs +0 -45
@@ -1,20 +1,24 @@
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, follows them, and opens an agent's terminal with the kernel's own
5
- // viewer; it changes nothing in a deployment (docs/tui.md).
4
+ // machines registered here, follows them, opens an agent's terminal in a panel beside the list
5
+ // (the kernel's own viewer, in a pane of the run's private tmux server: lib/panel.mjs), and
6
+ // stops, starts, restarts and retires an instance after a confirmation, through the shared
7
+ // lifecycle boundary and start rule (docs/tui.md).
6
8
  import { homedir } from "node:os";
7
9
  import { resolve } from "node:path";
8
10
  import { bindings } from "./actions.mjs";
9
- import { displayLine, pendingEntry, prepareRemoteTerm, sessionAttachArgv } from "./client.mjs";
11
+ import { TERMS, createLifecycleBoundary, createLifecycleConfirmation, displayLine, heldHome, pendingEntry, prepareRemoteTerm, sessionAttachArgv, startInstance } from "./client.mjs";
10
12
  import { loadConfig } from "./config.mjs";
11
- import { model, roster } from "./model.mjs";
12
- import { startViewer } from "./open.mjs";
13
- import { admitDeployment, createReader, findDeployment, leaveInstance, offeredDeployments, probeKernel } from "./read.mjs";
13
+ import { ACT_WORDS, actContext, actCwd, localDeployments, model, roster } from "./model.mjs";
14
+ import { createPanel, sweep } from "./panel.mjs";
15
+ import { CHANGE_FILES, admitDeployment, createReader, findDeployment, leaveInstance, offeredDeployments, probeKernel, realpath, tellable } from "./read.mjs";
14
16
  import { initialState, reduce } from "./store.mjs";
17
+ import { captureRows } from "./term/capture.mjs";
15
18
  import { createKeyParser, keyId } from "./term/keys.mjs";
16
19
  import { createScreen, glyphs } from "./term/screen.mjs";
17
20
  import { colorEnabled } from "./term/style.mjs";
21
+ import { backKeySequences, createThrough } from "./term/through.mjs";
18
22
  import { createGuard, isTerminal } from "./term/tty.mjs";
19
23
  import { frame, layout } from "./views/frame.mjs";
20
24
 
@@ -24,7 +28,8 @@ const HELP = `Usage:
24
28
 
25
29
  The OATS terminal client (preview): a full-screen view of a workspace's instances,
26
30
  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.
31
+ agent's terminal beside the list with Enter, and stops, retires, starts or
32
+ restarts an instance (X, D, S, R) after a confirmation.
28
33
  Keys: ? help, Enter open, w workspaces, q quit.
29
34
  docs/tui.md has the rest.
30
35
 
@@ -61,15 +66,22 @@ function errorLines(error) {
61
66
  return String(text).split("\n", 12).map((line) => displayLine(line)).filter(Boolean);
62
67
  }
63
68
 
64
- /** What the loop does outside the terminal, each replaceable by a test. */
65
- const EFFECTS = Object.freeze({ loadConfig, findDeployment, probeKernel, createReader, offeredDeployments, admitDeployment, prepareRemoteTerm, startViewer });
69
+ /** What the loop does outside the terminal, each replaceable by a test. `realpath` is the one the
70
+ * shared start rule checks a local home with; `startInstance` and `createLifecycleConfirmation`
71
+ * are the shared home's, replaceable so a test can drive the loop's wiring. `runDir` makes the
72
+ * run's private directory (the reader's change output and the panel's tmux server share it), and
73
+ * `removeDir` removes it on the way out once both have removed their files; `sweep` removes what
74
+ * runs that are gone left of theirs (lib/panel.mjs). */
75
+ const EFFECTS = Object.freeze({ loadConfig, findDeployment, probeKernel, createReader, offeredDeployments, admitDeployment, prepareRemoteTerm, createPanel, sweep,
76
+ runDir: CHANGE_FILES.dir, removeDir: CHANGE_FILES.remove, realpath, tellable, startInstance, createLifecycleConfirmation, createLifecycleBoundary });
66
77
 
67
78
  /** Run. Resolves with the exit status; never calls process.exit, so what was written drains.
68
79
  * Before the alternate screen, in this order, each failure one line on stderr and status 1:
69
80
  * the arguments; the instance variables removed from the environment (a TUI started in an
70
81
  * agent's pane must read the deployment it was asked about, and so must every child it starts);
71
82
  * the terminal; the user's tui.json; the deployment; the kernel it shipped with. */
72
- export async function main({ argv, stdin, stdout, stderr, env, proc = process, now = Date.now, setTimer = setTimeout, clearTimer = clearTimeout, cwd = () => process.cwd(), home = homedir(), effects = EFFECTS }) {
83
+ export async function main({ argv, stdin, stdout, stderr, env, proc = process, now = Date.now, setTimer = setTimeout, clearTimer = clearTimeout, cwd = () => process.cwd(), home = homedir(), effects: given = EFFECTS }) {
84
+ const effects = given === EFFECTS ? EFFECTS : { ...EFFECTS, ...given };
73
85
  const { options, error } = parseArgs(argv);
74
86
  if (error) { stderr.write(`${error}\n`); return 1; }
75
87
  if (options.help) { stdout.write(HELP); return 0; }
@@ -92,14 +104,24 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
92
104
  let parser = createKeyParser({ now });
93
105
  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 });
94
106
  const keymap = bindings(state.actions);
107
+ // While a terminal has the focus the bytes typed go to the agent: this scanner takes from them
108
+ // only the back key and a bracketed paste (term/through.mjs). A new one each time the terminal
109
+ // takes the focus, so nothing held from before is typed into it.
110
+ const backKey = backKeySequences(state.detachKey);
111
+ let through = createThrough({ sequences: backKey, now }), throughTimer = null;
95
112
  if (offered) state = reduce(state, { offered }, keymap).state;
96
113
  // What the last frame drew, for the store: how tall the list pane is and how far the other
97
114
  // pane scrolls. The store holds no size of its own.
98
115
  let drawn = { page: 1, extent: 0, room: 1, cols: 1 };
99
- let full = true, escTimer = null, ended = false;
116
+ let full = true, escTimer = null, ended = false, reads = 0;
100
117
  /** The preflight of another machine's agent under way: `{ id, controller, prepared }`, where
101
118
  * `prepared` is what it answered (`{ binary, args }`) once it has; or null. */
102
119
  let preflight = null;
120
+ /** The run's private directory, made at the first change or the first open (lib/read.mjs
121
+ * CHANGE_FILES): the reader writes a change's output there, and the panel keeps its tmux
122
+ * server's socket there. */
123
+ let dir = null;
124
+ const runDir = () => (dir ??= effects.runDir());
103
125
 
104
126
  // What the reader reads for, it asks of the state at that moment: the served deployments, the
105
127
  // entry a failed read keeps, and the roster and the memory the next outcome is made from.
@@ -109,7 +131,38 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
109
131
  getEntry: (id) => state.entries.get(id) ?? null,
110
132
  getRoster: () => ({ remote: state.remote, memory: state.memory, notes: state.notes }),
111
133
  onEntry: heard, onRoster: heard,
134
+ files: { ...CHANGE_FILES, dir: runDir },
112
135
  });
136
+ // THE OPEN TERMINAL (docs/tui.md, "Open an agent's terminal"): one at a time, in the panel.
137
+ // `viewing` is its viewer, `{ id, panel }` (the row's instanceId, and the panel's own id once
138
+ // the window exists, null before); `screenNow` the last capture (`{ lines, cursor }`), drawn
139
+ // until the next; `panelSize` and `panelShown` what the panel was last told.
140
+ let viewing = null, screenNow = null, panelSize = null, panelShown = true;
141
+ const panel = effects.createPanel({
142
+ dir: runDir, env, capture: captureRows,
143
+ onScreen: ({ id, screen: lines, cursor }) => { if (!ended && viewing !== null && viewing.panel === id) { screenNow = { lines, cursor }; guard.attempt(() => guard.draw()); } },
144
+ // The viewer ended. The store is told, whatever ended it; a terminal the person closed is no
145
+ // longer `viewing`, and the store says nothing of it.
146
+ onClosed: ({ id, status = null, stderr = "", asked = false }) => {
147
+ if (viewing === null || viewing.panel !== id) return;
148
+ const row = viewing.id;
149
+ viewing = null; screenNow = null;
150
+ heard({ returned: { id: row, status, stderr, asked } });
151
+ },
152
+ });
153
+ // THE ACTS (docs/tui.md, "Stopping, starting, restarting and retiring"). One lifecycle boundary
154
+ // per run: its plans, its kept answers and its one apply at a time are this run's. Its exec runs
155
+ // a plan read as a read the loop asked for (kind "read", ended on every way out) and an apply
156
+ // (`detached: true`, cliLifecycle's own mark of a change) as a change, which the TUI never ends.
157
+ // `applying` is the label of the apply this run's confirmation just sent: only one confirmation
158
+ // is open at a time, and the boundary calls its exec in the same turn as the request.
159
+ let applying = null;
160
+ const boundary = effects.createLifecycleBoundary({ terms: TERMS, exec: (bin, argv, { detached, ...options }, callback) => (detached
161
+ ? reader.changeExec(bin, argv, { ...options, label: applying }, callback)
162
+ : reader.exec(bin, argv, options, callback)) });
163
+ /** The confirmation open now: `{ n, made }`, `made` the shared confirmation; or null. */
164
+ let confirmation = null;
165
+
113
166
  /** What the reader gave, into the state, and the screen after it. */
114
167
  function heard(event) { if (!ended) guard.attempt(() => { if (!took(reduce(state, event, keymap))) guard.draw(); }); }
115
168
  /** One step of the reducer taken: the state, then what only the loop can do. True once the
@@ -128,32 +181,83 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
128
181
  took(reduce(state, admitted.ok ? { admitted: admitted.deployment, at: clock() } : { refused: effect.admit }, keymap));
129
182
  }
130
183
  if (effect.abandon) giveUpPreflight();
184
+ if (effect.close !== undefined) closeTerminal();
131
185
  if (effect.open) open(effect.open);
132
- if (effect.lend !== undefined) {
186
+ if (effect.panel !== undefined) {
133
187
  const ready = preflight;
134
188
  preflight = null;
135
- if (ready?.id === effect.lend && ready.prepared) lendTo(effect.lend, ready.prepared.binary, ready.prepared.args);
189
+ if (ready?.id === effect.panel && ready.prepared) view(effect.panel, ready.prepared.binary, ready.prepared.args);
136
190
  }
191
+ if (effect.dismiss !== undefined) dismiss(effect.dismiss);
192
+ if (effect.act) openConfirmation(effect.act);
193
+ if (effect.call) callConfirmation(effect.call);
194
+ if (effect.start) startAct(effect.start);
137
195
  if (effect.refresh) refresh(effect.refresh);
138
196
  return false;
139
197
  }
140
198
 
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. */
199
+ /** What the boundary admits a request of deployment `id` against, read at every admission. */
200
+ const contextOf = (id) => actContext(state, id, clock());
201
+ /** Open the shared confirmation of a stop or a retire the store decided on (`{ n, verb, row,
202
+ * label }`). Every step it tells goes to the store as `{ acted }`; an answer that settles asks
203
+ * for a live read of the rows (onSettled), and nothing else after an apply does. */
204
+ function openConfirmation({ n, verb, row, label }) {
205
+ dismiss(confirmation?.n);
206
+ const id = row.deployment?.id, name = row.instance;
207
+ const target = { workspace: id, instance: name, agent: row.agent, agentsRoot: row.agentsRoot, home: row.home, server: row.server ?? null };
208
+ const mine = { n, made: null };
209
+ const tell = () => { if (mine.made && confirmation === mine) heard({ acted: { n, confirmation: { ...mine.made.state(), view: mine.made.view() } } }); };
210
+ confirmation = mine;
211
+ mine.made = effects.createLifecycleConfirmation({
212
+ request: (body) => { if (body?.action === "apply") applying = { verb, name }; return boundary(body, () => contextOf(id)); },
213
+ target, operation: verb, terms: TERMS, label, leftover: heldHome(row)?.kind === "spawn-incomplete",
214
+ onChange: tell, onSettled: () => refresh({ live: true }),
215
+ });
216
+ tell();
217
+ }
218
+ /** A button pressed in the confirmation: its call, when it is still the open one. */
219
+ function callConfirmation({ n, method, args = [] }) {
220
+ if (confirmation?.n === n) confirmation.made[method](...args);
221
+ }
222
+ /** The confirmation closed: what it sent goes on, and what it answers is no longer told. */
223
+ function dismiss(n) {
224
+ if (confirmation === null || confirmation.n !== n) return;
225
+ const { made } = confirmation;
226
+ confirmation = null;
227
+ made?.close();
228
+ }
229
+ /** Start or restart the row (`{ n, verb, id, row }`) through the shared start rule, once, with no
230
+ * launch choice. Its child is a change of this run: the store hears when it is spawned and when
231
+ * it closes (`starting`), and the answer, whatever it is, asks for a live read. */
232
+ function startAct({ n, verb, id, row }) {
233
+ const label = { verb, name: row?.instance ?? "" };
234
+ const exec = (bin, argv, options, callback) => {
235
+ const child = reader.changeExec(bin, argv, { ...options, label }, (...answer) => { heard({ acted: { closed: id } }); callback(...answer); });
236
+ heard({ acted: { spawned: { id, verb }, at: now() } });
237
+ return child;
238
+ };
239
+ Promise.resolve()
240
+ .then(() => effects.startInstance(probe.cli, row, {}, { restart: verb === "restart", deployments: localDeployments(state, clock()), realpath: effects.realpath, localCwd: actCwd(state), exec, terms: TERMS }))
241
+ .then((answer) => heard({ acted: { n, answer } }), () => heard({ acted: { n, answer: null } }));
242
+ }
243
+
244
+ /** Open the agent the store decided on (lib/model.mjs openDecision). On this machine the viewer
245
+ * starts in the panel at once. On another, the shared preflight runs first over the reader's
246
+ * exec (a read like any other, ended on every way out), and what it prepared waits for the
247
+ * store's `panel`, which comes only if the open was not given up and the row is still there.
248
+ * The viewer is given no key of its own: the TUI takes the back key before the pane sees it. */
145
249
  function open(decision) {
146
250
  if (!decision.routed) {
147
251
  let args;
148
252
  // A target the shared home refuses (no absolute home) starts nothing; the line after says
149
253
  // 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);
254
+ try { args = sessionAttachArgv(probe.cli, decision.target); } catch { return void heard({ returned: { id: decision.id, status: null, stderr: "" } }); }
255
+ return view(decision.id, probe.cli.bin, args);
152
256
  }
153
257
  giveUpPreflight();
154
258
  const mine = preflight = { id: decision.id, controller: new AbortController(), prepared: null };
155
259
  Promise.resolve()
156
- .then(() => effects.prepareRemoteTerm(probe.cli, decision.target, { exec: reader.exec, signal: mine.controller.signal, detachKey: state.detachKey }))
260
+ .then(() => effects.prepareRemoteTerm(probe.cli, decision.target, { exec: reader.exec, signal: mine.controller.signal }))
157
261
  .then((prepared) => { if (preflight === mine) { mine.prepared = prepared; heard({ prepared: { id: mine.id } }); } },
158
262
  (error) => { if (preflight === mine) { preflight = null; heard({ prepared: { id: mine.id, error } }); } });
159
263
  }
@@ -164,49 +268,115 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
164
268
  preflight.controller.abort();
165
269
  preflight = null;
166
270
  }
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
- });
271
+ /** Start the viewer of row `id` (`node <bin> <args…>`) in the panel, at the size the frame gives
272
+ * the terminal, and tell the store when its window exists. One the panel could not start is a
273
+ * viewer that ended, with the panel's refusal: no tmux (or one too old), or tmux's own words.
274
+ * Nothing is lent: the reads and the screen go on. */
275
+ function view(id, bin, args) {
276
+ const mine = viewing = { id, panel: null };
277
+ const size = guard.size(), area = composed().made.terminal ?? { cols: size.cols, rows: Math.max(1, size.rows - 6) };
278
+ panelSize = { cols: area.cols, rows: area.rows };
279
+ // Shown: the panel keeps hidden or shown across its viewers, and the last one may have been
280
+ // closed hidden (behind the detail, or the list alone under 80 columns).
281
+ if (!panelShown) panel.setVisible(true);
282
+ panelShown = true;
283
+ Promise.resolve()
284
+ .then(() => panel.open({ argv: [process.execPath, bin, ...args], cols: area.cols, rows: area.rows }))
285
+ .then(({ id: made }) => {
286
+ if (viewing !== mine) return;
287
+ mine.panel = made;
288
+ // A frame of another size while the window was being made told a panel with no window yet.
289
+ if (panelSize.cols !== area.cols || panelSize.rows !== area.rows) panel.resize(panelSize.cols, panelSize.rows);
290
+ heard({ shown: { id } });
291
+ },
292
+ (error) => { if (viewing === mine) { viewing = null; heard({ returned: { id, status: null, stderr: typeof error?.detail === "string" ? error.detail : "", refused: error?.code === "E_PANEL_TMUX" ? "tmux" : "start" } }); } });
293
+ }
294
+ /** Close the open terminal's viewer (also one whose window is still being made): the agent keeps
295
+ * running, and the panel reports the end as asked for, which nobody waits for. */
296
+ function closeTerminal() {
297
+ if (viewing === null) return;
298
+ viewing = null; screenNow = null;
299
+ panel.close();
300
+ }
301
+ /** The panel told what the frame gives the terminal: shown or not (no capture runs while it is
302
+ * hidden, and one runs when it shows again), and its size (the viewer's window follows it). */
303
+ function fitPanel(given) {
304
+ // A view that draws no terminal (the help, the switcher, a confirmation) gives none.
305
+ const area = given ?? null;
306
+ if (viewing === null) return;
307
+ if ((area !== null) !== panelShown) { panelShown = area !== null; panel.setVisible(panelShown); }
308
+ if (area !== null && (area.cols !== panelSize.cols || area.rows !== panelSize.rows)) { panelSize = { cols: area.cols, rows: area.rows }; panel.resize(area.cols, area.rows); }
309
+ }
310
+ /** The frame for the state now, with what the loop needs of it: the layout first, because the
311
+ * model's window is as tall, and its sentences as wide, as the list pane it gives. The switcher
312
+ * takes the whole body and has no notice of a deployment. The last capture of the open
313
+ * terminal goes with the model: it is the panel's, not the store's. */
314
+ function composed() {
315
+ const size = guard.size(), at = clock();
316
+ const listing = (state.view === "help" ? state.back : state.view) === "switcher";
317
+ const r = listing ? { notice: null, note: null, observed: true } : roster(state, at);
318
+ const g = layout(r.notice, size, { observed: r.observed, note: r.note, ascii: state.ascii, outcome: listing ? null : state.outcome });
319
+ const m = { ...model(state, { page: g.page, now: now(), at, cols: g.listCols }), screen: screenNow };
320
+ return { size, g, made: frame(m, size) };
321
+ }
322
+ /** Whether what is typed goes to the agent: the open terminal has the focus. */
323
+ const typing = () => state.terminal?.focus === "terminal" && state.view === "instances";
324
+ /** Bytes typed while the terminal has the focus: to the agent as they came, a paste as a paste,
325
+ * and the back key to the store, which gives the focus to the list; what came after the back key
326
+ * in the same read is read as keys, by a parser that starts afresh. */
327
+ function typed(events) {
328
+ for (const event of events) {
329
+ if (event.input) panel.input(event.input);
330
+ else if (event.paste !== undefined) panel.paste(event.paste);
331
+ else if (event.back) {
332
+ parser = createKeyParser({ now });
333
+ if (took(reduce(state, { back: true }, keymap))) return;
334
+ if (event.rest.length) act(parser.feed(event.rest)); else guard.draw();
335
+ watchEscape();
336
+ }
337
+ }
338
+ watchThrough();
339
+ }
340
+ /** A beginning of the back key that nothing has followed for the parser's timeout is the agent's. */
341
+ function watchThrough() {
342
+ if (throughTimer !== null) { clearTimer(throughTimer); throughTimer = null; }
343
+ const due = through.timeoutAt();
344
+ if (due !== null) throughTimer = setTimer(() => { throughTimer = null; guard.attempt(() => { if (typing()) typed(through.expire()); }); }, Math.max(0, due - now()));
183
345
  }
184
346
  const guard = createGuard({
185
347
  stdin, stdout, proc, setTimer, clearTimer,
186
348
  frame() {
187
- const size = guard.size(), at = clock();
188
- // The layout first: the model's window is as tall, and its sentences as wide, as the list
189
- // pane it gives. The switcher takes the whole body and has no notice of a deployment.
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 });
193
- const made = frame(model(state, { page: g.page, now: now(), at, cols: g.listCols }), size);
349
+ const { size, g, made } = composed();
194
350
  drawn = { page: made.page, extent: made.extent, room: made.room, cols: g.listCols };
195
- const bytes = screen.render(made.rows, size, { full });
351
+ fitPanel(made.terminal);
352
+ const bytes = screen.render(made.rows, size, { full, cursor: made.cursor });
196
353
  full = false;
197
354
  return bytes;
198
355
  },
199
- onInput(bytes) { if (guard.lent) return; reader.touch(); act(parser.feed(bytes)); watchEscape(); },
356
+ onInput(bytes) {
357
+ reader.touch();
358
+ if (typing()) return typed(through.feed(bytes));
359
+ act(parser.feed(bytes)); watchEscape();
360
+ },
200
361
  onResize() { full = true; guard.draw(); },
201
- onRedraw() { full = true; guard.draw(); },
362
+ // Ctrl+L and the return from a stop: the whole screen, and the open terminal captured afresh.
363
+ onRedraw() { full = true; if (viewing !== null) panel.refresh(); guard.draw(); },
202
364
  // A cycle in flight when the process stops is no evidence about the deployment (lib/read.mjs):
203
365
  // it is dropped before the stop, and again after a stop nobody here asked for; the return
204
366
  // reads at once.
205
367
  // A preflight is given up first, by the TUI itself: ended as a read it would answer as a
206
368
  // timeout. The person opens the agent again.
207
- onStop() { stopPreflight(); dropReads(); },
208
- onResume(asked) { if (!asked) { stopPreflight(); dropReads(); } refresh({ live: true }); },
209
- onEnd() { ended = true; reader.stop(); },
369
+ // The open terminal's server and viewer live on through a stop; the panel stops sending output
370
+ // while nothing reads it, and captures afresh on the way back.
371
+ onStop() { stopPreflight(); dropReads(); if (viewing !== null) panel.pause(); },
372
+ onResume(asked) { if (!asked) { stopPreflight(); dropReads(); } if (viewing !== null) panel.resume(); refresh({ live: true }); },
373
+ // On the way out the confirmation is closed, the private tmux server is ended (its viewer with
374
+ // it) and the reads end; a change in flight is let go, never signalled (lib/read.mjs
375
+ // changeExec), and named after the screen is left.
376
+ // The run's directory goes last, made for whichever of the two needed it first: the reader
377
+ // removes it only when it wrote a change there, and one it cannot remove (a change still
378
+ // writing) stays.
379
+ onEnd() { ended = true; dismiss(confirmation?.n); panel.end(); reader.stop(); if (dir !== null) { try { effects.removeDir(dir); } catch { /* not empty, or gone */ } } },
210
380
  });
211
381
  function refresh(how) { Promise.resolve(reader.request(how)).catch(() => {}); }
212
382
  /** A preflight under way when the process stops: given up, and the store told. */
@@ -218,13 +388,20 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
218
388
  /** Every read in flight is void (lib/read.mjs), the roster's with them: the reader says nothing
219
389
  * for a void read, so the state is told here that none is in flight. */
220
390
  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). */
391
+ /** The events of one batch of input, in order. Once one of them gave the terminal the focus,
392
+ * the rest are dropped: they were typed before it had it, and neither the list nor the agent
393
+ * is to have them (a `q` behind the Enter would end the run). Each batch is one read of input,
394
+ * numbered (`read`): a confirmation ignores the press of its act in the read that moved the
395
+ * focus onto it, so a paste cannot both move and press. */
224
396
  function act(events) {
397
+ const read = ++reads;
225
398
  for (const event of events) {
226
- if (guard.lent) return;
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;
399
+ if (took(reduce(state, "paste" in event ? { paste: event.paste } : { key: keyId(event), ...(typeof event.text === "string" && !event.alt ? { text: event.text } : {}), read, ...drawn }, keymap))) return;
400
+ if (typing()) {
401
+ if (escTimer !== null) { clearTimer(escTimer); escTimer = null; }
402
+ through = createThrough({ sequences: backKey, now });
403
+ break;
404
+ }
228
405
  }
229
406
  guard.draw();
230
407
  }
@@ -232,15 +409,24 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
232
409
  function watchEscape() {
233
410
  if (escTimer !== null) { clearTimer(escTimer); escTimer = null; }
234
411
  const due = parser.timeoutAt();
235
- if (due !== null) escTimer = setTimer(() => { escTimer = null; if (!guard.lent) guard.attempt(() => { act(parser.expire()); watchEscape(); }); }, Math.max(0, due - now()));
412
+ if (due !== null) escTimer = setTimer(() => { escTimer = null; if (!typing()) guard.attempt(() => { act(parser.expire()); watchEscape(); }); }, Math.max(0, due - now()));
236
413
  }
237
414
 
238
415
  guard.start();
239
416
  guard.attempt(() => { if (!ended) Promise.resolve(reader.start()).catch(() => {}); });
240
417
  guard.attempt(() => guard.draw());
418
+ // Once a run, after the first frame: what runs that are gone left of their private servers
419
+ // (lib/panel.mjs sweep, which signals nothing and removes only what it can prove is dead).
420
+ guard.attempt(() => { if (!ended) { try { effects.sweep({ env }); } catch { /* nothing swept */ } } });
241
421
  const end = await guard.done;
242
422
  if (escTimer !== null) clearTimer(escTimer);
423
+ if (throughTimer !== null) clearTimer(throughTimer);
243
424
  // After the alternate screen is left, so the message stays on the screen the user returns to.
425
+ // One line per change still running, to a terminal or a file only; the status never depends on it.
426
+ const running = reader.changes?.() ?? [];
427
+ if (running.length && effects.tellable(stderr)) {
428
+ try { stderr.write(running.map(({ label }) => `${ACT_WORDS.leaving(label?.verb ?? "change", displayLine(label?.name) ?? "an instance")}\n`).join("")); } catch { /* nothing to tell it to */ }
429
+ }
244
430
  if (end.error !== undefined) stderr.write(`oats: \`oats tui\` stopped on an internal error; the terminal was restored\n${errorLines(end.error).map((line) => ` ${line}\n`).join("")}`);
245
431
  return end.status;
246
432
  }