sumo-agents 0.3.0 → 0.5.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 (52) hide show
  1. package/AGENTS.md +8 -6
  2. package/CHANGELOG.md +155 -0
  3. package/README.md +82 -19
  4. package/bin/sumo.mjs +13 -2
  5. package/guides/feature.md +2 -1
  6. package/guides/memory.md +6 -4
  7. package/guides/projects.md +1 -1
  8. package/guides/review.md +1 -1
  9. package/package.json +5 -4
  10. package/prompts/dream.md +6 -0
  11. package/spinner.txt +25 -1
  12. package/src/apply.mjs +146 -18
  13. package/src/auth.mjs +32 -5
  14. package/src/card.mjs +39 -2
  15. package/src/catalog.mjs +6 -3
  16. package/src/chat.mjs +289 -89
  17. package/src/cli.mjs +359 -135
  18. package/src/cost.mjs +67 -8
  19. package/src/db.mjs +106 -3
  20. package/src/dream.mjs +445 -19
  21. package/src/editor.mjs +113 -11
  22. package/src/export.mjs +105 -7
  23. package/src/guard.mjs +57 -11
  24. package/src/guides.mjs +5 -4
  25. package/src/herdr.mjs +9 -4
  26. package/src/hooks.mjs +35 -19
  27. package/src/jobs.mjs +118 -39
  28. package/src/jobtools.mjs +6 -4
  29. package/src/keeper.mjs +77 -0
  30. package/src/local-server.mjs +9 -16
  31. package/src/lock.mjs +2 -1
  32. package/src/logs.mjs +165 -0
  33. package/src/loop.mjs +121 -44
  34. package/src/mcp.mjs +72 -16
  35. package/src/memory.mjs +142 -15
  36. package/src/model.mjs +41 -21
  37. package/src/paths.mjs +38 -0
  38. package/src/prime.mjs +19 -31
  39. package/src/projects.mjs +94 -12
  40. package/src/redact.mjs +10 -0
  41. package/src/render.mjs +2 -1
  42. package/src/route.mjs +39 -25
  43. package/src/sandbox.mjs +82 -3
  44. package/src/scan.mjs +35 -1
  45. package/src/scribe.mjs +10 -22
  46. package/src/sessions.mjs +49 -13
  47. package/src/setup.mjs +425 -76
  48. package/src/text.mjs +100 -1
  49. package/src/tools.mjs +258 -21
  50. package/src/tty.mjs +481 -105
  51. package/src/ui.mjs +1205 -276
  52. package/src/verify.mjs +17 -1
package/src/ui.mjs CHANGED
@@ -1,19 +1,22 @@
1
1
  import { Box, render, renderToString, Static, Text, useAnimation, useApp, useBoxMetrics, useInput, usePaste, useStdout, useWindowSize } from 'ink';
2
2
  import { execFile, spawn } from 'node:child_process';
3
- import { closeSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
- import { join } from 'node:path';
5
- import { createElement as h, useEffect, useReducer, useRef } from 'react';
6
- import { compactLine, retryLine, routeLine, routeOf } from './chat.mjs';
3
+ import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
4
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
5
+ import { homedir } from 'node:os';
6
+ import { createContext, createElement as h, useContext, useEffect, useReducer, useRef } from 'react';
7
+ import { compactLine, contextReport, routeLine, routeOf } from './chat.mjs';
8
+ import { contextBand } from './sessions.mjs';
7
9
  import { liveFile } from './jobs.mjs';
8
10
  import { stopReason } from './loop.mjs';
9
- import { compactInput, INPUT_SHOWN } from './mcp.mjs';
11
+ import { INPUT_SHOWN } from './mcp.mjs';
10
12
  import { paths } from './paths.mjs';
13
+ import { scratchDir } from './projects.mjs';
11
14
  import { redact } from './redact.mjs';
12
15
  import { elapsed } from './text.mjs';
13
- import { editor, keysOf, matchFiles, menuOf, paste, press, under } from './editor.mjs';
16
+ import { cleanPaste, editor, keysOf, matchFiles, menuOf, paste, press, under } from './editor.mjs';
14
17
  import { clipboardImage, copyText, droppedImages } from './images.mjs';
15
- import { BASH_TOOL, DELEGATE_TOOL, EDITOR_TOOL } from './tools.mjs';
16
- import { colourEnabled, createRenderer, flow, fold, logoLines, messageAt, pathFrom, pickMessage, renderBlock, safeForTerminal, spinnerMessages, styles, sunset, tilde, toolView, transcript, untab, wrap } from './tty.mjs';
18
+ import { ASK_TOOL, BASH_TOOL, DELEGATE_TOOL, EDITOR_TOOL } from './tools.mjs';
19
+ import { colourEnabled, createRenderer, explained, fold, glyphs, GUTTER, inline, linked, logoLines, markdownOf, messageAt, OUT_AT, pathFrom, pickMessage, renderBlock, safeForTerminal, spinnerMessages, styles, TEXT_AT, tilde, toolView, transcript, unnamed, untab, VERSION, withoutColourCodes, withSpan, wrap } from './tty.mjs';
17
20
 
18
21
  /**
19
22
  * The chat on a real terminal. What is finished scrolls away above — what
@@ -26,9 +29,10 @@ import { colourEnabled, createRenderer, flow, fold, logoLines, messageAt, pathFr
26
29
  * says who it is — each call on one line, its output behind Ctrl-O — and a
27
30
  * line starting with @ is said to it. An image pasted with Ctrl-V, or a file
28
31
  * dropped on the box, stands in it as `[Image #n]` and goes with the message
29
- * that names it. The chat opens on its name in blocks, in a sunset; while the
30
- * conversation is short the box stands at the foot of the window, and until the
31
- * first message is sent the logo stands faint in the room above it. A command
32
+ * that names it. Every row is set in a ledger: named on the left in a word —
33
+ * you, sumo, read, edit, run, ask — its state beside the name, its words after.
34
+ * While the conversation is short the box stands at the foot of the window, and
35
+ * until the first message is sent the logo stands faint in the room above it. A command
32
36
  * shows what it prints while it runs; a message sent while the model works is
33
37
  * read with its next request; a turn ends on a line that says how long it took,
34
38
  * what it changed and what it cost, and — when the window is not the one in
@@ -39,10 +43,14 @@ import { colourEnabled, createRenderer, flow, fold, logoLines, messageAt, pathFr
39
43
  * is drawing; the session in chat.mjs does the work.
40
44
  */
41
45
 
42
- const ACCENT = '#d77757';
46
+ /** The chat's one colour of its own: the terminal's cyan, so the theme the user chose decides its shade, light or dark. */
47
+ const ACCENT = 'cyan';
48
+ /** The marks the screen draws with: plain ones (`chat.screen plain`) for a screen reader. Every component reads them here. */
49
+ const Marks = createContext(glyphs(false));
50
+ const useMarks = () => useContext(Marks);
43
51
  /** The name at the top of the chat, two rows of blocks. */
44
- const WORDMARK = ['█▀▀ █ █ █▀▄▀█ █▀█', '▄▄█ █▄█ █ ▀ █ █▄█'];
45
- const FLOW_STEP_MS = 100;
52
+ /** How often the spinner on the working line turns: a line with one cell changed, not every character in a colour of its own. */
53
+ const SPIN_MS = 100;
46
54
  const TONES = { plain: {}, dim: { dimColor: true }, error: { color: 'red' }, add: { color: 'green' }, del: { color: 'red' }, ask: { color: 'yellow' } };
47
55
  const LEAVE_WINDOW_MS = 2000;
48
56
  const NOTICE_MS = 3000;
@@ -65,6 +73,25 @@ const TITLE_BACK = '\x1b[23;0t';
65
73
  */
66
74
  const SCREEN_ASIDE = '\x1b[?1049h';
67
75
  const SCREEN_BACK = '\x1b[?1049l';
76
+ /**
77
+ * The tab's own progress mark (OSC 9;4): busy while the chat works, gone when it is done. Only where the terminal is known to
78
+ * draw it — elsewhere the same sequence is a notification, or text.
79
+ */
80
+ const PROGRESS_BUSY = '\x1b]9;4;3;0\x07';
81
+ const PROGRESS_DONE = '\x1b]9;4;0;0\x07';
82
+ function showsProgress(env = process.env) {
83
+ if (env.TMUX || env.STY) return false;
84
+ if (env.WT_SESSION || env.ConEmuANSI === 'ON' || env.TERM_PROGRAM === 'ghostty') return true;
85
+ if (env.TERM_PROGRAM === 'iTerm.app') {
86
+ const [major, minor] = String(env.TERM_PROGRAM_VERSION ?? '').split('.').map(Number);
87
+ return major > 3 || (major === 3 && minor >= 6);
88
+ }
89
+ return false;
90
+ }
91
+
92
+ /** How long Ctrl-Z waits to be stopped before it takes it that nothing will stop it. */
93
+ const SUSPEND_CHECK_MS = 300;
94
+
68
95
  /** Longer than Ink waits for the terminal to say how its keyboard speaks (200 ms): see `runUi`. */
69
96
  const KITTY_WAIT_MS = 300;
70
97
  /** A turn at least this long ends on a bell when the window is not in front, and on its footer whatever it did. */
@@ -78,6 +105,9 @@ const LIVE_DRAW_MS = 100;
78
105
  /** The most rows of the box, and of a message once sent, that are drawn: a long paste must not push the screen past the window. */
79
106
  const INPUT_ROWS = 10;
80
107
  const ECHO_LINES = 10;
108
+ /** A paste longer than this stands in the box as a marker — `[Pasted text #1 +120 lines]` — and goes whole with the message. */
109
+ const PASTE_LINES = 12;
110
+ const PASTE_CHARS = 2000;
81
111
  /** How long the list of a project's files is good for, while a file is being named with `@`. */
82
112
  const FILES_FRESH_MS = 15_000;
83
113
  /** How many of a resumed session's turns are drawn again: enough to see where it stopped. */
@@ -148,6 +178,18 @@ export function replayOf(messages, turns = REPLAY_TURNS) {
148
178
  return [{ kind: 'note', text: `${hidden} earlier turn${hidden === 1 ? '' : 's'} not drawn again — the model has all of them` }, ...entries.slice(starts.at(-turns))];
149
179
  }
150
180
 
181
+ /**
182
+ * Where `/export` writes: the path given — from the project, or from home with `~` — and into a folder given, a file of its
183
+ * own; with none, the home's exports folder, named by the day and the session.
184
+ */
185
+ function exportPath(given, cwd, sessionId = null) {
186
+ const named = `${new Date().toISOString().slice(0, 10)}-${String(sessionId ?? 'session').slice(0, 8)}.md`;
187
+ if (!given) return join(paths().home, 'exports', named);
188
+ const path = given.replace(/^~(?=$|\/)/, homedir());
189
+ const full = isAbsolute(path) ? path : resolve(cwd, path);
190
+ return existsSync(full) && statSync(full).isDirectory() ? join(full, named) : full;
191
+ }
192
+
151
193
  /** What Up recalls across sessions: the last lines typed, one a line, in the home. */
152
194
  const HISTORY_KEPT = 50;
153
195
  const historyFile = () => join(paths().home, 'history');
@@ -170,6 +212,8 @@ function keepHistory(line) {
170
212
  try {
171
213
  mkdirSync(paths().home, { recursive: true, mode: 0o700 });
172
214
  writeFileSync(historyFile(), `${lines.slice(-HISTORY_KEPT).join('\n')}\n`, { mode: 0o600 });
215
+ // The mode is given only to a file being made: one made before it was set is made private here.
216
+ chmodSync(historyFile(), 0o600);
173
217
  } catch {
174
218
  // Nowhere to keep it: the line is still sent.
175
219
  }
@@ -178,54 +222,165 @@ function keepHistory(line) {
178
222
  const thousands = (n) => (n >= 1000 ? `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)}k` : String(n));
179
223
 
180
224
  /**
181
- * The lines under a call: what came back, the first of them with the mark. Folded to `columns` here, by the same count the
182
- * replies are folded by, so a line too long for the window goes on under itself — not under the mark, and not past the edge.
225
+ * A request being sent again, for the scroll: why, in the words a known failure is said in — not what to do about it,
226
+ * since it is being done — and which try this is. One it does not know is said as it came.
183
227
  */
184
- const linesUnder = (lines, columns) =>
185
- lines
186
- .flatMap((line) => fold(untab(line.text), Math.max(20, columns - 6)).map((text) => ({ ...line, text })))
187
- .map((line, i) => h(Text, { key: i, ...TONES[line.tone], wrap: 'truncate' }, `${i === 0 ? ' ⎿ ' : ' '}${line.text}`));
228
+ const retryWhy = (reason) => {
229
+ const said = explained(reason);
230
+ return said.detail ? said.text.replace(/^error: /, '').split(' — ')[0] : String(reason ?? '').replace(/\s+/g, ' ').trim().slice(0, 160);
231
+ };
232
+ const retryNote = ({ attempt, limit, reason }) => `${retryWhy(reason)} · retrying (${attempt} of ${limit})`;
233
+
234
+ /**
235
+ * Reverse video, whatever the colour: NO_COLOR asks for no colour, and chalk, told so, drops every style with it — the
236
+ * cursor in the box, and the part of an edit that changed, would be gone. These are not colour, and are kept.
237
+ */
238
+ const reverse = (text) => `\x1b[7m${text}\x1b[27m`;
239
+
240
+ /**
241
+ * The lines under a call: what came back, under the words of the step. Folded to `columns` here, by the same count the
242
+ * replies are folded by, so a line too long for the window goes on under itself — not under the gutter, and not past the
243
+ * edge. With `max`, at most that many rows: the last says how many lines were folded away — a line partly shown is shown.
244
+ * `at` is the column they start on: what came back stands under the step's words, a note of the chat's own under its words.
245
+ */
246
+ const linesUnder = (lines, columns, s = styles(false), max = null, at = OUT_AT) => {
247
+ const rows = [];
248
+ let reached = 0;
249
+ const room = Math.max(20, columns - at - 1);
250
+ // Folded only as far as the budget needs: a long edit is not laid out whole to show its top.
251
+ while (reached < lines.length && (max === null || rows.length <= max)) {
252
+ const line = lines[reached];
253
+ // An address in what came back opens on a click, whole, however the line is folded. The part of a diff's line that changed is in reverse video.
254
+ const text = line.span ? withSpan(line, { ...s, inverse: reverse }) : linked(untab(line.text), s);
255
+ // A numbered line — a diff's, a file's — and an item of a list go on under their own text, not under the number or the bullet.
256
+ const hang = /^\s*(?:\d+(?: [-+ ] | {2,})\s*|[•*-] |\d+[.)] )/.exec(text)?.[0].length ?? 0;
257
+ rows.push(...fold(text, room, ' '.repeat(Math.min(hang, Math.floor(room / 2)))).map((row) => ({ ...line, text: row, from: reached })));
258
+ reached++;
259
+ }
260
+ let kept = rows;
261
+ if (max !== null && (rows.length > max || reached < lines.length)) {
262
+ kept = rows.slice(0, max - 1);
263
+ // A line cut short is counted with the ones never reached: the fold says what is not there to read.
264
+ const whole = (kept.at(-1)?.from ?? -1) + (rows[kept.length]?.from === kept.at(-1)?.from ? 0 : 1);
265
+ const folded = lines.length - whole;
266
+ kept.push({ text: `… +${folded} line${folded === 1 ? '' : 's'}`, tone: 'dim' });
267
+ }
268
+ const indent = ' '.repeat(at);
269
+ return kept.map((line, i) => h(Text, { key: i, ...TONES[line.tone], wrap: 'truncate' }, `${indent}${line.text}`));
270
+ };
188
271
 
189
272
  /**
190
273
  * The last lines a running command has printed, as the screen may show them: without secrets or control characters, a
191
274
  * progress bar as its latest state. What was kept may begin mid-line — or mid-secret — so its first line is not shown.
192
275
  */
193
276
  function lastLines({ out, cut }) {
194
- const lines = safeForTerminal(redact(out).text).split(/\r?\n|\r/);
277
+ const lines = withoutColourCodes(safeForTerminal(redact(out).text)).split(/\r?\n|\r/);
195
278
  return (cut ? lines.slice(1) : lines).map((l) => untab(l).trimEnd()).filter(Boolean).slice(-LIVE_LINES);
196
279
  }
197
280
 
198
- /** A command that is running: for how long, and the last of what it has printed so far. */
199
- function Running({ live }) {
200
- // Drawn again more often than the clock it shows turns over, so a second is not skipped by a tick that came just short of it.
201
- useAnimation({ interval: 250 });
202
- const ran = live ? Date.now() - live.since : 0;
281
+ /** The last of what a running command has printed so far, faint, under its words: how long it has run is on the step's own row. */
282
+ const runningLines = (live) => (live ? lastLines(live) : []).map((line, i) => h(Text, { key: `live-${i}`, dimColor: true, wrap: 'truncate' }, `${' '.repeat(OUT_AT)}${line}`));
283
+
284
+ /**
285
+ * A row of the ledger: its name set right in the gutter, its state in the column beside it, its words from there on —
286
+ * going on under themselves, never under the name. `tone` colours the name, `markTone` the state.
287
+ */
288
+ function Row({ label = '', tone = DIM, mark = ' ', markTone = null, columns, marginTop = 0, children }) {
203
289
  return h(
204
290
  Box,
205
- { flexDirection: 'column' },
206
- h(Text, { dimColor: true }, ` ⎿ Running…${ran >= 1000 ? ` ${elapsed(ran)}` : ''}`),
207
- ...(live ? lastLines(live) : []).map((line, i) => h(Text, { key: i, dimColor: true, wrap: 'truncate' }, ` ${line}`)),
291
+ { marginTop },
292
+ h(Box, { flexShrink: 0, width: TEXT_AT }, h(Text, null, h(Text, tone, String(label).slice(0, GUTTER).padStart(GUTTER)), ' ', h(Text, markTone, mark), ' ')),
293
+ // A width of its own: a box in a row is never made narrower than its longest word, and a command can be one long word.
294
+ h(Box, { flexDirection: 'column', flexShrink: 1, width: Math.max(10, columns - TEXT_AT) }, ...[children].flat()),
208
295
  );
209
296
  }
297
+ const DIM = { dimColor: true };
298
+ /** Words for a row of the ledger, folded to what is left of the window after the gutter, each line on its own. */
299
+ const folded = (text, columns) =>
300
+ String(text)
301
+ .split('\n')
302
+ .map((line) => wrap(line, Math.max(10, columns - TEXT_AT - 1)))
303
+ .join('\n');
210
304
 
211
- /** A tool call: what ran, and under it what came back — or, while it runs, the jobs it started, or what it prints. */
212
- function Tool({ view, failed = false, running = false, jobs = [], live = null, columns }) {
305
+ /**
306
+ * What a call ran, as the rows it takes after its name: what it was given, how much an edit added and took away, how
307
+ * long it ran — folded here, at the spaces, so a row that goes on starts at the words' margin, not with the space it broke at.
308
+ */
309
+ function titleRows(view, took, s, width) {
310
+ const stat = view.stat ? ` ${s.green(`+${view.stat.added}`)} ${s.red(`−${view.stat.removed}`)}` : '';
311
+ const time = took >= TOOK_SHOWN_MS ? s.dim(` · ${elapsed(took)}`) : '';
312
+ return untab(`${view.detail}${stat}${time}`)
313
+ .split('\n')
314
+ .flatMap((line) => wrap(line, width).split('\n'));
315
+ }
316
+
317
+ /**
318
+ * A step: its name in the gutter — read, edit, run — what it was given, and under it what came back; or, while it runs,
319
+ * the jobs it started or the last of what it prints. Its state stands beside the name: ✗ failed, • at work (with its
320
+ * clock), ? waiting on the user. `tight` sets it straight under the step before it: steps in a row are one list.
321
+ */
322
+ function Tool(props) {
323
+ const g = useMarks();
324
+ const step = stepOf(props, g);
325
+ // At work, the row is drawn again for its clock, a little more often than it turns over so a second is never skipped.
326
+ useAnimation({ interval: 250, isActive: step.ticking });
327
+ const { view, failed = false, running = false, tight = false, columns } = props;
213
328
  return h(
214
329
  Box,
215
- { flexDirection: 'column', marginTop: 1 },
216
- // The mark stands apart from the words, so a command that wraps, or has lines of its own, goes on under them, not under it.
217
- h(
218
- Box,
219
- null,
220
- h(Box, { flexShrink: 0 }, h(Text, { color: running ? undefined : failed ? 'red' : 'green', dimColor: running }, '⏺ ')),
221
- h(Box, { flexShrink: 1 }, h(Text, null, h(Text, { bold: true }, view.title), `(${untab(view.detail)})`, view.stat ? h(Text, null, ' ', h(Text, { color: 'green' }, `+${view.stat.added}`), ' ', h(Text, { color: 'red' }, `−${view.stat.removed}`)) : null)),
222
- ),
223
- running && jobs.length === 0 ? h(Running, { live }) : null,
224
- ...jobs.map(([id, job]) => h(JobAtWork, { key: id, id, job })),
225
- ...linesUnder(view.lines, columns),
330
+ { flexDirection: 'column', marginTop: tight ? 0 : 1 },
331
+ // A failure has a mark of its own and its name in red: the colour alone says nothing to someone who cannot see it.
332
+ h(Row, { label: view.title, tone: failed && !running ? { color: 'red' } : DIM, mark: step.mark, markTone: step.markTone, columns }, ...step.title.map((row, i) => h(Text, { key: i }, row))),
333
+ step.note ? h(Text, { dimColor: true }, `${' '.repeat(OUT_AT)}${step.note}`) : null,
334
+ ...step.live,
335
+ ...step.jobs.map(([id, job]) => h(JobAtWork, { key: id, id, job })),
336
+ ...step.under,
226
337
  );
227
338
  }
228
339
 
340
+ /**
341
+ * What a step draws, row by row — its title folded, a note, what a command prints, its jobs, what came back — so the step
342
+ * (`Tool`) and the count of rows the work above a question takes are one and the same.
343
+ */
344
+ function stepOf({ view, failed = false, running = false, waiting = false, jobs = [], live = null, took = 0, since = 0, columns, s = styles(false) }, g) {
345
+ const plain = g === glyphs(true);
346
+ // A question put to the user is not running anything: it waits on them, and says so.
347
+ // A call held for the user's word runs nothing either: the panel under the work says it waits, and nothing here says it again.
348
+ // A delegation has no job yet while the router picks the model and effort it runs on.
349
+ const asking = running && view.title === 'asked' && !waiting;
350
+ // Only what runs has a clock: not a call waiting on the user, nor one whose jobs keep their own. Plain, for a screen
351
+ // reader, there is none: the row is drawn again for what the command prints, not for the time.
352
+ const ticking = running && !plain && !waiting && !asking && jobs.length === 0;
353
+ const ran = ticking && since > 0 ? Date.now() - since : running ? 0 : took;
354
+ const width = Math.max(10, columns - TEXT_AT);
355
+ // Waiting on the user, the step is one row: the panel under it shows what would run, whole, and the window's rows are its.
356
+ const rows = titleRows(view, ran, s, width);
357
+ const title = waiting && rows.length > 1 ? [`${rows[0].slice(0, Math.max(1, width - 2))} …`] : rows;
358
+ return {
359
+ ticking,
360
+ note: asking ? 'waiting for your answer' : running && !waiting && jobs.length === 0 && view.title === 'job' ? 'picking the model and effort…' : null,
361
+ mark: waiting || asking ? g.ask : running ? g.live : failed ? g.fail : ' ',
362
+ markTone: waiting || asking ? { color: 'yellow' } : running ? { color: ACCENT } : failed ? { color: 'red' } : null,
363
+ title,
364
+ live: running && !waiting && jobs.length === 0 ? runningLines(live) : [],
365
+ jobs,
366
+ under: linesUnder(view.lines, columns, s, view.rows ?? null),
367
+ };
368
+ }
369
+
370
+ /** The rows a step takes on the screen: the blank one over it, unless it is tight under the step before. */
371
+ const stepRowCount = (props, g) => {
372
+ const step = stepOf(props, g);
373
+ return (props.tight ? 0 : 1) + step.title.length + (step.note ? 1 : 0) + step.live.length + step.jobs.length + step.under.length;
374
+ };
375
+
376
+ /** Steps follow one another without a blank row between them: after a step, or what a command of the user's printed. */
377
+ const STEP_KINDS = new Set(['tool', 'output']);
378
+
379
+ /** A call that took at least this long says how long, beside what ran. */
380
+ const TOOK_SHOWN_MS = 1000;
381
+ /** Thought for less than this, the line that says so would say nothing. */
382
+ const THOUGHT_SHOWN_MS = 1000;
383
+
229
384
  /** The rows the screen gives to what the model is thinking. */
230
385
  const THOUGHT_ROWS = 3;
231
386
 
@@ -246,33 +401,36 @@ const TITLE_CHARS = 32;
246
401
 
247
402
  /**
248
403
  * A job at work, in one line: how long, how many calls, and that it is working — what it runs and thinks is in its record,
249
- * a step and Enter away, not here. Under the call that waits for it; or — at work in the background, with no call standing
250
- * over it — in a row of its own under the box, with who it is, marked when it is the one stepped on (`picked`) or the one
251
- * whose record is open.
404
+ * a step and Enter away, not here. Under the call that waits for it, under the call's words; or — at work in the
405
+ * background, with no call standing over it — in a row of the ledger under the box, named by its id, marked when it is
406
+ * the one stepped on (`picked`) or the one whose record is open.
252
407
  */
253
408
  function JobAtWork({ id, job, alone = false, picked = false, open = false }) {
254
- useAnimation({ interval: 1000 });
409
+ // Plain, the row says what the job has done, not for how long: a clock would have it read out every second.
410
+ const g = useMarks();
411
+ const plain = g === glyphs(true);
412
+ useAnimation({ interval: 1000, isActive: !plain });
255
413
  const calls = `${job.calls} tool call${job.calls === 1 ? '' : 's'}`;
256
- const mark = alone ? (picked ? ' ❯ ' : ' ⏺ ') : ' ⎿ ';
257
- const who = alone ? ` ${job.agent} — ${job.title.length > TITLE_CHARS ? `${job.title.slice(0, TITLE_CHARS - 1)}…` : job.title}` : '';
258
- const lead = `j${id}${who} · ${elapsed(Date.now() - job.since)} · ${calls} · `;
259
- return h(
260
- Text,
261
- { wrap: 'truncate' },
262
- h(Text, picked || open ? { color: ACCENT } : { dimColor: true }, mark),
263
- h(Text, { dimColor: !picked }, lead),
264
- h(Text, { dimColor: true }, 'working'),
265
- );
414
+ // Under the call that started it the title is the call's own: the row says who works on it, on what, and where to follow it.
415
+ const who = alone ? `${job.agent} — ${job.title.length > TITLE_CHARS ? `${job.title.slice(0, TITLE_CHARS - 1)}…` : job.title}` : `j${id} ${job.agent} · ${job.route}`;
416
+ const lead = `${who} · ${plain ? '' : `${elapsed(Date.now() - job.since)} · `}${calls} · `;
417
+ const rest = [h(Text, { key: 'lead', dimColor: !picked }, lead), h(Text, { key: 'working', dimColor: true }, 'working'), !alone && job.where ? h(Text, { key: 'where', dimColor: true }, ` · ${job.where.replace(/^follow it: /, '')}`) : null];
418
+ if (!alone) return h(Text, { wrap: 'truncate' }, ' '.repeat(OUT_AT), ...rest);
419
+ return h(Text, { wrap: 'truncate' }, h(Text, picked || open ? { bold: true } : DIM, `j${id}`.padStart(GUTTER)), ' ', h(Text, { color: ACCENT }, picked ? g.pick : ' '), ' ', ...rest);
266
420
  }
267
421
 
268
422
  /** The chat itself, as the first of the rows under the box: the place Enter comes back to from a job's record. */
269
423
  const MAIN = 'main';
270
424
 
271
- /** The chat's own row, over the jobs it delegated: marked when it is the one stepped on (`picked`), or the one on the screen (`shown`). */
425
+ /** The chat's own row, over the jobs it delegated: marked when it is the one stepped on (`picked`), named in full weight when it is the one on the screen (`shown`). */
272
426
  function MainAtWork({ working, picked = false, shown = false }) {
273
- return h(Text, { wrap: 'truncate' }, h(Text, picked || shown ? { color: ACCENT } : { dimColor: true }, picked ? ' ❯ ' : ' ⏺ '), h(Text, { dimColor: !picked }, 'main · '), h(Text, { dimColor: true }, working ? 'working' : 'idle'));
427
+ const g = useMarks();
428
+ return h(Text, { wrap: 'truncate' }, h(Text, picked || shown ? { bold: true } : DIM, MAIN.padStart(GUTTER)), ' ', h(Text, { color: ACCENT }, picked ? g.pick : ' '), ' ', h(Text, { dimColor: true }, working ? 'working' : 'idle'));
274
429
  }
275
430
 
431
+ /** A line of a job's record, which is written with the full marks, in the marks this screen draws with. */
432
+ const inMarks = (line, g) => (g.fail === '✗' ? line : line.replaceAll('✗', g.fail));
433
+
276
434
  /** What a job at work has written down so far, as the screen may show it: its lines, under the one that says who it is. None where there is no record yet. */
277
435
  function recordLines(id) {
278
436
  try {
@@ -285,129 +443,384 @@ function recordLines(id) {
285
443
  /** The rows of the window an open job's record may take: the turn's own work, the box and the rows under it need the rest. */
286
444
  const openRows = (rows) => Math.max(3, Math.min(rows - 24, Math.floor(rows / 2)));
287
445
 
446
+ /**
447
+ * Which lines of a record are what came back from a step: the unnamed lines after a step's row, up to the next named row.
448
+ * What the job says — its reply, a list or code in it set in as deep — follows a row named sumo, and keeps full weight.
449
+ */
450
+ export function underSteps(lines) {
451
+ let step = false;
452
+ return lines.map((line) => {
453
+ const name = line.slice(0, GUTTER).trim();
454
+ if (name) step = name !== 'sumo';
455
+ return !name && step;
456
+ });
457
+ }
458
+
288
459
  /**
289
460
  * A job opened from under the box: who it is, and the end of what it has written down — each call with the top of what
290
461
  * came back, and what it said — read again as its clock ticks. It is the record `sumo job watch` follows; Ctrl-O has all of it.
291
462
  */
292
- function JobOpen({ id, job, rows }) {
463
+ function JobOpen({ id, job, rows, columns }) {
293
464
  useAnimation({ interval: 1000 });
465
+ const g = useMarks();
294
466
  const all = recordLines(id);
467
+ const faint = underSteps(all);
295
468
  const seen = all.slice(-openRows(rows));
296
469
  const above = all.length - seen.length;
470
+ const pad = ' '.repeat(TEXT_AT);
297
471
  return h(
298
472
  Box,
299
473
  { flexDirection: 'column', marginTop: 1 },
300
- h(Text, { wrap: 'truncate' }, h(Text, { color: ACCENT }, '⏺ '), h(Text, { bold: true }, `j${id}`), ` ${job.agent} · ${job.route} — ${job.title}`),
301
- above > 0 ? h(Text, { dimColor: true }, ` … +${above} line${above === 1 ? '' : 's'}`) : null,
302
- all.length === 0 ? h(Text, { dimColor: true }, ' nothing done yet') : null,
303
- ...seen.map((line, i) => h(Text, { key: i, dimColor: /^\s*⎿/.test(line), wrap: 'truncate' }, untab(line) || ' ')),
474
+ h(Row, { label: `j${id}`, tone: { bold: true }, columns }, h(Text, { wrap: 'truncate' }, `${job.agent} · ${job.route} — ${job.title}`)),
475
+ above > 0 ? h(Text, { dimColor: true }, `${pad}… +${above} line${above === 1 ? '' : 's'}`) : null,
476
+ all.length === 0 ? h(Text, { dimColor: true }, `${pad}nothing done yet`) : null,
477
+ ...seen.map((line, i) => h(Text, { key: i, dimColor: faint[all.length - seen.length + i], wrap: 'truncate' }, inMarks(untab(line), g) || ' ')),
304
478
  );
305
479
  }
306
480
 
307
481
  /** The most of a call's input the question shows in full; past it, the cut is said. A recipient or a body hidden past the cut is one the user never approved. */
308
482
  const ASK_INPUT_MAX = 4_000;
309
483
 
484
+ /**
485
+ * What a question shows, as plain text: no escape of any kind, colours included — a conceal code (`ESC[8m`) would hide
486
+ * the very part of a command or a path the user is asked to judge. What draws the work keeps its colours; this does not.
487
+ */
488
+ const asText = (text) => safeForTerminal(String(text ?? '').replace(/\x1b/g, '␛').replace(/[\x00-\x08\x0b-\x1f\x7f]/g, (c) => (c === '\x7f' ? '^?' : `^${String.fromCharCode(c.charCodeAt(0) + 64)}`)));
489
+
490
+ /**
491
+ * A change to a file outside the project, as the question shows it: the file and the command, then what is taken out (-)
492
+ * and put in (+). The file is where the write lands, named as the call above it names it: from the project when it is in
493
+ * it (a guarded one can be), else whole — one file, one spelling.
494
+ */
495
+ function editLines(ask, cwd = null) {
496
+ const input = ask.input ?? {};
497
+ const lines = (text, mark) => asText(text).replace(/\n$/, '').split('\n').map((l) => `${mark} ${l}`);
498
+ // The head is the model's words and a path it chose: drawn as text, never as what the terminal would do with an escape.
499
+ // What it does is said in words, not by the editor's own command.
500
+ const verb = { str_replace: 'change', create: 'create', insert: 'insert into' }[input.command] ?? input.command;
501
+ const head = asText(`${verb} ${pathFrom(ask.path, cwd)}${input.command === 'insert' ? ` after line ${input.insert_line ?? 0}` : ''}`);
502
+ if (input.command === 'create') return [head, ...lines(input.file_text, '+')];
503
+ if (input.command === 'insert') return [head, ...lines(input.insert_text ?? input.new_str, '+')];
504
+ return [head, ...lines(input.old_str, '-'), ...lines(input.new_str, '+')];
505
+ }
506
+
507
+ /**
508
+ * The keys that answer a call waiting on the user, and what each answers. A run outside the sandbox is this one run or
509
+ * none; a guarded file is changed this once or not; a file outside the project can be opened for the session, alone or
510
+ * with its directory; an MCP call can be allowed for good.
511
+ */
512
+ function answersTo(ask) {
513
+ // Every kind can be refused with the user's words: r opens a line for them, and the model reads them as what to do instead.
514
+ if (ask.unsandboxed) return 'y yes · n no · r no, say why';
515
+ if (ask.guarded) return 'y once · n no · r no, say why';
516
+ // The folder by its name: the path just above it in the question is the file's, in that folder.
517
+ if (ask.path) return `y once · a this file, session${ask.directory ? ` · d all of ${asText(basename(ask.directory))}/, session` : ''} · n no · r no, say why`;
518
+ return 'y once · a always · n no · r no, say why';
519
+ }
520
+ const KEY_ANSWERS = { y: 'once', a: 'always', d: 'directory', n: 'no', r: 'why' };
521
+ /** The answer a key gives to a waiting call, or undefined when the key answers nothing on it. */
522
+ const answerOf = (ask, key) => (answersTo(ask).split(' · ').some((said) => said.startsWith(`${key} `)) ? KEY_ANSWERS[key] : undefined);
523
+ /** What the panel says when a key answers nothing: each key and what it does, Esc's too. */
524
+ const explainKeys = (ask, aside = false) =>
525
+ `${answersTo(ask)
526
+ .split(' · ')
527
+ .map((said) => ({ 'y yes': 'y runs it once outside the sandbox', 'y once': ask.path ? 'y changes it once' : 'y allows it once', 'a always': 'a always', 'a this file, session': 'a this file, session', d: `d all of ${asText(basename(ask.directory ?? ''))}/, session`, 'n no': 'n refuses it', 'r no, say why': 'r with why' })[said.startsWith('d ') ? 'd' : said] ?? said)
528
+ .join(' · ')} · esc ${aside ? 'refuses it' : 'interrupts the turn'}`;
529
+
530
+ /** How long a run of spaces may be before the question counts it instead of drawing it: blank rows hide what follows them. */
531
+ const SPACES_COUNTED = 16;
532
+ /** A long run of spaces or tabs in what would run, as a count the eye cannot miss: `echo ok ⟨200 spaces⟩ ; curl …`. */
533
+ const spacesCounted = (line) => line.replace(new RegExp(`[ \\t]{${SPACES_COUNTED},}`, 'g'), (run) => ` ⟨${run.length} spaces⟩ `);
534
+
310
535
  /** A call waiting on the user's word: who asks, what would run with what — the whole input, not its first line — and the keys that answer. */
311
- function Ask({ ask, aside = false }) {
536
+ function Ask({ ask, aside = false, waiting = 1, why = null, explain = false, columns, cwd = null, rows = null }) {
312
537
  const who = ask.job ? `j${ask.job}: ` : '';
313
538
  // A command the sandbox blocked is asked as itself: the command, to run once outside the sandbox — yes or no, never always.
314
- const command = ask.unsandboxed ? safeForTerminal(String(ask.input?.command ?? '')) : null;
315
- const whole = command ?? JSON.stringify(ask.input ?? {});
316
- // Short enough for the line, it is on the line; longer, it is laid out under it, every field whole, up to the cut.
539
+ const command = ask.unsandboxed ? asText(ask.input?.command) : null;
540
+ // A change outside the project, or to a guarded file, is asked as the change: once; outside and not guarded, this file or its directory for the session.
541
+ const edit = ask.path ? editLines(ask, cwd) : null;
542
+ const whole = command ?? edit?.join('\n') ?? JSON.stringify(ask.input ?? {});
543
+ // Short enough for a line, it is the one line; longer, it is laid out, every field whole, up to the cut.
317
544
  const short = whole.length <= INPUT_SHOWN && !whole.includes('\n');
318
- const laid = short ? [] : command !== null ? command.split('\n') : JSON.stringify(ask.input ?? {}, null, 2).split('\n');
545
+ const laid = short ? [whole] : command !== null ? command.split('\n') : edit ?? JSON.stringify(ask.input ?? {}, null, 2).split('\n');
546
+ // Up to the cap, every character: a line longer than what is left is shown as far as it goes, and what the cap left out
547
+ // is counted in characters — a single line can hold what matters past any count of lines.
319
548
  const kept = [];
320
549
  let size = 0;
550
+ let unshown = 0;
321
551
  for (const line of laid) {
322
- if (size + line.length > ASK_INPUT_MAX) break;
323
- kept.push(line);
324
- size += line.length + 1;
552
+ const room = ASK_INPUT_MAX - size;
553
+ if (room <= 0) unshown += line.length + 1;
554
+ else if (line.length > room) {
555
+ kept.push(line.slice(0, room));
556
+ unshown += line.length - room;
557
+ size = ASK_INPUT_MAX;
558
+ } else {
559
+ kept.push(line);
560
+ size += line.length + 1;
561
+ }
325
562
  }
326
- const cut = laid.length - kept.length;
563
+ // A server names its own tools: the title draws them as text, as it draws the input.
564
+ const title = asText(command !== null ? `${who}Run this once outside the sandbox?` : ask.guarded ? `${who}Change this guarded file? ${ask.guarded}` : edit ? `${who}Change this file outside the project?` : `${who}Allow ${ask.server} · ${ask.tool}?`);
327
565
  // Esc stops the turn the call is part of; for a job at work in the background there is no such turn, and Esc refuses the call.
566
+ // Several jobs can ask at once: the ones behind this are counted, so none waits unseen.
567
+ // Saying why, the keys are the line's: Enter refuses with the words, Esc goes back to the question.
568
+ // A key that answers nothing has every key explained here, in the panel's own colour, where nothing is cut to fit.
569
+ // Esc is named as the working line names it, wherever it stops the turn.
570
+ const keys = why !== null ? `enter refuses with this · esc back to the question${waiting > 1 ? ` · ${waiting - 1} more waiting` : ''}` : explain ? `${explainKeys(ask, aside)}${waiting > 1 ? ` · ${waiting - 1} more waiting` : ''}` : `${answersTo(ask)} · esc ${aside ? 'no' : 'to interrupt'}${waiting > 1 ? ` · ${waiting - 1} more waiting` : ''}`;
571
+ // A panel of its own, set apart from the work: named `ask` in yellow, and a yellow bar down the state column beside all
572
+ // it asks about — what would run, whole, and the keys that answer — so where the question ends is never in doubt.
573
+ // Plain, it has no bar: a frame is read out as a row of lines.
574
+ const g = useMarks();
575
+ const framed = g !== glyphs(true);
576
+ const width = Math.max(20, columns - TEXT_AT - 1);
577
+ // Everything in it is folded here, at the width it is drawn at, so the rows it takes are known before it is drawn.
578
+ const titled = folded(title, columns);
579
+ const refused = ask.unsandboxed && ask.blocked ? fold(asText(`the sandbox refused: ${ask.blocked}`), width) : [];
580
+ const input = whole === '{}' ? null : kept.flatMap((line) => fold(spacesCounted(untab(line)) || ' ', Math.max(10, width - 2)));
581
+ const keyed = keyRows(keys, width);
582
+ const reason = why !== null ? fold(`${asText(why)}▌`, Math.max(10, width - 9)) : [];
583
+ const noted = (n) => fold(`… ${n.toLocaleString('en-US')} more character${n === 1 ? '' : 's'} not shown — n, and ask the model for less`, Math.max(10, width - 2));
584
+ // Given the rows it may take (`rows`), what would run is shown as far as they go: a panel taller than the window makes
585
+ // Ink wipe the screen and the scrollback to draw it. What is left out is counted, as the cap's is, and the advice is the same.
586
+ let shown = input ?? [];
587
+ let hidden = unshown;
588
+ if (rows !== null && input) {
589
+ // A key's words longer than a row go on to the next: counted as they would fold, never fewer.
590
+ const keyRowCount = keyed.reduce((sum, row) => sum + wrap(row, width - 1).split('\n').length, 0);
591
+ const fixed = 1 + titled.split('\n').length + refused.length + 2 + (reason.length > 0 ? reason.length + 1 : 0) + keyRowCount;
592
+ if (fixed + input.length + (hidden > 0 ? noted(hidden).length : 0) > rows) {
593
+ const room = Math.max(1, rows - fixed - noted(hidden + whole.length).length);
594
+ hidden += input.slice(room).reduce((sum, row) => sum + row.trim().length, 0);
595
+ shown = input.slice(0, room);
596
+ }
597
+ }
328
598
  return h(
329
599
  Box,
330
- { marginTop: 1, flexDirection: 'column' },
331
- h(Text, { color: 'yellow' }, command !== null ? `⚠ ${who}run this once outside the sandbox?${short ? ` ${whole}` : ''}` : `⚠ ${who}allow ${ask.server} · ${ask.tool}(${short ? whole : '…'})?`),
332
- ...kept.map((line, i) => h(Text, { key: i, color: 'yellow', wrap: 'truncate-end' }, ` ${line}`)),
333
- cut > 0 ? h(Text, { color: 'yellow', dimColor: true }, ` … ${cut} more line${cut === 1 ? '' : 's'} of input not shown — n, and ask the model for less`) : null,
334
- h(Text, { dimColor: true }, ` ${command !== null ? 'y yes · n no' : 'y once · a always · n no'} · esc ${aside ? 'no' : 'stop'}`),
600
+ { marginTop: 1, flexDirection: 'column', width: Math.max(20, columns) },
601
+ h(Row, { label: 'ask', tone: { color: 'yellow', bold: true }, mark: g.ask, markTone: { color: 'yellow', bold: true }, columns }, h(Text, { color: 'yellow', bold: true }, titled)),
602
+ h(
603
+ Box,
604
+ // The bar stands in the state column: the box starts there, as wide as what is left of the window.
605
+ { flexDirection: 'column', ...(framed ? { borderStyle: 'single', borderColor: 'yellow', borderTop: false, borderRight: false, borderBottom: false, marginLeft: GUTTER + 1, paddingLeft: 1, width: Math.max(20, columns - GUTTER - 1) } : { paddingLeft: TEXT_AT, width: Math.max(20, columns) }) },
606
+ // Why a run outside is asked: what the sandbox refused, faint, above the command.
607
+ ...refused.map((row, i) => h(Text, { key: `refused-${i}`, dimColor: true, wrap: 'truncate' }, row)),
608
+ // Folded, never cut at the edge: what would run past the window's width is what the question is for. Set in, as what came back from a step is.
609
+ h(
610
+ Box,
611
+ { flexDirection: 'column', paddingLeft: 2, marginY: 1 },
612
+ ...(input === null ? [h(Text, { key: 'none', dimColor: true }, '(no input)')] : shown.map((row, i) => h(Text, { key: i, wrap: 'truncate' }, row || ' '))),
613
+ ...(hidden > 0 ? noted(hidden).map((row, i) => h(Text, { key: `noted-${i}`, dimColor: true, wrap: 'truncate' }, row)) : []),
614
+ ),
615
+ why !== null ? h(Box, { marginBottom: 1 }, h(Box, { flexShrink: 0 }, h(Text, { color: 'yellow' }, 'why not? ')), h(Text, null, reason.join('\n'))) : null,
616
+ // The keys go to as many rows as they need, broken only between keys — at full weight, the key itself bold: they are
617
+ // what the panel asks the user to read and press.
618
+ ...keyed.map((row, i) => h(Text, { key: `keys-${i}`, ...(explain && why === null ? { color: 'yellow' } : {}), wrap: 'wrap' }, ...keysBold(row))),
619
+ ),
335
620
  );
336
621
  }
337
622
 
338
- /** A question of the model's: its options, the one the arrows are on, and the keys that answer — a pick, or words typed in the box. */
339
- function Question({ ask }) {
623
+ /** A row of keys, `y once · n no`, with each key in bold: the eye finds the letter to press before what it does. */
624
+ const keysBold = (row) =>
625
+ row.split(' · ').flatMap((unit, i) => {
626
+ const key = /^(?:[a-z]|esc|enter|tab|↑↓)(?= )/.exec(unit)?.[0] ?? '';
627
+ return [i > 0 ? ' · ' : '', key ? h(Text, { key: i, bold: true }, key) : null, key ? unit.slice(key.length) : unit];
628
+ });
629
+
630
+ /**
631
+ * The keys a question takes, `y once · n no · …`, in rows that break only between them: a key never stands at the end of one
632
+ * row with what it does on the next. A key longer than a row has it to itself.
633
+ */
634
+ export function keyRows(said, width) {
635
+ const rows = [];
636
+ for (const unit of String(said).split(' · ')) {
637
+ const last = rows.at(-1);
638
+ if (last !== undefined && last.length + 3 + unit.length <= width) rows[rows.length - 1] = `${last} · ${unit}`;
639
+ else rows.push(unit);
640
+ }
641
+ return rows;
642
+ }
643
+
644
+ /** A mark, and words that go on under themselves, never under the mark: the options of a question. */
645
+ function Hung({ mark, width, color, children }) {
646
+ return h(Box, null, h(Box, { flexShrink: 0 }, h(Text, { color }, mark)), h(Box, { width: Math.max(10, width - mark.length) }, h(Text, { color }, ...[children].flat())));
647
+ }
648
+
649
+ /** A question of the model's: asked by sumo, waiting on the user (?), its options under it, the one the arrows are on marked, and the keys that answer — a pick, or words typed in the box. */
650
+ function Question({ ask, columns }) {
651
+ const g = useMarks();
652
+ const width = Math.max(20, columns - TEXT_AT);
340
653
  return h(
341
654
  Box,
342
655
  { marginTop: 1, flexDirection: 'column' },
343
- h(Text, { color: 'yellow' }, `? ${ask.question}`),
344
- ...ask.options.map((option, i) => h(Text, { key: i, color: i === ask.at ? ACCENT : undefined }, ` ${i === ask.at ? '❯' : ' '} ${option.label}`, option.detail ? h(Text, { dimColor: true }, ` — ${option.detail}`) : null)),
345
- h(Text, { dimColor: true }, ' ↑↓ choose · enter picks · or type your own answer · esc stop'),
656
+ h(Row, { label: 'sumo', tone: { bold: true }, mark: g.ask, markTone: { color: 'yellow', bold: true }, columns }, h(Text, { bold: true }, folded(ask.question, columns))),
657
+ h(
658
+ Box,
659
+ { flexDirection: 'column', paddingLeft: TEXT_AT },
660
+ ...ask.options.map((option, i) => h(Hung, { key: i, mark: `${i === ask.at ? g.pick : ' '} ${i + 1}. `, width, color: i === ask.at ? ACCENT : undefined }, option.label, option.detail ? h(Text, { dimColor: true }, ` — ${option.detail}`) : null)),
661
+ // Broken only between keys, as a panel's are: never `esc` at the end of a row and `to interrupt` on the next.
662
+ ...keyRows(`↑↓ choose · enter picks · 1–${ask.options.length} picks that one · or type your own answer · esc to interrupt`, width - 1).map((row, i) => h(Text, { key: `keys-${i}`, dimColor: true }, row)),
663
+ ),
346
664
  );
347
665
  }
348
666
 
349
- /** One line of a reply; the first of a block carries the mark. */
350
- function Reply({ text, first }) {
351
- return h(Box, { marginTop: first ? 1 : 0 }, h(Text, null, first ? '⏺ ' : ' '), h(Text, null, text || ' '));
667
+ /** One line of a reply; the first of a block is named `sumo` in the gutter, and stands apart from what came before it. */
668
+ function Reply({ text, first, columns }) {
669
+ return h(Row, { label: first ? 'sumo' : '', tone: { bold: true }, marginTop: first ? 1 : 0, columns }, h(Text, null, text || ' '));
352
670
  }
353
671
 
672
+ /** A folder by where it really is — `/var` is `/private/var` on macOS — or as given, when it is not there to ask. */
673
+ const realOrSame = (folder) => {
674
+ try {
675
+ return realpathSync(folder);
676
+ } catch {
677
+ return resolve(folder);
678
+ }
679
+ };
680
+
681
+ /** Why the tools are not working in the folder the chat was opened in, and what makes them. */
682
+ const awayLine = (folder) => `${folder} is not a project: the tools work in scratch — sumo project add . there makes it one`;
683
+
684
+ /** The fewest columns the folder keeps beside who answers, on the header's row. */
685
+ const HEADER_PATH_MIN = 16;
686
+
354
687
  /** Something finished, drawn once and left to scroll. */
355
688
  /** `columns` is the window's width, handed down: every item asking the terminal for it would be a listener each, on a stream that takes ten. */
356
- function Item({ item, columns }) {
689
+ function Item({ item, columns, s }) {
690
+ // The top: sumo, where the tools work, who answers. One row — the room under it is the conversation's.
357
691
  if (item.kind === 'header') {
692
+ const who = h(Text, null, item.route, VERSION ? h(Text, { dimColor: true }, ` · ${VERSION}`) : null);
693
+ const beside = columns - TEXT_AT - 1 - `${item.route} · ${VERSION}`.length - 2 >= HEADER_PATH_MIN;
358
694
  return h(
359
695
  Box,
360
- { flexDirection: 'column' },
696
+ { flexDirection: 'column', marginTop: 1 },
361
697
  h(
362
- Box,
363
- { gap: 3, marginTop: 1 },
364
- // The sunset runs across the name, gold at the S to crimson at the O.
365
- h(Box, { flexDirection: 'column', flexShrink: 0 }, ...WORDMARK.map((row, r) => h(Text, { key: r }, ...[...row].map((ch, i) => h(Text, { key: i, color: sunset(i / (row.length - 1)) }, ch))))),
366
- h(Box, { flexDirection: 'column' }, h(Text, null, item.route), h(Text, { dimColor: true }, item.cwd)),
698
+ Row,
699
+ { label: 'sumo', tone: { color: ACCENT, bold: true }, columns },
700
+ // A long path loses its middle, never runs past the edge; who answers keeps its place at the right — or, in a window
701
+ // too narrow for both on a row, goes under it: the folder the tools work in is never what gives way.
702
+ ...(beside
703
+ ? [h(Box, { key: 'row', justifyContent: 'space-between', gap: 2 }, h(Box, { flexShrink: 1 }, h(Text, { dimColor: true, wrap: 'truncate-middle' }, item.cwd)), h(Box, { flexShrink: 0 }, who))]
704
+ : [h(Text, { key: 'cwd', dimColor: true, wrap: 'truncate-middle' }, item.cwd), h(Text, { key: 'who', wrap: 'truncate-end' }, who)]),
367
705
  ),
368
- item.block ? h(Box, { marginTop: 1 }, h(Text, null, item.block)) : null,
706
+ item.away ? h(Box, { paddingLeft: TEXT_AT }, h(Text, { dimColor: true }, wrap(awayLine(item.away), Math.max(10, columns - TEXT_AT - 1)))) : null,
707
+ item.block ? h(Box, { marginTop: 1, paddingLeft: TEXT_AT }, h(Text, null, item.block)) : null,
369
708
  );
370
709
  }
371
- // What the user said is what a scroll back looks for: full weight, a bar of the chat's colour down its side.
710
+ // What the user said is what a scroll back looks for: named `you` in the chat's colour, the words at full weight.
372
711
  if (item.kind === 'user') {
712
+ const more = item.more ? h(Text, { dimColor: true }, `… +${item.more} line${item.more === 1 ? '' : 's'}`) : null;
713
+ // Folded here, at the spaces, so a row that goes on starts under the words, not with the space it broke at.
714
+ return h(Row, { label: 'you', tone: { color: ACCENT, bold: true }, marginTop: 1, columns }, h(Text, null, folded(untab(item.text), columns)), more);
715
+ }
716
+ if (item.kind === 'text') return h(Reply, { ...item, columns });
717
+ if (item.kind === 'tool') return h(Tool, { ...item, tight: STEP_KINDS.has(item.after), columns, s });
718
+ if (item.kind === 'output') return h(Box, { flexDirection: 'column' }, ...linesUnder(item.lines, columns, s));
719
+ // The turn summed up, faint, straight under the words that ended it.
720
+ if (item.kind === 'footer') return h(Box, { paddingLeft: TEXT_AT, width: columns }, h(Text, { dimColor: true }, wrap(item.text, Math.max(10, columns - TEXT_AT - 1))));
721
+ if (item.kind === 'job') return h(Row, { label: `j${item.id}`, tone: { bold: true }, marginTop: 1, columns }, h(Text, null, `${item.agent} · ${item.route} — ${item.title}`, h(Text, { dimColor: true }, ` · ${item.where}`)));
722
+ // A failure is named `error` with a mark of its own, as a failed call is, and goes on under its own words, not at the
723
+ // window's edge: folded here, at the spaces. What came back stands faint beneath, at the same margin.
724
+ if (item.kind === 'error') {
725
+ const width = Math.max(10, columns - TEXT_AT - 1);
373
726
  return h(
374
727
  Box,
375
- { marginTop: 1, flexDirection: 'column', borderStyle: 'bold', borderColor: ACCENT, borderTop: false, borderRight: false, borderBottom: false, paddingLeft: 1 },
376
- h(Text, null, untab(item.text)),
377
- item.more ? h(Text, { dimColor: true }, `… +${item.more} line${item.more === 1 ? '' : 's'}`) : null,
728
+ { marginTop: 1, flexDirection: 'column' },
729
+ h(Row, { label: 'error', tone: { color: 'red' }, mark: s.g.fail, markTone: { color: 'red' }, columns }, h(Text, { color: 'red' }, wrap(unnamed(item.text), width))),
730
+ item.detail ? h(Box, { paddingLeft: TEXT_AT }, h(Text, { dimColor: true }, wrap(item.detail, width))) : null,
378
731
  );
379
732
  }
380
- if (item.kind === 'text') return h(Reply, item);
381
- if (item.kind === 'tool') return h(Tool, { ...item, columns });
382
- if (item.kind === 'output') return h(Box, { flexDirection: 'column' }, ...linesUnder(item.lines, columns));
383
- if (item.kind === 'footer') return h(Box, { marginTop: 1 }, h(Text, { dimColor: true }, ` ${item.text}`));
384
- // The mark stands apart from the words, so a line that wraps in a narrow window goes on under them, not under it.
385
- if (item.kind === 'job') return h(Box, { marginTop: 1 }, h(Text, { color: ACCENT }, '⏺ '), h(Text, null, h(Text, { bold: true }, `j${item.id}`), ` ${item.agent} · ${item.route} — ${item.title}`, h(Text, { dimColor: true }, ` · ${item.where}`)));
386
- if (item.kind === 'error') return h(Box, { marginTop: 1 }, h(Text, { color: 'red' }, item.text));
387
- return h(Box, { flexDirection: 'column' }, ...linesUnder(item.text.split('\n').map((text) => ({ text, tone: 'dim' })), columns));
733
+ // /help: the command or key in the chat's colour, what it does faint beside it, going on under itself in a narrow window.
734
+ // A table of its own, near the margin: its keys are its gutter, and what they do keeps the room to stay on one row.
735
+ if (item.kind === 'help') {
736
+ const wide = Math.max(...item.rows.filter(Boolean).map((row) => row.key.length)) + 2;
737
+ const room = Math.max(10, columns - 2 - wide);
738
+ return h(Box, { marginTop: 1, flexDirection: 'column', paddingLeft: 2 }, ...item.rows.map((row, i) => (row ? h(Box, { key: i }, h(Box, { width: wide, flexShrink: 0 }, h(Text, { color: ACCENT }, row.key)), h(Box, { width: room }, h(Text, { dimColor: true }, wrap(row.does, room)))) : h(Text, { key: i }, ' '))));
739
+ }
740
+ // What the model thought before it answered: how long, here; the thought itself is in the pager.
741
+ if (item.kind === 'thought') return h(Row, { label: 'think', marginTop: 1, columns }, h(Text, { dimColor: true }, `for ${elapsed(item.ms)}`));
742
+ // A note of the chat's own — what a command did, where a session stopped — faint, under the words.
743
+ return h(Box, { flexDirection: 'column' }, ...linesUnder(item.text.split('\n').map((text) => ({ text, tone: 'dim' })), columns, s, null, TEXT_AT));
388
744
  }
389
745
 
746
+ /** The fewest characters of its words the working line keeps before what follows them gives way as well. */
747
+ const WORDS_KEPT = 12;
748
+
390
749
  /**
391
- * The line that says it is working: your words, the next of them every few seconds, a sunset flowing through them; how
392
- * long, how much, and how to stop it. Under it, while the model thinks, the last rows of what it has thought so far.
750
+ * The line that says it is working: named `sumo`, a spinner turning in its state column, your words — the next of them
751
+ * every few seconds — and, faint, how long, how much, and how to stop it. Under it, while the model thinks, the last rows
752
+ * of what it has thought so far.
393
753
  */
394
- function Working({ messages, first, tokens, thought = '', heard = 0, quietAfterMs = QUIET_AFTER_MS }) {
395
- const { frame, time } = useAnimation({ interval: FLOW_STEP_MS });
754
+ function Working({ messages, first, tokens, thought = '', heard = 0, quietAfterMs = QUIET_AFTER_MS, motion = true, retry = null, plan = null, waiting = false }) {
755
+ // With motion off the spinner stands still and the line is drawn once a second, for its clock. While a question
756
+ // waits on the user, nothing works: the line steps aside — the question's own rows say it waits, and how Esc stops the
757
+ // turn — and nothing is drawn for it, so the screen holds still while the question is read. It stays in place, its
758
+ // clock running, to come back when the question is answered. Plain, for a screen reader, there is no clock at all: a
759
+ // row written again every second is a row read out again every second.
760
+ const g = useMarks();
761
+ const plain = g === glyphs(true);
762
+ const spinning = motion && !waiting;
763
+ const { frame } = useAnimation({ interval: spinning ? SPIN_MS : 1000, isActive: !plain && !waiting });
764
+ // Timed from when the line appeared, not by the animation, whose clock starts again whenever its pace changes.
765
+ const began = useRef(Date.now());
766
+ const time = Date.now() - began.current;
396
767
  const { columns } = useWindowSize();
397
- const words = `${messageAt(messages, first, time)}…`;
398
- const spent = tokens > 0 ? ` · ↓ ${thousands(tokens)} tokens` : '';
399
- const thinking = thoughtRows(thought, Math.max(20, columns - 6));
768
+ if (waiting) return null;
769
+ const said = `${messageAt(messages, first, time)}…`;
770
+ const thinking = thoughtRows(thought, Math.max(20, columns - OUT_AT - 1));
400
771
  // `heard` is when the model last said or did anything, while nothing of its own is running: a long silence is said, so a stream that died is told from one that thinks.
401
772
  const silent = heard > 0 ? Date.now() - heard : 0;
402
- const quiet = silent >= quietAfterMs ? ` · quiet ${elapsed(silent)}` : '';
773
+ // A request sent again is waited on in the open: how long until it goes, and which try it is.
774
+ const left = retry ? retry.until - Date.now() : 0;
775
+ const parts = {
776
+ clock: plain ? '' : elapsed(time),
777
+ spent: tokens > 0 ? `↓ ${thousands(tokens)} tokens` : '',
778
+ again: retry && plain ? `retrying · attempt ${retry.attempt}/${retry.limit}` : left > 0 ? `retrying in ${Math.ceil(left / 1000)}s · attempt ${retry.attempt}/${retry.limit}` : '',
779
+ quiet: !plain && silent >= quietAfterMs ? `quiet ${elapsed(silent)}` : '',
780
+ };
781
+ const status = () => [parts.clock, parts.spent, parts.again, parts.quiet, 'esc to interrupt'].filter(Boolean).join(' · ');
782
+ // In a narrow window what is least needed gives way first — the tokens, the silence — then the words, to a few of their
783
+ // own, then the clock and the try. How to stop the turn is never what is cut.
784
+ const room = () => columns - TEXT_AT - status().length - 3;
785
+ for (const part of ['spent', 'quiet']) if (room() < said.length) parts[part] = '';
786
+ for (const part of ['clock', 'again']) if (room() < WORDS_KEPT) parts[part] = '';
787
+ // Cut between words where there is one to cut at: what is left still reads.
788
+ const fits = Math.max(WORDS_KEPT, room());
789
+ const cut = said.slice(0, fits - 1);
790
+ const words = said.length <= fits ? said : `${(cut.lastIndexOf(' ') >= WORDS_KEPT / 2 ? cut.slice(0, cut.lastIndexOf(' ')) : cut).trimEnd()}…`;
403
791
  return h(
404
792
  Box,
405
793
  { marginTop: 1, flexDirection: 'column' },
406
- h(Box, null, h(Text, null, ...[...words].map((ch, i) => h(Text, { key: i, color: flow(i, frame) }, ch)), ' '), h(Text, { dimColor: true }, `(${Math.floor(time / 1000)}s${spent}${quiet} · esc to interrupt)`)),
407
- ...thinking.map((row, i) => h(Text, { key: i, dimColor: true, wrap: 'truncate' }, `${i === 0 ? ' ⎿ ' : ' '}${row}`)),
794
+ // One row: the words, and what follows them cut at the edge rather than set in a column of its own beside them.
795
+ h(
796
+ Row,
797
+ { label: 'sumo', tone: { bold: true }, mark: spinning ? g.spin[frame % g.spin.length] : g.live, markTone: { color: ACCENT }, columns },
798
+ h(Box, null, h(Box, { flexShrink: 0 }, h(Text, null, `${words} `)), h(Box, { flexShrink: 1 }, h(Text, { dimColor: true, wrap: 'truncate-end' }, status()))),
799
+ ),
800
+ // The plan the model keeps in its reply: how far it has got, and what it says comes next.
801
+ plan ? h(Text, { dimColor: true, wrap: 'truncate-end' }, `${' '.repeat(TEXT_AT)}plan ${plan.done}/${plan.total}${plan.next ? ` · next: ${plan.next}` : ' · all done'}`) : null,
802
+ ...thinking.map((row, i) => h(Text, { key: i, dimColor: true, wrap: 'truncate' }, `${' '.repeat(OUT_AT)}${row}`)),
408
803
  );
409
804
  }
410
805
 
806
+ const CHECKLIST_ITEM = /^\s*[-*+]\s+\[([ xX])\]\s+(.+?)\s*$/;
807
+
808
+ /**
809
+ * A checklist in what the model wrote — `- [ ]` and `- [x]` items — as a plan: how many are done, and the first that is
810
+ * not. The latest one is the plan: a checklist written after another replaces it. Null without one.
811
+ */
812
+ export function planOf(text) {
813
+ const lines = String(text ?? '').split('\n');
814
+ let end = lines.length - 1;
815
+ while (end >= 0 && !CHECKLIST_ITEM.test(lines[end])) end--;
816
+ if (end < 0) return null;
817
+ let start = end;
818
+ while (start > 0 && CHECKLIST_ITEM.test(lines[start - 1])) start--;
819
+ const items = lines.slice(start, end + 1).map((line) => CHECKLIST_ITEM.exec(line)).map(([, mark, said]) => ({ done: mark !== ' ', said }));
820
+ const next = items.find((item) => !item.done);
821
+ return { done: items.filter((item) => item.done).length, total: items.length, next: next ? inline(next.said, styles(false)) : null };
822
+ }
823
+
411
824
  /**
412
825
  * The part of the text the box draws when it is too long to draw whole: `max` rows of it around the cursor, a row being
413
826
  * a line of the text or as much of a long one as fits the box, with how many rows lie above and below. The text itself
@@ -427,155 +840,316 @@ export function inView({ text, cursor }, width, max) {
427
840
  return { text: text.slice(rows[first][0], rows[last][1]), cursor: cursor - rows[first][0], above: first, below: rows.length - 1 - last };
428
841
  }
429
842
 
430
- /** The box to type in, the cursor drawn where the next key lands; of a text too long for it, the rows around the cursor. */
431
- function Input({ state, width, rows }) {
432
- const seen = inView(state, Math.max(10, width - 6), Math.max(3, Math.min(INPUT_ROWS, rows - 12)));
843
+ /**
844
+ * Where you type: a faint rule across the window between the conversation and you, then your row of the ledger — named
845
+ * `you`, the prompt in the state column, the cursor where the next key lands, set where what you send will stand. Of a
846
+ * text too long for it, the rows around the cursor.
847
+ */
848
+ function Input({ state, width, rows, placeholder = '' }) {
849
+ const seen = inView(state, Math.max(10, width - TEXT_AT - 1), Math.max(3, Math.min(INPUT_ROWS, rows - 12)));
433
850
  const { text, cursor } = seen;
434
851
  const on = under(seen);
435
852
  // A cursor on a line end, or past the last character, is drawn as a space of its own.
436
853
  const shown = on === '' || on === '\n' ? ' ' : on;
437
854
  const after = on === '\n' ? text.slice(cursor) : text.slice(cursor + on.length);
438
855
  const hidden = (n) => (n > 0 ? h(Text, { dimColor: true }, `… +${n} line${n === 1 ? '' : 's'}`) : null);
856
+ // Plain, there is no rule: a line of box drawing is read out as a row of lines.
857
+ const g = useMarks();
858
+ const framed = g !== glyphs(true);
439
859
  return h(
440
860
  Box,
441
- { borderStyle: 'round', borderColor: 'gray', paddingX: 1, width },
442
- h(Text, null, '> '),
443
- h(Box, { flexGrow: 1, flexShrink: 1, flexDirection: 'column' }, hidden(seen.above), h(Text, null, untab(text.slice(0, cursor)), h(Text, { inverse: true }, untab(shown)), untab(after)), hidden(seen.below)),
861
+ { flexDirection: 'column', width },
862
+ framed ? h(Text, { dimColor: true }, g.rule.repeat(Math.max(1, width))) : null,
863
+ h(
864
+ Box,
865
+ null,
866
+ h(Box, { flexShrink: 0, width: TEXT_AT }, h(Text, null, h(Text, { dimColor: true }, 'you'.padStart(GUTTER)), ' ', h(Text, { color: ACCENT, bold: true }, g.pick), ' ')),
867
+ // An empty box says what it is for, faint behind the cursor, until something has been said.
868
+ h(Box, { flexGrow: 1, flexShrink: 1, flexDirection: 'column' }, hidden(seen.above), h(Text, { wrap: !text && placeholder ? 'truncate-end' : 'wrap' }, untab(text.slice(0, cursor)), reverse(untab(shown)), untab(after), !text && placeholder ? h(Text, { dimColor: true }, placeholder) : null), hidden(seen.below)),
869
+ ),
444
870
  );
445
871
  }
446
872
 
447
- function Menu({ menu, pick }) {
873
+ /** The most rows of a menu drawn at once: a long one scrolls with the pick, so opening it never pushes the conversation far up. */
874
+ const MENU_ROWS = 8;
875
+
876
+ /** The commands, or the files, a half-typed word could mean: one row each, the one picked marked; past the rows there is room for, a window that follows the pick. */
877
+ /**
878
+ * A description cut to its room where a clause ends — at `;`, `:` or ` — ` — so what is left still says something
879
+ * whole: "the MCP servers", not "the MCP servers: connected or not, their tools, what may run u…". With no such place
880
+ * in reach it is cut between words.
881
+ */
882
+ function clauseFit(text, room) {
883
+ if (text.length <= room) return text;
884
+ let cut = -1;
885
+ for (const mark of ['; ', ': ', ' — ']) {
886
+ for (let at = text.indexOf(mark); at !== -1 && at <= room; at = text.indexOf(mark, at + 1)) cut = Math.max(cut, at);
887
+ }
888
+ if (cut > 0) return text.slice(0, cut);
889
+ const space = text.lastIndexOf(' ', room - 2);
890
+ return space > 0 ? `${text.slice(0, space)} …` : text.slice(0, Math.max(0, room - 1));
891
+ }
892
+
893
+ function Menu({ menu, pick, columns = 80 }) {
894
+ const g = useMarks();
448
895
  const wide = Math.max(...menu.map((c) => c.label.length)) + 2;
896
+ // The row's room for the description: the window less the gutter, the mark and the name.
897
+ const room = Math.max(10, columns - TEXT_AT - 1 - wide);
898
+ const first = Math.min(Math.max(0, pick - MENU_ROWS + 1), Math.max(0, menu.length - MENU_ROWS));
899
+ const shown = menu.slice(first, first + MENU_ROWS);
900
+ const below = menu.length - first - shown.length;
901
+ // The mark in the state column, the names under the words of the box: what is picked is what the box would hold.
449
902
  return h(
450
903
  Box,
451
- { flexDirection: 'column', paddingX: 2 },
452
- ...menu.map((c, i) => h(Text, { key: c.name, color: i === pick ? ACCENT : undefined, dimColor: i !== pick }, c.label.padEnd(wide), c.hint)),
904
+ { flexDirection: 'column', paddingLeft: GUTTER + 1, paddingRight: 1 },
905
+ first > 0 ? h(Text, { dimColor: true }, ` ↑ ${first} more`) : null,
906
+ // A hint is one row: wrapped, its second line would stand under the names, where a name is looked for.
907
+ ...shown.map((c, i) => h(Text, { key: c.name, color: first + i === pick ? ACCENT : undefined, dimColor: first + i !== pick, wrap: 'truncate-end' }, `${first + i === pick ? `${g.pick} ` : ' '}${c.label.padEnd(wide)}`, c.hint ? clauseFit(c.hint, room) : c.hint)),
908
+ below > 0 ? h(Text, { dimColor: true }, ` ↓ ${below} more`) : null,
453
909
  );
454
910
  }
455
911
 
456
912
  /** A sum of money for a margin: nothing until it is a cent. */
457
913
  const dollars = (cost) => (cost >= 0.005 ? `$${cost.toFixed(2)}` : '');
458
914
 
459
- function Status({ session, leaving, notice, jobs, aside = [], pick = null, open = null, where, spent, waiting, columns }) {
460
- const size = session.contextTokens >= 1000 ? ` · ${Math.round(session.contextTokens / 1000)}k context` : '';
915
+ /** The keys most reached for, as `?` shows them: the key, then what it does. /help has all of them. */
916
+ const KEYS = [
917
+ ['enter', 'send'],
918
+ ['\\ enter', 'a new line'],
919
+ ['esc', 'interrupt the turn'],
920
+ ['↑ ↓', 'what you sent before'],
921
+ ['ctrl-r', 'search what you sent'],
922
+ ['ctrl-c', 'clear · twice to leave'],
923
+ ['ctrl-o', 'the whole transcript'],
924
+ ['ctrl-g', 'write in your editor'],
925
+ ['ctrl-v', 'paste an image'],
926
+ ['ctrl-y', 'put back what was cut'],
927
+ ['ctrl-_', 'undo in the box'],
928
+ ['ctrl-l', 'draw the screen again'],
929
+ ['/', 'commands'],
930
+ ['@', 'name a file'],
931
+ ['!', 'run a command yourself'],
932
+ ];
933
+
934
+ const KEY_WIDTH = Math.max(...KEYS.map(([key]) => key.length)) + 2;
935
+
936
+ /** `?` on an empty box: the keys, in as many columns as the window holds, until the next key. */
937
+ function Keys({ columns }) {
938
+ const per = columns >= 96 ? 3 : columns >= 64 ? 2 : 1;
939
+ const width = Math.floor((columns - TEXT_AT - 1) / per);
940
+ const rows = [];
941
+ for (let i = 0; i < KEYS.length; i += per) rows.push(KEYS.slice(i, i + per));
942
+ return h(
943
+ Box,
944
+ { flexDirection: 'column', paddingLeft: TEXT_AT, paddingRight: 1 },
945
+ ...rows.map((row, r) => h(Box, { key: r }, ...row.map(([key, does], i) => h(Box, { key: i, width }, h(Text, { wrap: 'truncate-end' }, h(Text, { color: ACCENT }, key.padEnd(KEY_WIDTH)), h(Text, { dimColor: true }, does)))))),
946
+ // Broken only between its parts, as a question's keys are.
947
+ ...keyRows('/help has the commands too · any key closes this', columns - TEXT_AT - 1).map((row, i) => h(Text, { key: `more-${i}`, dimColor: true }, row)),
948
+ );
949
+ }
950
+
951
+ /** Ctrl-R at work: what has been typed to find, and how to go on; the box shows what it found. */
952
+ function Search({ search }) {
953
+ return h(
954
+ Box,
955
+ { paddingLeft: TEXT_AT, paddingRight: 1 },
956
+ h(
957
+ Text,
958
+ { wrap: 'truncate-end' },
959
+ h(Text, { color: search.failed ? 'red' : ACCENT }, `search: ${search.query}`),
960
+ h(Text, { dimColor: true }, search.failed ? ' — nothing you sent holds that' : !search.query ? 'type what to find in what you sent · esc puts your draft back' : `${search.end ? ' — nothing further back' : ' · ctrl-r further back'} · enter keeps it · esc puts your draft back`),
961
+ ),
962
+ );
963
+ }
964
+
965
+ /** The size of the context, coloured by how far it has grown: faint while it is small, yellow once quality starts to drop, red when it is time for /handoff. */
966
+ export function contextTone(tokens) {
967
+ const band = contextBand(tokens);
968
+ return band === 'act' ? { color: 'red' } : band === 'watch' ? { color: 'yellow' } : { dimColor: true };
969
+ }
970
+
971
+ /**
972
+ * Hints that fit the room they have, whole: the ones at the end give way first, so a row never ends in a key broken
973
+ * off ("ctrl-o fu…"). One that is too long alone is cut between words, never inside one.
974
+ */
975
+ function fitHint(hint, room) {
976
+ if (hint.length <= room) return hint;
977
+ const parts = hint.split(' · ');
978
+ while (parts.length > 1 && parts.join(' · ').length > room) parts.pop();
979
+ const left = parts.join(' · ');
980
+ if (left.length <= room) return left;
981
+ const space = left.lastIndexOf(' ', room - 2);
982
+ return space > 0 ? `${left.slice(0, space)} …` : '';
983
+ }
984
+
985
+ function Status({ session, leaving, notice, jobs, aside = [], pick = null, open = null, where, spent, overBudget = false, waiting, columns }) {
986
+ const tokens = session.contextTokens;
987
+ const size = tokens >= 1000 ? ` · ${Math.round(tokens / 1000)}k context${contextBand(tokens) === 'act' ? ' · /handoff' : ''}` : '';
461
988
  const cost = dollars(spent) && ` · ${dollars(spent)}`;
462
989
  // Where the tools run: the project and the branch it is on. The header that says it scrolls away; this does not.
463
990
  const place = where ? `${where.name}${where.branch ? ` (${where.branch})` : ''}` : '';
464
- const hint = leaving ? `Ctrl-C again to leave${aside.length > 0 ? ` — it stops ${aside.map((id) => `j${id}`).join(', ')}, to be picked up again later` : ''}` : notice ? notice : pick === MAIN ? 'enter shows main · ↑ back to the box' : pick !== null ? `enter opens j${pick} · ↑ back to the box` : open !== null ? `esc closes j${open} · ctrl-o all of its record · @ message talks to it` : jobs.length > 0 ? `${jobs.length === 1 ? `@ message talks to j${jobs[0]}` : '@j<id> message talks to that job'} · ${aside.length > 0 ? `↓ enter opens ${aside.length === 1 ? 'it' : 'one'} · /stop stops it` : 'ctrl-o full output'}` : waiting ? '↑ takes back what is waiting' : '/ commands · /help · ctrl-o full output';
991
+ const hint = leaving ? `ctrl-c again to leave${aside.length > 0 ? ` — it stops ${aside.map((id) => `j${id}`).join(', ')}, to be picked up again later` : ''}` : notice ? notice : pick === MAIN ? 'enter shows main · ↑ back to the box' : pick !== null ? `enter opens j${pick} · ↑ back to the box` : open !== null ? `esc closes j${open} · ctrl-o all of its record · @ message talks to it` : jobs.length > 0 ? `${jobs.length === 1 ? `@ message talks to j${jobs[0]}` : '@j<id> message talks to that job'} · ${aside.length > 0 ? `↓ enter opens ${aside.length === 1 ? 'it' : 'one'} · /stop stops it` : 'ctrl-o full output'}` : waiting ? '↑ takes it back' : '/ commands · ? keys · ctrl-o full output';
465
992
  // In a narrow window the hints give way, then the place — unless the line has something to say just now, which the place
466
993
  // gives way to; the model, the size of the context and the cost never fold.
467
994
  const route = `${routeLine(session)}${size}${cost}`;
468
- const room = columns - 4 - route.length - 2;
469
995
  const said = leaving || notice;
470
- const placed = place && place.length <= room - (said ? hint.length + 2 : 0) ? place : '';
471
- const hinted = room - (placed ? placed.length + 2 : 0) >= 12 ? hint : '';
996
+ // Under the words of the box — unless that would fold the route onto a second row, or cut what the row has to say just
997
+ // now: then it starts near the margin, and what is said is said whole.
998
+ const at = TEXT_AT + 1 + route.length + (said ? 2 + hint.length : 0) <= columns ? TEXT_AT : 2;
999
+ // The route in its parts: the size coloured by how far it has grown, the cost yellow once the session has passed its budget.
1000
+ const routed = h(Text, null, h(Text, { dimColor: true }, routeLine(session)), size ? h(Text, contextTone(tokens), size) : null, cost ? h(Text, overBudget ? { color: 'yellow' } : { dimColor: true }, cost) : null);
1001
+ const room = columns - at - 1 - route.length - 2;
1002
+ const placed = place && place.length + 3 <= room - (said ? hint.length + 2 : 0) ? place : '';
1003
+ const hinted = room - (placed ? placed.length + 3 : 0) >= 12 ? fitHint(hint, room - (placed ? placed.length + 3 : 0)) : '';
472
1004
  // With jobs at work the keys are what is needed, and they are long: they follow the jobs, from the left, and give way in a
473
- // narrow window; the route stands at the right, over the place, so nothing under the jobs reads as one more of them.
1005
+ // narrow window; the route stands at the right with the place beside it, while the keys keep room for their first words.
474
1006
  if (jobs.length > 0) {
1007
+ // The keys come first here: the place stands beside the route only when they still fit whole.
1008
+ const beside = place && columns - at - 1 - route.length - place.length - 3 - 2 >= hint.length;
475
1009
  return h(
476
1010
  Box,
477
- { paddingX: 2, flexDirection: 'column' },
478
- h(Box, { justifyContent: 'space-between', gap: 2 }, h(Box, { flexShrink: 1 }, h(Text, { dimColor: true, wrap: 'truncate' }, hint)), h(Box, { flexShrink: 0 }, h(Text, { dimColor: true }, route))),
479
- place && place.length <= columns - 4 ? h(Box, { justifyContent: 'flex-end' }, h(Text, { dimColor: true }, place)) : null,
1011
+ { paddingLeft: at, paddingRight: 1, justifyContent: 'space-between', gap: 2 },
1012
+ h(Box, { flexShrink: 1 }, h(Text, { dimColor: true, wrap: 'truncate' }, fitHint(hint, columns - at - 1 - route.length - 2 - (beside ? place.length + 3 : 0)))),
1013
+ h(Box, { flexShrink: 0, gap: 3 }, routed, beside ? h(Text, { dimColor: true }, place) : null),
480
1014
  );
481
1015
  }
1016
+ // The place stands with the route it belongs to, on the left, under the words of the box; the keys at the right.
482
1017
  return h(
483
1018
  Box,
484
- { paddingX: 2, justifyContent: 'space-between', gap: 2 },
485
- h(Box, { flexShrink: 0 }, h(Text, { dimColor: true }, route)),
486
- placed ? h(Box, { flexShrink: 0 }, h(Text, { dimColor: true }, placed)) : null,
1019
+ { paddingLeft: at, paddingRight: 1, justifyContent: 'space-between', gap: 2 },
1020
+ h(Box, { flexShrink: 0, gap: 3 }, routed, placed ? h(Text, { dimColor: true }, placed) : null),
487
1021
  hinted ? h(Box, { flexShrink: 1 }, h(Text, { dimColor: true, wrap: 'truncate' }, hinted)) : null,
488
1022
  );
489
1023
  }
490
1024
 
491
- /** `/help`: every command with what it does, and the keys — written as a reply is, so it is drawn as one. */
492
- function helpText(commands) {
493
- const keys = [
494
- ['Enter', 'send — while the model works, it reads the message with its next step'],
495
- ['\\\\ then Enter · Shift-Enter · Option-Enter · Ctrl-J', 'a new line'],
496
- ['Up · Down', 'between the lines of the text, then through what you sent before; on an empty box, Up takes back a message that is waiting'],
497
- ['Esc', 'stop the turn (first closes the command menu); what was waiting comes back to the box'],
498
- ['Ctrl-C', 'clear the box; on an empty one, stop the turn, or twice to leave — Ctrl-D leaves too'],
499
- ['Ctrl-O', 'the whole conversation in your pager ($PAGER, or less): every command and all its output, to scroll and search'],
500
- ['Ctrl-G', 'write the message in your editor ($VISUAL or $EDITOR); what you save comes back to the box'],
501
- ['@ and a few letters', 'name a file of the project: the menu offers the ones they could mean, and Enter or Tab puts the path in'],
502
- ['Ctrl-V', 'paste an image from the clipboard; an image file dropped on the box is the image'],
503
- ['Ctrl-A · Ctrl-E', 'the start and the end of the line'],
504
- ['Ctrl-U · Ctrl-K', 'cut to the start, or to the end, of the line'],
505
- ['Ctrl-W · Option-Backspace', 'cut the word before the cursor'],
506
- ['Option-Left · Option-Right', 'a word at a time'],
507
- ['! command', 'run a command yourself, where the agent would be refused; the model sees what it printed'],
508
- ['@ message · @j<id> message', 'say it to the job that is running — the one open, when one is — or to a named one'],
509
- ['Down, then Enter', 'from the box onto the jobs at work under it, and open the one stepped on: the end of its record, as it grows; Esc closes it, Ctrl-O shows all of it'],
510
- ];
511
- return [
512
- '**Commands**',
513
- '',
514
- '| Command | What it does |',
515
- '|---|---|',
516
- ...commands.map((c) => `| \`/${c.name}\` | ${c.hint.replaceAll('|', '\\|')} |`),
517
- '',
518
- '**Keys**',
519
- '',
520
- '| Key | What it does |',
521
- '|---|---|',
522
- ...keys.map(([key, does]) => `| ${key} | ${does} |`),
523
- '',
524
- ].join('\n');
525
- }
1025
+ /** The keys /help lists under the commands, a row each: the ones most reached for. `?` on an empty box shows them at a glance. */
1026
+ const HELP_KEYS = [
1027
+ ['enter', 'send; while the model works, it reads it next'],
1028
+ ['\\ enter', 'a new line (shift-enter and ctrl-j too)'],
1029
+ ['esc', 'interrupt the turn, or close a menu'],
1030
+ ['↑ ↓', 'what you sent before'],
1031
+ ['ctrl-r', 'search what you sent'],
1032
+ ['ctrl-c', 'clear the box; twice on an empty one to leave'],
1033
+ ['ctrl-o', 'the whole conversation in your pager'],
1034
+ ['ctrl-g', 'write the message in your editor'],
1035
+ ['ctrl-v', 'paste an image'],
1036
+ ['ctrl-z', 'suspend to the shell; fg brings it back'],
1037
+ ['@ file', 'name a file of the project'],
1038
+ ['! command', 'run a command yourself'],
1039
+ ['@j<id> message', 'talk to a job at work'],
1040
+ ];
1041
+
1042
+ /** `/help`: every command with what it takes and what it does, then the keys — a row each, to be taken in at a glance. A blank row between. */
1043
+ const helpRows = (commands) => [...commands.map((c) => ({ key: `/${c.name}${c.args ? ` ${c.args}` : ''}`, does: c.hint })), null, ...HELP_KEYS.map(([key, does]) => ({ key, does }))];
1044
+
1045
+ /** What an empty chat suggests under its header, faint: something to try, and where the rest is. */
1046
+ const STARTER = 'try "explain this project" or "add a test for @file" · /help for more';
1047
+ /** The rows the suggestion takes at the top of the room, with a blank row on either side of it. */
1048
+ const STARTER_ROWS = 3;
526
1049
 
527
1050
  /**
528
- * The room between the conversation and the box, with the logo behind it: faint, in the middle of the window, where it stays while
529
- * the conversation grows over it — what reaches it covers it. `from` is the row of the window the live part of the screen starts on.
1051
+ * The room between the conversation and the box: in an empty chat, a line of what to try at its top, and the logo behind it
1052
+ * — faint, in the middle of the window. Whatever takes rows from the room — a menu under the box, what was said — moves the
1053
+ * logo up while it still fits whole, and then leaves it out: it is never cut. `from` is the row of the window the live part
1054
+ * of the screen starts on.
530
1055
  */
531
- function Room({ logo, rows, from }) {
1056
+ function Room({ logo, rows, from, starter = false }) {
532
1057
  const ref = useRef(null);
533
1058
  const { width, height, top, hasMeasured } = useBoxMetrics(ref);
534
1059
  const wide = Math.max(0, ...logo.map((row) => row.length));
535
- const at = Math.floor((rows - logo.length) / 2) - from - top;
536
- const seen = logo.length > 0 && hasMeasured && width >= wide && at < height && at + logo.length > 0;
1060
+ const clear = starter ? STARTER_ROWS : 0;
1061
+ const at = Math.max(clear, Math.min(Math.floor((rows - logo.length) / 2) - from - top, height - logo.length));
1062
+ const seen = logo.length > 0 && hasMeasured && width >= wide && at + logo.length <= height;
537
1063
  return h(
538
1064
  Box,
539
1065
  { ref, flexGrow: 1, flexDirection: 'column', overflow: 'hidden' },
1066
+ starter ? h(Box, { marginTop: 1, paddingLeft: TEXT_AT }, h(Text, { dimColor: true, wrap: 'truncate-end' }, STARTER)) : null,
540
1067
  seen ? h(Box, { position: 'absolute', top: at, left: Math.floor((width - wide) / 2), flexDirection: 'column' }, ...logo.map((row, i) => h(Text, { key: i, color: 'gray', dimColor: true }, row || ' '))) : null,
541
1068
  );
542
1069
  }
543
1070
 
544
- function App({ session, events, messages, cwd, block, opening, logo, clipboard, copy, notify: alerts, notifyAfterMs, quietAfterMs, run, listFiles }) {
545
- const { exit, suspendTerminal } = useApp();
1071
+ function App({ session, events, messages, cwd, block, opening, logo, clipboard, copy, notify: alerts, notifyAfterMs, quietAfterMs, run, listFiles, motion, progress, plain = false, front = { now: true } }) {
1072
+ const { exit, suspendTerminal, waitUntilRenderFlush } = useApp();
546
1073
  const { stdout, write } = useStdout();
547
1074
  const { columns, rows } = useWindowSize();
548
1075
  const [, redraw] = useReducer((n) => n + 1, 0);
549
- const s = styles(colourEnabled(stdout));
550
- const header = (text) => ({ kind: 'header', route: routeLine(session), cwd: tilde(cwd), block: text });
1076
+ // Addresses in a reply open on a click; the pager gets none of that, since a pager may draw its codes as text.
1077
+ const s = styles(colourEnabled(stdout), { links: true, plain });
1078
+ const paged = styles(colourEnabled(stdout), { plain });
1079
+ /**
1080
+ * The top of a session: who answers, and where the tools work — the project, which is not always the folder the chat was
1081
+ * opened in. Opened in a folder that is not a project, the work goes to scratch: the header says so, and how to change it.
1082
+ */
1083
+ const header = (text) => {
1084
+ const at = session.where().cwd;
1085
+ const away = at === scratchDir() && realOrSame(cwd) !== at ? tilde(cwd) : null;
1086
+ return { kind: 'header', route: routeLine(session), cwd: tilde(at), away, block: text };
1087
+ };
551
1088
  // What the screen holds between draws. Keys and the session's events both write here, in the order they happen, and then ask for a draw.
552
1089
  // `log` is what happened, as it was said; `items` is the log drawn for this window, and is drawn again when the window or the view changes.
553
1090
  const st = useRef(null);
554
1091
  // `live` is what each running command has printed so far and since when; `heard`, when the model last said or did anything;
555
1092
  // `turn`, what the turn in hand has done; `talking`, that the model — not a `!` command — is what the screen is working on;
556
1093
  // `pick`, the job under the box that Down has stepped onto; `open`, the one whose record is shown.
557
- st.current ??= { log: [], items: [], unmeasured: [], used: 0, next: 0, epoch: 0, raw: '', ed: editor(readHistory()), images: [], notice: null, queue: [], working: null, talking: false, tokens: 0, thought: '', heard: 0, running: new Map(), live: new Map(), drawSoon: null, jobs: new Map(), pick: null, open: null, asks: [], reply: null, fresh: true, leaving: null, gone: false, focused: true, title: null, turn: null, where: session.where(), spent: session.spent(), files: { cwd: null, at: 0, list: [] }, away: false };
1094
+ st.current ??= { log: [], items: [], unmeasured: [], used: 0, next: 0, epoch: 0, raw: '', ed: editor(readHistory()), images: [], pastes: [], keys: false, notice: null, queue: [], started: new Map(), known: new Map(), working: null, talking: false, tokens: 0, thought: '', thinking: null, showThinking: true, heard: 0, running: new Map(), live: new Map(), drawSoon: null, jobs: new Map(), pick: null, open: null, asks: [], why: null, reply: null, fresh: true, leaving: null, gone: false, title: null, turn: null, where: session.where(), spent: session.spent(), files: { cwd: null, at: 0, list: [] }, away: false };
558
1095
  const state = st.current;
559
1096
  state.columns = columns;
560
1097
  state.rows = rows;
561
1098
 
1099
+ /** An item as it is placed: its id, and the kind of the one before it — steps one after another stand without a blank row between. */
1100
+ const stamped = (item) => ({ id: state.next++, after: state.items.at(-1)?.kind, ...item });
562
1101
  const place = (items) => {
563
- const placed = items.map((item) => ({ id: state.next++, ...item }));
564
- state.items = [...state.items, ...placed];
565
- state.unmeasured.push(...placed);
1102
+ for (const item of items) {
1103
+ const placed = stamped(item);
1104
+ state.items = [...state.items, placed];
1105
+ state.unmeasured.push(placed);
1106
+ }
566
1107
  };
567
1108
  /**
568
1109
  * The rows what is finished takes on the screen since it was last cleared, counted until it fills the window: the room under it is
569
1110
  * the box's to stand at the foot of. Measured before the next draw, never during one — a frame too tall would scroll the top away.
1111
+ * An item is drawn apart to be counted, and that sets off a draw of the screen that is waiting, if one is: so an item leaves
1112
+ * `unmeasured` only once it is counted, and a draw it sets off keeps the room shut rather than one row too tall.
570
1113
  */
1114
+ const rowsOf = (item) => renderToString(h(Marks.Provider, { value: s.g }, h(Item, { item, columns: state.columns, s })), { columns: state.columns }).split('\n').length;
571
1115
  const measure = () => {
572
- for (const item of state.unmeasured.splice(0)) {
573
- if (state.used < state.rows) state.used += renderToString(h(Item, { item, columns: state.columns }), { columns: state.columns }).split('\n').length;
1116
+ while (state.unmeasured.length > 0) {
1117
+ if (state.used < state.rows) state.used += rowsOf(state.unmeasured[0]);
1118
+ state.unmeasured.shift();
574
1119
  }
575
1120
  };
1121
+ /**
1122
+ * Reads one after another are drawn as one row: they wait here, under the work, until something else comes — and
1123
+ * anything that goes on the screen first puts them there, as the row they make. The log keeps every one of them.
1124
+ */
1125
+ state.reads ??= [];
1126
+ const isRead = (entry) => entry.kind === 'tool' && entry.call.name === EDITOR_TOOL.name && entry.call.input?.command === 'view' && !entry.result.isError && !entry.started?.length;
1127
+ const readsDrawn = (reads) => {
1128
+ if (reads.length === 1) return drawn(reads[0]);
1129
+ // By the files' names: the row is a glance, and the paths, whole, are in Ctrl-O. Two of one name are told apart by their paths.
1130
+ const paths = [...new Set(reads.map((entry) => String(entry.call.input?.path ?? '')))];
1131
+ const names = paths.map((p) => basename(p));
1132
+ const seen = paths.map((p, i) => (names.indexOf(names[i]) === names.lastIndexOf(names[i]) ? names[i] : pathFrom(p, state.where.cwd)));
1133
+ const named = seen.length > 2 ? [...seen.slice(0, 2), `+${seen.length - 2}`] : seen;
1134
+ const lines = reads.reduce((sum, entry) => sum + (entry.result.content === '' ? 0 : entry.result.content.replace(/\n$/, '').split('\n').length), 0);
1135
+ const files = new Set(reads.map((entry) => entry.call.input?.path)).size;
1136
+ return [{ kind: 'tool', view: { title: 'read', detail: `${files} file${files === 1 ? '' : 's'} · ${named.join(', ')}`, lines: [{ text: `${lines} lines`, tone: 'dim' }] }, failed: false, took: reads.reduce((sum, entry) => sum + (entry.took ?? 0), 0) }];
1137
+ };
1138
+ const placeReads = () => {
1139
+ if (state.reads.length > 0) place(readsDrawn(state.reads.splice(0)));
1140
+ };
1141
+ /**
1142
+ * Items for the screen, each counted before it is placed: a draw that counting one sets off sees the screen as it was —
1143
+ * never an item placed and not yet counted, which is a frame a row too tall for the window: the top scrolls away for good
1144
+ * and the box is left standing above the foot. What was placed and not counted yet is counted first.
1145
+ */
576
1146
  const show = (items) => {
577
- place(items);
578
1147
  measure();
1148
+ for (const item of [...(state.reads.length > 0 ? readsDrawn(state.reads.splice(0)) : []), ...items]) {
1149
+ const placed = stamped(item);
1150
+ if (state.used < state.rows) state.used += rowsOf(placed);
1151
+ state.items = [...state.items, placed];
1152
+ }
579
1153
  redraw();
580
1154
  };
581
1155
  /** A renderer for a reply: each line it finishes goes on the screen, the first of a block with the mark. */
@@ -586,17 +1160,36 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
586
1160
  state.fresh = false;
587
1161
  },
588
1162
  s,
589
- { width: state.columns - 3 },
1163
+ { width: state.columns - TEXT_AT - 1 },
590
1164
  );
591
1165
  /** One entry of the log as the lines this window shows for it. */
592
1166
  function drawn(entry) {
593
1167
  if (entry.kind === 'header') {
594
1168
  // The memory block is the model's; what is wrong in it is the user's to see.
595
1169
  const warnings = entry.block.split('\n').filter((line) => line.startsWith('Warning')).join('\n');
596
- return [{ ...entry, block: warnings && renderBlock(warnings, s, { width: state.columns - 1 }) }];
1170
+ return [{ ...entry, block: warnings && renderBlock(warnings, s, { width: state.columns - TEXT_AT - 1 }) }];
597
1171
  }
598
1172
  if (entry.kind === 'tool') {
599
- return [{ kind: 'tool', view: toolView(entry.call, entry.result, { cwd: state.where.cwd }), failed: entry.result.isError }];
1173
+ const view = toolView(entry.call, entry.result, { cwd: state.where.cwd });
1174
+ // A job the call started in the background is told under it: who, on what, and where to follow it — not on a line of its own above the call.
1175
+ const started = entry.started ?? [];
1176
+ if (started.length === 1 && /^j\d+ is running in the background/.test(entry.result.content)) {
1177
+ const [job] = started;
1178
+ view.lines = [
1179
+ { text: `j${job.id} ${job.agent} · ${job.route} — running in the background`, tone: 'plain' },
1180
+ { text: `its report comes here when it is done · ${job.where}`, tone: 'dim' },
1181
+ ];
1182
+ } else if (started.length > 1 && /^j\d+ is running in the background/.test(entry.result.content)) {
1183
+ // Attempts side by side: a line each, and one for the report they make together.
1184
+ view.lines = [
1185
+ ...started.map((job) => ({ text: `j${job.id} ${job.agent} · ${job.route} — running in the background · ${job.where.replace(/^follow it: /, '')}`, tone: 'plain' })),
1186
+ { text: `their report comes here when all ${started.length} are done`, tone: 'dim' },
1187
+ ];
1188
+ }
1189
+ // A question's answer is the user's: said as theirs, without what rode with it for the model.
1190
+ const answered = entry.call.name === ASK_TOOL.name && !entry.result.isError ? /^The user (chose|answered): ([^\n]*)/.exec(entry.result.content) : null;
1191
+ if (answered) view.lines = [{ text: answered[1] === 'chose' ? `you chose ${answered[2]}` : `you answered: ${answered[2]}`, tone: 'plain' }];
1192
+ return [{ kind: 'tool', view, failed: entry.result.isError, took: entry.took ?? 0 }];
600
1193
  }
601
1194
  // What the user's own command printed: drawn as a tool's output is, under the line they typed.
602
1195
  if (entry.kind === 'shell') return [{ kind: 'output', lines: toolView({ name: BASH_TOOL.name }, entry.result).lines }];
@@ -615,13 +1208,27 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
615
1208
  }
616
1209
  const record = (entry) => {
617
1210
  state.log.push(entry);
618
- show(drawn(entry));
1211
+ if (!isRead(entry)) return show(drawn(entry));
1212
+ state.reads.push(entry);
1213
+ redraw();
1214
+ };
1215
+ /** The whole log placed again, reads one after another as the row they make; the last of them still waits while the turn goes on (`open`). */
1216
+ const placeLog = (open = false) => {
1217
+ state.reads = [];
1218
+ for (const entry of state.log) {
1219
+ if (isRead(entry)) state.reads.push(entry);
1220
+ else {
1221
+ placeReads();
1222
+ place(drawn(entry));
1223
+ }
1224
+ }
1225
+ if (!open) placeReads();
619
1226
  };
620
1227
  if (state.log.length === 0) {
621
1228
  state.log.push(header(block));
622
1229
  // A chat opened on a saved session shows where it stopped and says which, under the header, where a fresh one shows the block's warnings.
623
1230
  if (opening) state.log.push(...replayOf(session.params.messages), { kind: 'note', text: opening });
624
- for (const entry of state.log) place(drawn(entry));
1231
+ placeLog();
625
1232
  }
626
1233
 
627
1234
  /** The jobs at work with no call standing over them, by id: the ones under the box. */
@@ -637,6 +1244,14 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
637
1244
  if (!state.jobs.has(state.open)) state.open = null;
638
1245
  };
639
1246
 
1247
+ /** The model has stopped thinking and acts: how long it thought stays on the screen, and what it thought goes in the log for the pager. */
1248
+ const thoughtDone = () => {
1249
+ if (state.thinking === null) return;
1250
+ const ms = Date.now() - state.thinking;
1251
+ state.thinking = null;
1252
+ if (ms >= THOUGHT_SHOWN_MS) record({ kind: 'thought', ms, text: state.thought });
1253
+ };
1254
+
640
1255
  /** The reply so far is whole: its last line is drawn, it joins the log, and the next text starts a new block. */
641
1256
  const closeReply = () => {
642
1257
  state.reply?.flush();
@@ -645,6 +1260,19 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
645
1260
  state.fresh = true;
646
1261
  };
647
1262
 
1263
+ /**
1264
+ * The reply in hand thrown away, as the loop throws it away: the try it came from failed and is being sent again, or
1265
+ * the model declined it. What has not been drawn is not drawn; none of it joins the log, so the pager, /copy and
1266
+ * /export never have it, and the next text starts a block of its own.
1267
+ */
1268
+ const dropReply = () => {
1269
+ state.raw = '';
1270
+ state.fresh = true;
1271
+ state.thought = '';
1272
+ state.thinking = null;
1273
+ if (state.reply) state.reply = replyTo((item) => show([item]));
1274
+ };
1275
+
648
1276
  /**
649
1277
  * Everything again, from the log, after the window changed size — the window and its scrollback wiped, since what they
650
1278
  * hold is drawn again. A session that starts over has nothing to draw again:
@@ -654,7 +1282,7 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
654
1282
  state.items = [];
655
1283
  state.unmeasured = [];
656
1284
  state.used = 0;
657
- for (const entry of state.log) place(drawn(entry));
1285
+ placeLog(Boolean(state.working));
658
1286
  measure();
659
1287
  state.fresh = true;
660
1288
  if (state.working) {
@@ -673,7 +1301,7 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
673
1301
 
674
1302
  /** A bell and a notification, when the window is not the one in front: the turn is over, or it waits for an answer. */
675
1303
  const alert = (text) => {
676
- if (alerts && !state.focused) tell(`\x1b]9;sumo — ${safeForTerminal(text).replace(/\s+/g, ' ')}\x07\x07`);
1304
+ if (alerts && !front.now) tell(`\x1b]9;sumo — ${safeForTerminal(text).replace(/\s+/g, ' ')}\x07\x07`);
677
1305
  };
678
1306
 
679
1307
  /** How a turn ended, in one line: how long, how many calls, the files it changed, what it cost. A quick answer with no calls gets none. */
@@ -682,8 +1310,12 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
682
1310
  state.spent = session.spent();
683
1311
  state.where = session.where();
684
1312
  const { calls, edited } = state.turn;
685
- const files = [...edited];
686
- const parts = [elapsed(took), calls > 0 ? `${calls} call${calls === 1 ? '' : 's'}` : '', files.length > 0 ? `edited ${files.slice(0, 3).join(', ')}${files.length > 3 ? ` +${files.length - 3} more` : ''}` : '', dollars(state.spent - before)];
1313
+ // The files by their names, as the rows above them were: each edit's row has its path.
1314
+ const files = [...new Set([...edited].map((path) => basename(path)))];
1315
+ // A turn quicker than a second has no time worth saying: `0s` reads as nothing happened.
1316
+ const parts = [took >= 1000 ? elapsed(took) : '', calls > 0 ? `${calls} call${calls === 1 ? '' : 's'}` : '', files.length > 0 ? `edited ${files.slice(0, 3).join(', ')}${files.length > 3 ? ` +${files.length - 3} more` : ''}` : '', state.tokens > 0 ? `↓ ${thousands(state.tokens)} tokens` : '', dollars(state.spent - before)];
1317
+ // The turn is over: reads still waiting for what comes after them go on the screen now.
1318
+ if (state.reads.length > 0) show([]);
687
1319
  if (calls > 0 || took >= notifyAfterMs) record({ kind: 'footer', text: parts.filter(Boolean).join(' · ') });
688
1320
  if (took >= notifyAfterMs) alert(`${state.where.name}: ${ended}`);
689
1321
  };
@@ -693,17 +1325,44 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
693
1325
  state.gone = true;
694
1326
  state.queue = [];
695
1327
  if (state.working) session.interrupt();
696
- else exit();
1328
+ else close();
1329
+ };
1330
+
1331
+ /** The screen let go: the box and the margin under it are cleared first, so what stays in the terminal is the conversation. */
1332
+ const close = () => {
1333
+ placeReads();
1334
+ state.closed = true;
1335
+ redraw();
1336
+ // The cleared frame is drawn before the screen lets go, however slow the machine: exit waits for it.
1337
+ waitUntilRenderFlush().then(() => exit(), () => exit());
697
1338
  };
698
1339
 
699
1340
  /** The user's answer to a call waiting on it; one answered already — by Esc, say — is left alone. */
700
1341
  const settle = (ask, answer) => {
701
1342
  if (!state.asks.includes(ask)) return;
702
1343
  state.asks = state.asks.filter((a) => a !== ask);
1344
+ if (state.why?.ask === ask) state.why = null;
1345
+ if (state.explain?.ask === ask) {
1346
+ clearTimeout(state.explain.timer);
1347
+ state.explain = null;
1348
+ }
703
1349
  ask.resolve(answer);
704
1350
  redraw();
705
1351
  };
706
1352
 
1353
+ /** A key that answers nothing on a waiting call: for a moment the panel says what each key does, in place of its keys. */
1354
+ const explainKeysOf = (ask) => {
1355
+ clearTimeout(state.explain?.timer);
1356
+ state.explain = {
1357
+ ask,
1358
+ timer: setTimeout(() => {
1359
+ state.explain = null;
1360
+ redraw();
1361
+ }, NOTICE_MS),
1362
+ };
1363
+ redraw();
1364
+ };
1365
+
707
1366
  /** Said under the box for a moment, in place of the hints: why a key did nothing. */
708
1367
  const notify = (text) => {
709
1368
  clearTimeout(state.notice?.timer);
@@ -745,65 +1404,120 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
745
1404
  return record({ kind: 'shell', result: { content: await session.shell(line.slice(1).trim()), isError: false } });
746
1405
  }
747
1406
  const { text, said, guide, control, args, error } = session.expand(line);
748
- if (error) return record({ kind: 'error', text: error });
1407
+ // A command mistyped is no failure: what was typed, and the command it was nearest to.
1408
+ if (error) {
1409
+ record({ kind: 'user', text: line });
1410
+ return record({ kind: 'note', text: error });
1411
+ }
749
1412
  if (control === 'quit') return leave();
750
- if (control === 'new') {
751
- session.end();
752
- state.log = [];
1413
+ if (control === 'new' || control === 'handoff') {
1414
+ // A hand-off is written first, by the model, while the working line says so; one that cannot be had leaves this session as it is.
1415
+ let handed = null;
1416
+ if (control === 'handoff') {
1417
+ record({ kind: 'user', text: line });
1418
+ state.working = 'writing the hand-off';
1419
+ state.talking = true;
1420
+ redraw();
1421
+ try {
1422
+ handed = await session.handoff();
1423
+ } finally {
1424
+ state.working = null;
1425
+ state.talking = false;
1426
+ }
1427
+ } else {
1428
+ session.end();
1429
+ }
753
1430
  // The old session's pictures go with it; their numbers stay taken, so a marker recalled from before names nothing.
754
1431
  state.images = state.images.map(() => null);
755
- const block = session.start('new');
1432
+ state.pastes = state.pastes.map(() => null);
1433
+ state.overBudget = false;
1434
+ const block = handed ? handed.block : session.start('new');
756
1435
  state.where = session.where();
757
1436
  state.spent = session.spent();
758
- refresh(scrolledClear(state.rows));
759
- return record(header(block));
1437
+ // The new session is in the log before the window is drawn again: one frame, measured under its header. A frame drawn
1438
+ // first for an empty window would be written after the header, still that tall, and scroll the header away.
1439
+ state.log = [header(block), ...(handed ? [{ kind: 'note', text: `handed off from ${handed.from}: the hand-off rides in with your next message\n${handed.text}` }] : [])];
1440
+ return refresh(scrolledClear(state.rows));
760
1441
  }
761
1442
  if (control === 'resume') {
762
1443
  record({ kind: 'user', text: line });
763
1444
  if (!args) {
764
1445
  const saved = session.saved();
765
- return record({ kind: 'note', text: saved.length > 0 ? saved.join('\n') : 'no saved sessions' });
1446
+ return record({ kind: 'note', text: saved.length > 0 ? `${saved.join('\n')}\nopen one with /resume <id>` : 'no saved sessions' });
766
1447
  }
767
1448
  // Refused — no such session, or one open elsewhere — nothing changes, and the refusal is shown below like any other error.
768
1449
  const said = session.resume(args);
769
- state.log = [];
770
1450
  state.images = state.images.map(() => null);
1451
+ state.pastes = state.pastes.map(() => null);
1452
+ state.overBudget = false;
771
1453
  state.where = session.where();
772
1454
  state.spent = session.spent();
773
- refresh(scrolledClear(state.rows));
774
- record(header(''));
775
1455
  // Where it stopped, drawn again: the last few turns, so what is picked up is in front of the user and not only the model.
776
- for (const entry of replayOf(session.params.messages)) record(entry);
777
- return record({ kind: 'note', text: said });
1456
+ // In the log before the window is drawn again, as for /new.
1457
+ state.log = [header(''), ...replayOf(session.params.messages), { kind: 'note', text: said }];
1458
+ return refresh(scrolledClear(state.rows));
778
1459
  }
779
1460
  if (control === 'copy') {
780
1461
  record({ kind: 'user', text: line });
781
- if (args && args !== 'code') return record({ kind: 'error', text: `/copy takes nothing, or "code" — not "${args}"` });
1462
+ // A number goes further back: /copy 2 is the reply before the last, /copy code 2 the code block before the last.
1463
+ const asked = /^(code)?\s*(\d+)?$/.exec(args);
1464
+ // What /copy cannot take, or has nothing to take, is no failure: it is said as a note.
1465
+ if (!asked || asked[2] === '0') return record({ kind: 'note', text: `/copy takes nothing, "code", a number, or both — /copy 2 is the reply before the last — not "${args}"` });
1466
+ const [, code, n] = asked;
1467
+ const back = Number(n ?? 1);
782
1468
  // The reply as the model wrote it, not as the screen drew it: no indent, no line broken to fit the window.
783
1469
  const replies = state.log.filter((entry) => entry.kind === 'reply' && !entry.own);
784
1470
  const blocks = replies.flatMap((entry) => [...entry.raw.matchAll(/^[ \t]*```[^\n]*\n([\s\S]*?)^[ \t]*```[ \t]*$/gm)].map((m) => m[1]));
785
- const text = (args === 'code' ? blocks.at(-1) : replies.at(-1)?.raw)?.replace(/\n+$/, '');
786
- if (!text) return record({ kind: 'error', text: args === 'code' ? 'no code block in the conversation yet' : 'no reply to copy yet' });
1471
+ const text = (code ? blocks.at(-back) : replies.at(-back)?.raw)?.replace(/\n+$/, '');
1472
+ const which = code ? (back === 1 ? 'the last code block' : `code block ${back} from the end`) : back === 1 ? 'the last reply' : `reply ${back} from the end`;
1473
+ if (!text) return record({ kind: 'note', text: back > 1 ? `no ${which} — there ${(code ? blocks : replies).length === 1 ? 'is' : 'are'} ${(code ? blocks : replies).length}` : code ? 'no code block in the conversation yet' : 'no reply to copy yet' });
787
1474
  // Where no clipboard command takes it, the terminal is asked to (OSC 52).
788
1475
  const taken = await copy(text);
789
1476
  if (!taken) tell(`\x1b]52;c;${Buffer.from(text).toString('base64')}\x07`);
790
1477
  const lines = text.split('\n').length;
791
- return record({ kind: 'note', text: `copied ${args === 'code' ? 'the last code block' : 'the last reply'} — ${lines} line${lines === 1 ? '' : 's'}${taken ? '' : ", through the terminal's clipboard"}` });
1478
+ return record({ kind: 'note', text: `copied ${which} — ${lines} line${lines === 1 ? '' : 's'}${taken ? '' : ", through the terminal's clipboard"}` });
1479
+ }
1480
+ if (control === 'context') {
1481
+ record({ kind: 'user', text: line });
1482
+ const turns = state.log.filter((entry) => entry.kind === 'user' && !/^[/!]/.test(entry.text)).length;
1483
+ const calls = state.log.filter((entry) => entry.kind === 'tool').length;
1484
+ return record({ kind: 'reply', raw: contextReport({ contextTokens: session.contextTokens, rows: session.usage(), turns, calls }), own: true });
1485
+ }
1486
+ if (control === 'thinking') {
1487
+ record({ kind: 'user', text: line });
1488
+ if (args !== 'on' && args !== 'off') return record({ kind: 'note', text: `thinking is ${state.showThinking ? 'shown' : 'hidden'} under the working line — /thinking on or /thinking off` });
1489
+ state.showThinking = args === 'on';
1490
+ return record({ kind: 'note', text: state.showThinking ? 'the model\'s thinking is shown under the working line' : 'the model\'s thinking is hidden — the pager (ctrl-o) still has it' });
1491
+ }
1492
+ if (control === 'export') {
1493
+ record({ kind: 'user', text: line });
1494
+ const file = exportPath(args, state.where.cwd, session.sessionId);
1495
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
1496
+ writeFileSync(file, markdownOf(state.log, { cwd: state.where.cwd, title: `Sumo — ${state.where.name}` }), { mode: 0o600 });
1497
+ // Named as the calls name files: from the project when it went there.
1498
+ return record({ kind: 'note', text: `the conversation is in ${pathFrom(file, state.where.cwd)}` });
792
1499
  }
1500
+ // The chat's own words, not the model's: not drawn as a reply, and not what /copy takes.
793
1501
  if (control === 'help') {
794
1502
  record({ kind: 'user', text: line });
795
- return record({ kind: 'reply', raw: helpText(session.commands), own: true });
1503
+ return record({ kind: 'help', rows: helpRows(session.commands) });
796
1504
  }
797
- if (control === 'model' || control === 'memory' || control === 'mcp' || control === 'undo') {
1505
+ // The route said as the status row says it, and how to change it.
1506
+ if (control === 'model') {
798
1507
  record({ kind: 'user', text: line });
799
- const text = control === 'model' ? session.route(args) : control === 'undo' ? session.undo() : control === 'mcp' ? (await session.mcp()).join('\n') : await session.memoryPage();
1508
+ session.route(args);
1509
+ return record({ kind: 'note', text: args ? `${routeLine(session)} from the next message` : `${routeLine(session)} · /model <model> <effort> changes it` });
1510
+ }
1511
+ if (control === 'memory' || control === 'mcp' || control === 'undo') {
1512
+ record({ kind: 'user', text: line });
1513
+ const text = control === 'undo' ? session.undo() : control === 'mcp' ? (await session.mcp()).join('\n') : await session.memoryPage();
800
1514
  return record({ kind: 'note', text });
801
1515
  }
802
1516
  record({ kind: 'user', text: line });
803
1517
  await modelTurn(() => session.say(text, said, images, { guide }));
804
1518
  } catch (cause) {
805
1519
  closeReply();
806
- record({ kind: 'error', text: `error: ${cause.message}` });
1520
+ record({ kind: 'error', ...explained(cause.message) });
807
1521
  } finally {
808
1522
  endTurn();
809
1523
  }
@@ -826,15 +1540,18 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
826
1540
  outcome = await run();
827
1541
  } catch (cause) {
828
1542
  closeReply();
829
- record({ kind: 'error', text: `error: ${cause.message}` });
1543
+ record({ kind: 'error', ...explained(cause.message) });
830
1544
  return closeTurn(began, before, 'stopped on an error');
831
1545
  }
1546
+ // A declined reply is not kept by the loop, and what streamed of it is not an answer: it leaves the screen as well.
1547
+ if (outcome?.stop === 'refusal') dropReply();
832
1548
  closeReply();
833
1549
  // Nothing was waiting after all: no turn was run.
834
1550
  if (!outcome) return undefined;
835
- if (outcome.stop === 'interrupted') record({ kind: 'note', text: 'Interrupted' });
836
- if (outcome.stop === 'error') record({ kind: 'error', text: `error: ${outcome.error}` });
837
- if (stopReason(outcome.stop)) record({ kind: 'note', text: stopReason(outcome.stop) });
1551
+ if (outcome.stop === 'interrupted') record({ kind: 'note', text: 'Interrupted · say what it should do instead' });
1552
+ if (outcome.stop === 'error') record({ kind: 'error', ...explained(outcome.error) });
1553
+ if (outcome.stop === 'refusal') record({ kind: 'error', text: `error: the model declined to answer${outcome.stopDetail ? ` (${outcome.stopDetail})` : ''} — rephrase the request, or /model to try another model` });
1554
+ else if (stopReason(outcome.stop, outcome.stopDetail)) record({ kind: 'note', text: stopReason(outcome.stop, outcome.stopDetail) });
838
1555
  return closeTurn(began, before, outcome.stop === 'error' ? 'stopped on an error' : outcome.stop === 'interrupted' ? 'interrupted' : 'done');
839
1556
  }
840
1557
 
@@ -847,11 +1564,16 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
847
1564
  state.live.clear();
848
1565
  for (const id of [...state.jobs.keys()]) if (!aside.includes(id)) state.jobs.delete(id);
849
1566
  dropEnded();
1567
+ thoughtDone();
850
1568
  state.working = null;
851
1569
  state.talking = false;
852
1570
  state.thought = '';
1571
+ // The plan and a countdown were the turn's: the next one starts without them.
1572
+ state.plan = null;
1573
+ state.retry = null;
1574
+ state.retried = null;
853
1575
  redraw();
854
- if (state.gone) exit();
1576
+ if (state.gone) close();
855
1577
  }
856
1578
 
857
1579
  /** A turn nobody typed: what the background jobs reported, read by the model as soon as it is free to. */
@@ -860,7 +1582,7 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
860
1582
  await modelTurn(() => session.wake());
861
1583
  } catch (cause) {
862
1584
  closeReply();
863
- record({ kind: 'error', text: `error: ${cause.message}` });
1585
+ record({ kind: 'error', ...explained(cause.message) });
864
1586
  } finally {
865
1587
  endTurn();
866
1588
  }
@@ -882,15 +1604,18 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
882
1604
  function stopJob(line, given) {
883
1605
  record({ kind: 'user', text: line });
884
1606
  const ids = session.running();
885
- if (ids.length === 0) return record({ kind: 'error', text: 'no job is at work in the background' });
1607
+ // No job to stop, or which one, is a note: nothing went wrong.
1608
+ if (ids.length === 0) return record({ kind: 'note', text: 'no job is at work in the background' });
886
1609
  const id = given ? Number(/^j?(\d+)$/.exec(given)?.[1]) : ids.length === 1 ? ids[0] : NaN;
887
- if (!ids.includes(id)) return record({ kind: 'error', text: `which one — ${ids.map((j) => `/stop j${j}`).join(' or ')}` });
1610
+ if (!ids.includes(id)) return record({ kind: 'note', text: `which one — ${ids.map((j) => `/stop j${j}`).join(' or ')}` });
888
1611
  session.stop(id);
889
1612
  return record({ kind: 'note', text: `stopping j${id} — it can be picked up again: ask for it by its id` });
890
1613
  }
891
1614
 
892
1615
  /** What was typed: now if nothing is running, after the turn in hand if something is. */
893
- async function submit(line) {
1616
+ async function submit(typed) {
1617
+ // A long paste stood in the box as a marker; what is sent is the paste itself.
1618
+ const line = typed.replace(/\[Pasted text #(\d+)[^\]\n]*\]/g, (marker, n) => state.pastes[n - 1] ?? marker);
894
1619
  keepHistory(line);
895
1620
  const asked = line.startsWith('/') ? session.expand(line) : {};
896
1621
  if (asked.control === 'stop') return stopJob(line, asked.args);
@@ -978,7 +1703,7 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
978
1703
  writeFileSync(file, state.ed.text, { mode: 0o600 });
979
1704
  if (!(await handOver(process.env.VISUAL || process.env.EDITOR || 'vi', file, 'the editor'))) return;
980
1705
  const text = readFileSync(file, 'utf8').replace(/\r\n?/g, '\n').replace(/\n+$/, '');
981
- state.ed = { ...editor(state.ed.history), text, cursor: text.length };
1706
+ state.ed = { ...editor(state.ed.history, state.ed.kill), text, cursor: text.length };
982
1707
  } catch (cause) {
983
1708
  notify(cause.message);
984
1709
  } finally {
@@ -998,7 +1723,7 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
998
1723
  mkdirSync(paths().logs, { recursive: true, mode: 0o700 });
999
1724
  const live = state.raw ? [{ kind: 'reply', raw: state.raw }] : [];
1000
1725
  // What a job wrote is shown, never obeyed: its record goes to the pager as it goes to the screen.
1001
- const text = state.open === null ? transcript([...state.log, ...live], s, { width: state.columns, cwd: state.where.cwd }) : safeForTerminal(readFileSync(liveFile(state.open), 'utf8'));
1726
+ const text = state.open === null ? transcript([...state.log, ...live], paged, { width: state.columns, cwd: state.where.cwd }) : safeForTerminal(readFileSync(liveFile(state.open), 'utf8'));
1002
1727
  writeFileSync(file, text, { mode: 0o600 });
1003
1728
  // Opened at its end: what was asked about is nearly always the last thing that happened.
1004
1729
  await handOver(process.env.PAGER || 'less -R +G', file, 'the pager');
@@ -1009,39 +1734,104 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1009
1734
  }
1010
1735
  };
1011
1736
 
1737
+ /**
1738
+ * Ctrl-Z: the chat stopped and the shell given back, as any program in a terminal is; `fg` brings it back drawn. Not while
1739
+ * anything is at work: a turn or a job stopped with the process would hold its command, or its API request, half done.
1740
+ */
1741
+ const suspend = async () => {
1742
+ if (state.away) return;
1743
+ if (process.platform === 'win32') return notify('ctrl-z does not suspend on Windows');
1744
+ if (state.working || session.running().length > 0) return notify('ctrl-z waits until nothing is at work — esc interrupts the turn');
1745
+ state.away = true;
1746
+ let stopped = true;
1747
+ try {
1748
+ tell(FOCUS_OFF);
1749
+ await suspendTerminal(
1750
+ () =>
1751
+ new Promise((resolve) => {
1752
+ // The timer keeps the process alive while it waits — the screen has let go of the keyboard, the one thing that did —
1753
+ // and tells a stop that never came, as under a parent with no job control, from one that did.
1754
+ const began = Date.now();
1755
+ let continued = false;
1756
+ const done = () => {
1757
+ clearTimeout(check);
1758
+ process.off('SIGCONT', woke);
1759
+ stopped = continued || Date.now() - began >= SUSPEND_CHECK_MS * 3;
1760
+ resolve();
1761
+ };
1762
+ const woke = () => {
1763
+ continued = true;
1764
+ done();
1765
+ };
1766
+ const check = setTimeout(done, SUSPEND_CHECK_MS);
1767
+ process.once('SIGCONT', woke);
1768
+ process.kill(process.pid, 'SIGTSTP');
1769
+ }),
1770
+ );
1771
+ } finally {
1772
+ tell(FOCUS_ON);
1773
+ state.away = false;
1774
+ refresh();
1775
+ }
1776
+ if (!stopped) notify('ctrl-z: there is no shell here to suspend the chat into');
1777
+ };
1778
+
1012
1779
  /** What is waiting — to be read at the next step, or sent after the turn — back in the box, ahead of what is typed there; the model reads none of it. */
1013
1780
  const takeBack = (entries) => {
1014
1781
  for (const entry of entries) if (entry.steer) session.unsteer(entry.line);
1015
1782
  state.queue = state.queue.filter((entry) => !entries.includes(entry));
1016
1783
  const text = [...entries.map((entry) => entry.line), state.ed.text].filter(Boolean).join('\n');
1017
- state.ed = { ...editor(state.ed.history), text, cursor: text.length };
1784
+ state.ed = { ...editor(state.ed.history, state.ed.kill), text, cursor: text.length };
1018
1785
  };
1019
1786
 
1020
1787
  useEffect(() => {
1021
1788
  const onText = (chunk) => {
1789
+ thoughtDone();
1022
1790
  state.heard = Date.now();
1023
1791
  // The reply has begun: what was thought before it is no longer the news.
1024
1792
  state.thought = '';
1025
1793
  state.raw += chunk;
1026
1794
  state.reply?.write(chunk);
1795
+ // A checklist in the reply is the plan the turn works to: the latest one, under the working line.
1796
+ state.plan = planOf(state.raw) ?? state.plan;
1797
+ // Text came: a request sent again has gone through.
1798
+ state.retry = null;
1027
1799
  redraw();
1028
1800
  };
1029
1801
  // What the model is thinking, so far: shown under the working line until it acts. A job's thought is its own: it is not drawn here.
1030
1802
  const onThinking = ({ text, job }) => {
1031
1803
  if (job) return;
1804
+ state.thinking ??= Date.now();
1032
1805
  state.thought = text;
1033
1806
  state.heard = Date.now();
1034
1807
  redraw();
1035
1808
  };
1036
1809
  // A request being sent again, or a job's conversation summarized to make room: said where the work shows, with the job's id.
1037
- const onRetry = (r) => record({ kind: 'note', text: `${r.job ? `j${r.job}: ` : ''}${retryLine(r)}` });
1810
+ // A request of the chat's own being sent again counts down on the working line; the scroll says why, in words — once
1811
+ // for a run of tries that fail the same way, again when the reason changes. A reply that broke off half-way is thrown
1812
+ // away, as the loop throws it away, and the scroll says so.
1813
+ const onRetry = (r) => {
1814
+ if (r.job) return record({ kind: 'note', text: `j${r.job}: ${retryNote(r)}` });
1815
+ state.retry = { until: Date.now() + r.delayMs, attempt: r.attempt, limit: r.limit };
1816
+ const broke = Boolean(state.raw);
1817
+ if (broke) dropReply();
1818
+ const why = retryWhy(r.reason);
1819
+ const said = broke ? `the reply broke off: ${why} · asking again` : retryNote(r);
1820
+ if (state.retried === `${broke}${why}`) return redraw();
1821
+ state.retried = `${broke}${why}`;
1822
+ record({ kind: 'note', text: said });
1823
+ };
1038
1824
  const onCompact = (c) => record({ kind: 'note', text: `${c.job ? `j${c.job}: ` : ''}${compactLine(c)}` });
1039
1825
  // The session has passed what it may cost before it is said: said once, where the retries are.
1040
- const onBudget = ({ text }) => record({ kind: 'note', text });
1826
+ const onBudget = ({ text }) => {
1827
+ state.overBudget = true;
1828
+ record({ kind: 'note', text });
1829
+ };
1041
1830
  const onTool = ({ call, job }) => {
1042
1831
  const at = state.jobs.get(job);
1043
1832
  if (at) at.calls++;
1044
1833
  else if (!job) {
1834
+ thoughtDone();
1045
1835
  state.thought = '';
1046
1836
  closeReply();
1047
1837
  state.running.set(call.id, call);
@@ -1083,29 +1873,44 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1083
1873
  closeReply();
1084
1874
  record({ kind: 'note', text: `sources:\n${sources.map((page) => safeForTerminal(`${page.title} — ${page.url}`).replace(/\s+/g, ' ')).join('\n')}` });
1085
1875
  };
1876
+ // The turn goes on once: what it edited, what has not checked it, and what the model is asked to do about that.
1086
1877
  const onCheck = ({ edited, checks }) => {
1087
1878
  closeReply();
1088
- record({ kind: 'note', text: `held: ${edited.length} file${edited.length === 1 ? '' : 's'} edited, ${checks.length > 0 ? `${checks.join(' and ')} not run` : 'no check declared'}` });
1879
+ const what = edited.length === 1 ? basename(edited[0]) : `${edited.length} files`;
1880
+ const them = edited.length === 1 ? 'it' : 'them';
1881
+ record({ kind: 'note', text: checks.length > 0 ? `${what} edited, ${checks.join(' and ')} not run since · the model is asked to run ${checks.length === 1 ? 'it' : 'them'}` : `${what} edited and not checked yet · the model is asked to check ${them}` });
1089
1882
  };
1090
1883
  // A job's work is not the chat's: it shows one line while it works, its report when it ends, and the rest where it is watched.
1091
1884
  const onResult = ({ call, result, job }) => {
1092
1885
  if (job) return;
1093
1886
  // Delegated jobs run side by side: one ending leaves the others' calls on the screen.
1887
+ const took = state.live.has(call.id) ? Date.now() - state.live.get(call.id).since : 0;
1094
1888
  state.running.delete(call.id);
1095
1889
  state.live.delete(call.id);
1096
1890
  state.heard = Date.now();
1097
1891
  if (state.turn && call.name === EDITOR_TOOL.name && call.input?.command !== 'view' && !result.isError) state.turn.edited.add(pathFrom(call.input?.path ?? '', state.where.cwd));
1098
- record({ kind: 'tool', call, result });
1892
+ const started = state.started.get(call.id) ?? [];
1893
+ state.started.delete(call.id);
1894
+ record({ kind: 'tool', call, result, took, started });
1099
1895
  };
1100
1896
  const onJob = ({ job, call = null, tab = null }) => {
1101
- state.jobs.set(job.id, { parent: call, calls: 0, since: Date.now(), agent: job.agent, title: job.title, route: routeOf(job) });
1102
1897
  const where = tab?.pane ? 'working in its Herdr tab' : tab?.error ? `no Herdr tab (${tab.error}) — sumo job watch ${job.id}` : `follow it: sumo job watch ${job.id}`;
1103
- record({ kind: 'job', id: job.id, agent: job.agent, title: job.title, route: routeOf(job), where });
1898
+ const info = { id: job.id, agent: job.agent, title: job.title, route: routeOf(job), where };
1899
+ state.jobs.set(job.id, { parent: call, calls: 0, since: Date.now(), agent: job.agent, title: job.title, route: info.route, where });
1900
+ state.known.set(job.id, info);
1901
+ // Started by a call still on the screen: it is told under that call, at work and once the call is answered.
1902
+ if (call && state.running.has(call)) {
1903
+ state.started.set(call, [...(state.started.get(call) ?? []), info]);
1904
+ return redraw();
1905
+ }
1906
+ record({ kind: 'job', ...info });
1104
1907
  };
1105
1908
  // A job in the background has reported: how it went is drawn where the conversation has got to, and the model reads the
1106
1909
  // report with its next request — or, when nothing is at work, in a turn started here for it. One the user stopped starts none.
1107
- const onJobReport = ({ job, result }) => {
1108
- record({ kind: 'tool', call: { id: `report-${job}`, name: DELEGATE_TOOL.name, input: { job } }, result });
1910
+ const onJobReport = ({ job, result, quiet = false }) => {
1911
+ const known = state.known.get(job);
1912
+ // A job the user stopped is said to be stopped, not left open.
1913
+ record({ kind: 'tool', call: { id: `report-${job}`, name: DELEGATE_TOOL.name, input: { job, report: true, agent: known?.agent, title: known?.title, stopped: Boolean(quiet) } }, result });
1109
1914
  alert(`${state.where.name}: j${job} has reported`);
1110
1915
  if (!state.working) drain();
1111
1916
  };
@@ -1117,6 +1922,8 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1117
1922
  redraw();
1118
1923
  };
1119
1924
  const onUsage = ({ totals }) => {
1925
+ // A reply came back: a request that fails after it is a new run of tries, and its reason is said again.
1926
+ state.retried = null;
1120
1927
  state.tokens = totals.outputTokens;
1121
1928
  state.heard = Date.now();
1122
1929
  state.spent = session.spent();
@@ -1126,7 +1933,7 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1126
1933
  const onApprove = (ask) => {
1127
1934
  state.asks.push(ask);
1128
1935
  ask.signal?.addEventListener('abort', () => settle(ask, 'no'), { once: true });
1129
- alert(`${state.where.name}: ${ask.unsandboxed ? 'a command waits to run outside the sandbox' : `${ask.server} · ${ask.tool} waits for your answer`}`);
1936
+ alert(`${state.where.name}: ${ask.unsandboxed ? 'a command waits to run outside the sandbox' : ask.path ? 'a change to a file waits for your answer' : `${ask.server} · ${ask.tool} waits for your answer`}`);
1130
1937
  redraw();
1131
1938
  };
1132
1939
  // A question of the model's: shown with its options, the first one picked, until a pick or a typed answer settles it.
@@ -1147,15 +1954,31 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1147
1954
  events.off('text', onText).off('thinking', onThinking).off('retry', onRetry).off('compact', onCompact).off('budget', onBudget).off('tool', onTool).off('output', onOutput).off('heard', onHeard).off('guide', onGuide).off('sources', onSources).off('check', onCheck).off('result', onResult).off('usage', onUsage).off('job', onJob).off('tab-failed', onTabFailed).off('job-end', onJobEnd).off('job-report', onJobReport).off('approve', onApprove).off('ask', onAsk).off('mcp', onMcp);
1148
1955
  clearTimeout(state.leaving);
1149
1956
  clearTimeout(state.notice?.timer);
1957
+ clearTimeout(state.explain?.timer);
1150
1958
  clearTimeout(state.drawSoon);
1151
1959
  // The terminal as it was found: no more word of its focus, and its own title back.
1152
1960
  tell(`${FOCUS_OFF}${TITLE_BACK}`);
1153
1961
  };
1154
1962
  }, []);
1155
1963
 
1964
+ // The tab's progress mark follows the work: busy from the first word sent to the last, and cleared when the chat closes.
1965
+ const busy = Boolean(state.working) && state.asks.length === 0;
1966
+ const marked = useRef(false);
1967
+ useEffect(() => {
1968
+ if (!progress || marked.current === busy) return;
1969
+ marked.current = busy;
1970
+ tell(busy ? PROGRESS_BUSY : PROGRESS_DONE);
1971
+ }, [busy]);
1972
+ useEffect(
1973
+ () => () => {
1974
+ if (marked.current) tell(PROGRESS_DONE);
1975
+ },
1976
+ [],
1977
+ );
1978
+
1156
1979
  // The window's title says whose chat it is and what it is doing, for a glance at the tab bar: at work, or waiting for an answer.
1157
1980
  useEffect(() => {
1158
- const title = `${state.asks.length > 0 ? '? ' : state.working ? '✳ ' : ''}sumo · ${state.where.name}`;
1981
+ const title = `${state.asks.length > 0 ? '? ' : state.working ? '• ' : ''}sumo · ${state.where.name}`;
1159
1982
  if (title === state.title) return;
1160
1983
  state.title = title;
1161
1984
  tell(`\x1b]2;${safeForTerminal(title)}\x07`);
@@ -1184,27 +2007,50 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1184
2007
  useInput((input, key) => {
1185
2008
  // The terminal's answer to Ink's keyboard-protocol query, when it comes after Ink stopped waiting for it.
1186
2009
  if (/^\[\?\d+u$/.test(input)) return;
1187
- // The terminal saying its window came to the front, or went behind: not something typed.
1188
- if (input === '[I' || input === '[O') {
1189
- state.focused = input === '[I';
1190
- return;
1191
- }
1192
2010
  for (const [one, oneKey] of keysOf(input, key)) {
1193
- // A question of the model's: on an empty box the arrows move the pick and Enter takes it. Anything else is the box's,
1194
- // and Enter there sends what was typed as the answer; Esc and Ctrl-C go on to stop the turn.
2011
+ // Ctrl-R looking back through what was sent takes every key, Esc and Ctrl-C too: they put the draft back, and stop nothing.
2012
+ if (state.ed.search) {
2013
+ state.ed = press(state.ed, one, oneKey, session.commands, files).state;
2014
+ continue;
2015
+ }
2016
+ // The keys, shown for `?` on an empty box until the next key — which goes on to do what it does, but Esc, which only closes them.
2017
+ if (state.keys) {
2018
+ state.keys = false;
2019
+ if (oneKey.escape || one === '?') continue;
2020
+ } else if (one === '?' && !state.ed.text && !oneKey.ctrl && !oneKey.meta && state.asks.length === 0 && state.pick === null) {
2021
+ state.keys = true;
2022
+ continue;
2023
+ }
2024
+ // A question of the model's: on an empty box the arrows move the pick and Enter takes it, or a number picks that option.
2025
+ // Anything else is the box's, and Enter there sends what was typed as the answer; Esc and Ctrl-C go on to stop the turn.
1195
2026
  const asked = state.asks[0]?.options ? state.asks[0] : null;
2027
+ if (asked && !state.ed.text && /^[1-9]$/.test(one) && Number(one) <= asked.options.length && !oneKey.ctrl && !oneKey.meta) {
2028
+ settle(asked, { label: asked.options[Number(one) - 1].label });
2029
+ continue;
2030
+ }
1196
2031
  if (asked && !state.ed.text && (oneKey.upArrow || oneKey.downArrow || (oneKey.return && !oneKey.shift && !oneKey.meta))) {
1197
2032
  if (oneKey.return) settle(asked, { label: asked.options[asked.at].label });
1198
2033
  else asked.at = Math.max(0, Math.min(asked.options.length - 1, asked.at + (oneKey.downArrow ? 1 : -1)));
1199
2034
  continue;
1200
2035
  }
2036
+ // Saying why a call is refused: the keys write the line, Enter refuses with it, Esc goes back to the question. Ctrl-C still stops.
2037
+ if (state.why && state.why.ask === state.asks[0] && !(oneKey.ctrl && (one === 'c' || one === 'd'))) {
2038
+ if (oneKey.escape) state.why = null;
2039
+ else if (oneKey.return) settle(state.why.ask, state.why.text.trim() ? { no: state.why.text.trim() } : 'no');
2040
+ else if (oneKey.backspace || oneKey.delete) state.why.text = state.why.text.slice(0, -1);
2041
+ else if (!oneKey.ctrl && !oneKey.meta && one) state.why.text += one.replace(/[\r\n]+/g, ' ');
2042
+ redraw();
2043
+ continue;
2044
+ }
1201
2045
  // A call standing takes the key: an answer, or Esc and Ctrl-C, which go on to stop the turn; nothing lands in the box.
1202
2046
  if (!asked && state.asks.length > 0 && !oneKey.escape && !(oneKey.ctrl && (one === 'c' || one === 'd'))) {
1203
- // A run outside the sandbox is this one run or none: there is no always for it.
1204
- const unsandboxed = state.asks[0].unsandboxed;
1205
- const answer = (unsandboxed ? { y: 'once', n: 'no' } : { y: 'once', a: 'always', n: 'no' })[one];
1206
- if (answer) settle(state.asks[0], answer);
1207
- else notify(unsandboxed ? 'y runs it once outside the sandbox · n refuses it · esc stops the turn' : 'y allows it once · a always · n refuses it · esc stops the turn');
2047
+ // Each kind of call takes its own keys: a run outside the sandbox is this one run or none, a guarded file this once or not.
2048
+ const answer = answerOf(state.asks[0], one);
2049
+ if (answer === 'why') {
2050
+ state.why = { ask: state.asks[0], text: '' };
2051
+ redraw();
2052
+ } else if (answer) settle(state.asks[0], answer);
2053
+ else explainKeysOf(state.asks[0]);
1208
2054
  continue;
1209
2055
  }
1210
2056
  // A question from a job in the background: Esc refuses that one call, and stops nothing.
@@ -1230,8 +2076,9 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1230
2076
  // What is nearest goes first: Ctrl-C clears what is typed, Esc closes the menu, and only then is the turn stopped.
1231
2077
  // A menu of files is shut without a word of the message lost; a command half typed is all there is to lose.
1232
2078
  const open = oneKey.escape ? menuOf(state.ed, session.commands, files) : [];
1233
- if (oneKey.ctrl && state.ed.text) state.ed = editor(state.ed.history);
1234
- else if (open.length > 0) state.ed = open[0].file ? { ...state.ed, shut: state.ed.text } : editor(state.ed.history);
2079
+ // What Ctrl-C clears is not lost: Up brings it back, and so does Ctrl-Y.
2080
+ if (oneKey.ctrl && state.ed.text) state.ed = editor([...state.ed.history, state.ed.text], state.ed.text);
2081
+ else if (open.length > 0) state.ed = open[0].file ? { ...state.ed, shut: state.ed.text } : editor(state.ed.history, state.ed.kill);
1235
2082
  else if (state.working) {
1236
2083
  // Stopping the turn stops what was waiting on it too: it comes back to the box, to be sent again or not.
1237
2084
  takeBack([...state.queue]);
@@ -1254,6 +2101,15 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1254
2101
  openPager();
1255
2102
  continue;
1256
2103
  }
2104
+ // Ctrl-L: everything drawn again, for a screen something else wrote over.
2105
+ if (oneKey.ctrl && one === 'l') {
2106
+ refresh();
2107
+ continue;
2108
+ }
2109
+ if (oneKey.ctrl && one === 'z') {
2110
+ suspend();
2111
+ continue;
2112
+ }
1257
2113
  if (oneKey.ctrl && one === 'g') {
1258
2114
  openEditor();
1259
2115
  continue;
@@ -1286,6 +2142,12 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1286
2142
  });
1287
2143
  // A file dropped on the terminal arrives pasted as its path: an image's path becomes the image.
1288
2144
  usePaste((text) => {
2145
+ // Saying why a call is refused, a paste is part of the reason — on one line — and never lands in the box behind it.
2146
+ if (state.why && state.why.ask === state.asks[0]) {
2147
+ state.why.text += cleanPaste(text).text.replace(/\s+/g, ' ');
2148
+ redraw();
2149
+ return;
2150
+ }
1289
2151
  let images;
1290
2152
  try {
1291
2153
  images = droppedImages(text);
@@ -1293,52 +2155,94 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1293
2155
  return notify(cause.message);
1294
2156
  }
1295
2157
  if (images) for (const image of images) attach(image);
1296
- else state.ed = paste(state.ed, text);
2158
+ else {
2159
+ // What nobody can see in a paste — a direction override, a hidden tag — never reaches the model unseen.
2160
+ const { text: clean, removed } = cleanPaste(text);
2161
+ if (removed > 0) notify(`${removed} hidden character${removed === 1 ? '' : 's'} taken out of the paste`);
2162
+ const lines = clean.replace(/\r\n?/g, '\n').split('\n').length;
2163
+ if (lines > PASTE_LINES || clean.length > PASTE_CHARS) {
2164
+ // A long paste stands as a marker the box can hold; it goes whole with the message, and Backspace takes it out whole.
2165
+ state.pastes.push(clean.replace(/\r\n?/g, '\n'));
2166
+ state.ed = paste(state.ed, `[Pasted text #${state.pastes.length} ${lines > 1 ? `+${lines} lines` : `${clean.length} chars`}] `);
2167
+ } else state.ed = paste(state.ed, clean);
2168
+ }
1297
2169
  redraw();
1298
2170
  });
1299
2171
 
2172
+ if (state.closed) return h(Box, { flexDirection: 'column' }, h(Static, { key: state.epoch, items: state.items }, (item) => h(Item, { key: item.id, item, columns, s })));
1300
2173
  const menu = menuOf(state.ed, session.commands, files);
1301
2174
  const tail = state.reply?.tail ?? '';
1302
2175
  // The jobs the turn waits on: the ones whose call is still out. A job in the background holds nothing up.
1303
2176
  const atWork = [...state.jobs].filter(([, job]) => state.running.has(job.parent)).map(([id]) => `j${id}`);
1304
2177
  const reading = atWork.length === 0 ? 'next step' : `when ${atWork.join(', ')} report${atWork.length === 1 ? 's' : ''}`;
2178
+ // Once something has been said, the room is the conversation's: no logo, and no word in the box of what it is for.
2179
+ const said = state.log.some((entry) => entry.kind === 'user');
1305
2180
  // Ink adds a line under the frame; a frame that reached the last row would be drawn as a full screen.
1306
2181
  const room = state.unmeasured.length > 0 ? 0 : Math.max(0, rows - state.used - 1);
2182
+ // Reads that wait for what comes after them, drawn as the row they will make.
2183
+ const reads = state.reads.length > 0 ? readsDrawn(state.reads).map((item, i) => ({ after: i === 0 ? state.items.at(-1)?.kind : 'tool', ...item })) : [];
2184
+ // What runs now, and under a delegate call the jobs it started.
2185
+ // A question of the model's is said once, in its own rows under the work: the call that asks it is not drawn over it.
2186
+ const steps = [...state.running.values()]
2187
+ .filter((call) => !(call.name === ASK_TOOL.name && state.asks[0]?.options))
2188
+ .map((call, i) => ({ key: call.id, columns, s, view: toolView(call, null, { cwd: state.where.cwd }), running: true, tight: i > 0 || (!tail && STEP_KINDS.has(state.reads.length > 0 ? 'tool' : state.items.at(-1)?.kind)), waiting: state.asks.some((a) => !a.options && !a.job && (!a.name || a.name === call.name)), live: state.live.get(call.id), since: state.live.get(call.id)?.since ?? 0, jobs: [...state.jobs].filter(([, job]) => job.parent === call.id) }));
2189
+ // A question to approve takes the rows the window has left — less the work over it and what stands under it — and never
2190
+ // more: a frame that filled the window would have Ink wipe the screen and its scrollback to draw it. Counted from the
2191
+ // same layout the rows are drawn from; a line of a reply still arriving is counted as it would fold, never fewer.
2192
+ const approving = state.asks.length > 0 && !state.asks[0].options;
2193
+ const recorded = approving && state.open !== null ? recordLines(state.open).length : 0;
2194
+ const over = approving
2195
+ ? reads.reduce((sum, item) => sum + stepRowCount({ ...item, tight: STEP_KINDS.has(item.after), columns, s }, s.g), 0) +
2196
+ (tail ? (state.fresh ? 1 : 0) + wrap(untab(tail), Math.max(10, columns - TEXT_AT - 1)).split('\n').length : 0) +
2197
+ steps.reduce((sum, step) => sum + stepRowCount(step, s.g), 0)
2198
+ : 0;
2199
+ const under = approving ? (state.open !== null ? 2 + Math.min(Math.max(1, recorded), openRows(rows)) + (recorded > openRows(rows) ? 1 : 0) : 0) + (said ? 0 : STARTER_ROWS - 1) + 2 + state.queue.length + rowsUnderBox().length : 0;
2200
+ const asked = approving ? rows - 1 - over - under : null;
1307
2201
  return h(
1308
2202
  Box,
1309
2203
  { flexDirection: 'column', minHeight: room },
1310
- h(Static, { key: state.epoch, items: state.items }, (item) => h(Item, { key: item.id, item, columns })),
1311
- tail ? h(Reply, { text: tail, first: state.fresh }) : null,
1312
- // What runs now, and under a delegate call the jobs it started. In one box of their own, so the lines coming and going
1313
- // never move what follows — the working line keeps its clock.
1314
- h(
1315
- Box,
1316
- { flexDirection: 'column' },
1317
- ...[...state.running.values()].map((call) => h(Tool, { key: call.id, columns, view: toolView(call, null, { cwd: state.where.cwd }), running: true, live: state.live.get(call.id), jobs: [...state.jobs].filter(([, job]) => job.parent === call.id) })),
1318
- // A job no call here started — none should be — still shows that it works.
1319
- ),
2204
+ h(Static, { key: state.epoch, items: state.items }, (item) => h(Item, { key: item.id, item, columns, s })),
2205
+ ...reads.map((item, i) => h(Item, { key: `reads-${i}`, item, columns, s })),
2206
+ tail ? h(Reply, { text: tail, first: state.fresh, columns }) : null,
2207
+ // In one box of their own, so the lines coming and going never move what follows — the working line keeps its clock.
2208
+ h(Box, { flexDirection: 'column' }, ...steps.map((step) => h(Tool, step))),
1320
2209
  // The silence that is said is the model's: while a command, a job or a question is in hand, the wait is not on it.
1321
- state.working ? h(Working, { messages, first: state.working, tokens: state.tokens, thought: state.thought, quietAfterMs, heard: state.talking && state.running.size === 0 && state.jobs.size === 0 && state.asks.length === 0 ? state.heard : 0 }) : null,
1322
- state.asks.length > 0 ? (state.asks[0].options ? h(Question, { ask: state.asks[0] }) : h(Ask, { ask: state.asks[0], aside: session.running().includes(state.asks[0].job) })) : null,
2210
+ state.working ? h(Working, { messages, first: state.working, tokens: state.tokens, thought: state.showThinking ? state.thought : '', quietAfterMs, motion, retry: state.retry, plan: state.plan, heard: state.talking && state.running.size === 0 && state.jobs.size === 0 && state.asks.length === 0 ? state.heard : 0, waiting: state.asks.length > 0 }) : null,
2211
+ state.asks.length > 0 ? (state.asks[0].options ? h(Question, { ask: state.asks[0], columns }) : h(Ask, { ask: state.asks[0], aside: session.running().includes(state.asks[0].job), waiting: state.asks.length, why: state.why?.ask === state.asks[0] ? state.why.text : null, explain: state.explain?.ask === state.asks[0], columns, cwd: state.where.cwd, rows: asked })) : null,
1323
2212
  // The record of the job that is open, under everything the turn is doing: its end, as it grows.
1324
- state.open !== null ? h(JobOpen, { id: state.open, job: state.jobs.get(state.open), rows }) : null,
1325
- // The logo is the empty room's: once something has been said, the room is the conversation's.
1326
- h(Room, { logo: state.log.some((entry) => entry.kind === 'user') ? [] : logo, rows, from: state.used }),
2213
+ state.open !== null ? h(JobOpen, { id: state.open, job: state.jobs.get(state.open), rows, columns }) : null,
2214
+ // The logo and what to try are the empty room's: once something has been said, the room is the conversation's.
2215
+ h(Room, { logo: said ? [] : logo, rows, from: state.used, starter: !said }),
1327
2216
  h(
1328
2217
  Box,
1329
2218
  { flexDirection: 'column', marginTop: 1 },
1330
2219
  // A message for the model is read with its next request — which, while it waits on a delegated job, is when that job reports.
1331
- ...state.queue.map(({ line, steer }, i) => h(Text, { key: i, dimColor: true, wrap: 'truncate' }, ` ${steer ? reading : 'queued'}: ${line.split('\n')[0]}${line.includes('\n') ? ' …' : ''}`)),
1332
- h(Input, { state: state.ed, width: columns, rows }),
2220
+ ...state.queue.map(({ line, steer }, i) => h(Text, { key: i, dimColor: true, wrap: 'truncate' }, `${(steer ? 'next' : 'queued').padStart(GUTTER)} ${steer && atWork.length > 0 ? `${reading} · ` : ''}${line.split('\n')[0]}${line.includes('\n') ? ' …' : ''}`)),
2221
+ // While a call waits on the user's word every key is the answer's: no box stands there to type into.
2222
+ state.asks.length > 0 && !state.asks[0].options ? null : h(Input, { state: state.ed, width: columns, rows, placeholder: said ? '' : 'Ask anything · / commands · @ files · ? keys' }),
1333
2223
  // The jobs at work in the background, under the box, and the chat over them: they go on whether or not there is a turn.
1334
2224
  ...rowsUnderBox().map((id) => (id === MAIN ? h(MainAtWork, { key: MAIN, working: Boolean(state.working), picked: state.pick === MAIN, shown: state.open === null }) : h(JobAtWork, { key: `j${id}`, id, job: state.jobs.get(id), alone: true, picked: id === state.pick, open: id === state.open }))),
1335
- menu.length > 0 ? h(Menu, { menu, pick: state.ed.pick }) : h(Status, { session, leaving: Boolean(state.leaving), notice: state.notice?.text, jobs: [...state.jobs.keys()], aside: session.running(), pick: state.pick, open: state.open, where: state.where, spent: state.spent, waiting: state.queue.length > 0, columns }),
2225
+ menu.length > 0 ? h(Menu, { menu, pick: state.ed.pick, columns }) : state.ed.search ? h(Search, { search: state.ed.search }) : state.keys ? h(Keys, { columns }) : h(Status, { session, leaving: Boolean(state.leaving), notice: state.notice?.text, jobs: [...state.jobs.keys()], aside: session.running(), pick: state.pick, open: state.open, where: state.where, spent: state.spent, overBudget: state.overBudget, waiting: state.queue.length > 0, columns }),
1336
2226
  ),
1337
2227
  );
1338
2228
  }
1339
2229
 
1340
2230
  /** Starts the session and draws it. The returned instance's `waitUntilExit()` settles when the user leaves. */
1341
- export function runUi({ session, events, resume = null, stdin = process.stdin, stdout = process.stdout, messages = spinnerMessages(), cwd = process.cwd(), logo = logoLines(), clipboard = clipboardImage, copy = copyText, notify = true, notifyAfterMs = NOTIFY_AFTER_MS, quietAfterMs = QUIET_AFTER_MS, run = inTerminal, listFiles = gitFiles, debug = false }) {
2231
+ /**
2232
+ * Ink writes a changed line as: to its first column, the line, erase to the end. After a line exactly as wide as the
2233
+ * window the cursor waits on its last column, and an xterm-like terminal erases that column with it — the right edge
2234
+ * of every box, gone. The erase goes first instead: the same line drawn, nothing after it erased.
2235
+ */
2236
+ const ERASE_AFTER_LINE = /\x1b\[1G((?:(?!\x1b\[1G)[^\n])*?)\x1b\[K/g;
2237
+ export const eraseFirst = (chunk) => (typeof chunk === 'string' ? chunk.replace(ERASE_AFTER_LINE, (_whole, line) => `\x1b[1G\x1b[K${line}`) : chunk);
2238
+ /**
2239
+ * Ink steps over a line that has not changed with "next line" (`ESC[E`), which at the foot of the window goes nowhere: a
2240
+ * frame that grows past the last row is then drawn a row short, and the next one a row too high — over the frame before
2241
+ * it, which stays. A line feed is the same step everywhere else, and at the foot it scrolls, as a frame that grows needs.
2242
+ */
2243
+ export const nextLineScrolls = (chunk) => (typeof chunk === 'string' ? chunk.replaceAll('\x1b[E', '\r\n') : chunk);
2244
+
2245
+ export function runUi({ session, events, resume = null, stdin = process.stdin, stdout = process.stdout, messages = spinnerMessages(), cwd = process.cwd(), logo = logoLines(), clipboard = clipboardImage, copy = copyText, notify = true, notifyAfterMs = NOTIFY_AFTER_MS, quietAfterMs = QUIET_AFTER_MS, run = inTerminal, listFiles = gitFiles, motion = true, progress = showsProgress(), debug = false, plain = false }) {
1342
2246
  // Opened on a saved session (`sumo chat --resume`), the chat picks it up before the screen is drawn; a fresh one starts and is shown its block.
1343
2247
  const opening = resume === null ? null : session.resume(resume);
1344
2248
  const block = opening ? '' : session.start('startup');
@@ -1359,5 +2263,30 @@ export function runUi({ session, events, resume = null, stdin = process.stdin, s
1359
2263
  stdin.unshift = putBack;
1360
2264
  }, KITTY_WAIT_MS).unref();
1361
2265
  }
1362
- return render(h(App, { session, events, messages, cwd, block, opening, logo, clipboard, copy, notify, notifyAfterMs, quietAfterMs, run, listFiles }), { stdin, stdout, debug, exitOnCtrlC: false, kittyKeyboard: { mode: 'auto' } });
2266
+ // The terminal says when its window comes to the front and when it goes behind (`ESC[I`, `ESC[O`): a long turn that ends
2267
+ // behind rings. Ink drops replies like these before they reach the keys, so they are read here, as Ink reads them.
2268
+ const front = { now: true };
2269
+ if (typeof stdin.read === 'function') {
2270
+ const read = stdin.read.bind(stdin);
2271
+ stdin.read = (...args) => {
2272
+ const chunk = read(...args);
2273
+ if (chunk !== null && chunk !== undefined) {
2274
+ const text = String(chunk);
2275
+ const at = Math.max(text.lastIndexOf('\x1b[I'), text.lastIndexOf('\x1b[O'));
2276
+ if (at !== -1) front.now = text[at + 2] === 'I';
2277
+ }
2278
+ return chunk;
2279
+ };
2280
+ }
2281
+ // Plain (`chat.screen plain`), for a screen reader: ASCII marks, no frames, no pictures, and nothing moving.
2282
+ const app = h(App, { session, events, messages, cwd, block, opening, logo: plain ? [] : logo, clipboard, copy, notify, notifyAfterMs, quietAfterMs, run, listFiles, motion: motion && !plain, progress, plain, front });
2283
+ // Only the lines that changed are written again: a keystroke in the box rewrites the box's line, not the logo above it,
2284
+ // and a clock that ticks rewrites its own row. Measured in a real terminal at 80×24, a keystroke went from ~2.6 KB to
2285
+ // 200 bytes; on a slow or remote terminal the whole frame drawn again on every key is what flickers. Each line is
2286
+ // erased before it is written, not after (eraseFirst), and a line stepped over steps down even at the foot (nextLineScrolls).
2287
+ const write = stdout.write.bind(stdout);
2288
+ stdout.write = (chunk, ...rest) => write(nextLineScrolls(eraseFirst(chunk)), ...rest);
2289
+ // At a terminal the screen is interactive, whatever the environment says: Ink reads a CI variable as a cue to draw only
2290
+ // the last frame, and a shell that exports one (a CI runner, some setups) would get a chat that never shows its work.
2291
+ return render(h(Marks.Provider, { value: glyphs(plain) }, app), { stdin, stdout, debug, exitOnCtrlC: false, kittyKeyboard: { mode: 'auto' }, incrementalRendering: true, interactive: Boolean(stdout.isTTY) });
1363
2292
  }