sumo-agents 0.4.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/AGENTS.md +8 -6
  2. package/CHANGELOG.md +187 -0
  3. package/README.md +76 -18
  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 +186 -75
  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 +3 -2
  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 +1 -1
  26. package/src/hooks.mjs +31 -18
  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 +76 -12
  40. package/src/redact.mjs +10 -0
  41. package/src/render.mjs +2 -1
  42. package/src/route.mjs +16 -22
  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 +46 -11
  47. package/src/setup.mjs +423 -78
  48. package/src/text.mjs +100 -1
  49. package/src/tools.mjs +258 -21
  50. package/src/tty.mjs +210 -44
  51. package/src/ui.mjs +816 -226
  52. package/src/verify.mjs +17 -1
package/src/ui.mjs CHANGED
@@ -1,21 +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, existsSync, mkdirSync, openSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
4
- import { dirname, isAbsolute, join, resolve } from 'node:path';
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
5
  import { homedir } from 'node:os';
6
- import { createElement as h, useEffect, useReducer, useRef } from 'react';
7
- import { compactLine, contextReport, retryLine, routeLine, routeOf } from './chat.mjs';
6
+ import { createContext, createElement as h, useContext, useEffect, useReducer, useRef } from 'react';
7
+ import { compactLine, contextReport, routeLine, routeOf } from './chat.mjs';
8
8
  import { contextBand } from './sessions.mjs';
9
9
  import { liveFile } from './jobs.mjs';
10
10
  import { stopReason } from './loop.mjs';
11
- import { compactInput, INPUT_SHOWN } from './mcp.mjs';
11
+ import { INPUT_SHOWN } from './mcp.mjs';
12
12
  import { paths } from './paths.mjs';
13
+ import { scratchDir } from './projects.mjs';
13
14
  import { redact } from './redact.mjs';
14
15
  import { elapsed } from './text.mjs';
15
16
  import { cleanPaste, editor, keysOf, matchFiles, menuOf, paste, press, under } from './editor.mjs';
16
17
  import { clipboardImage, copyText, droppedImages } from './images.mjs';
17
- import { BASH_TOOL, DELEGATE_TOOL, EDITOR_TOOL } from './tools.mjs';
18
- import { colourEnabled, createRenderer, explained, flow, fold, linked, logoLines, markdownOf, messageAt, pathFrom, pickMessage, renderBlock, safeForTerminal, spinnerMessages, styles, sunset, tilde, toolView, transcript, untab, VERSION, withoutColourCodes, wrap } from './tty.mjs';
18
+ import { ASK_TOOL, BASH_TOOL, DELEGATE_TOOL, EDITOR_TOOL } from './tools.mjs';
19
+ import { colourEnabled, createRenderer, explained, flow, fold, glyphs, inline, linked, logoLines, markdownOf, messageAt, pathFrom, pickMessage, renderBlock, safeForTerminal, spinnerMessages, statOf, styles, sunset, tilde, toolView, transcript, untab, VERSION, withoutColourCodes, withSpan, wrap } from './tty.mjs';
19
20
 
20
21
  /**
21
22
  * The chat on a real terminal. What is finished scrolls away above — what
@@ -42,6 +43,9 @@ import { colourEnabled, createRenderer, explained, flow, fold, linked, logoLines
42
43
  */
43
44
 
44
45
  const ACCENT = '#d77757';
46
+ /** The marks the screen draws with: plain ones (`chat.screen plain`) for a screen reader. Every component reads them here. */
47
+ const Marks = createContext(glyphs(false));
48
+ const useMarks = () => useContext(Marks);
45
49
  /** The name at the top of the chat, two rows of blocks. */
46
50
  const WORDMARK = ['█▀▀ █ █ █▀▄▀█ █▀█', '▄▄█ █▄█ █ ▀ █ █▄█'];
47
51
  const FLOW_STEP_MS = 100;
@@ -56,6 +60,10 @@ const CLEAR = '\x1b[2J\x1b[3J\x1b[H';
56
60
  * the drawing starts at the top. For a chat that opens, or starts over — nothing that was on the terminal is lost to it.
57
61
  */
58
62
  const scrolledClear = (rows) => `\x1b[${rows};1H${'\n'.repeat(rows)}\x1b[H`;
63
+ /** A report that the window came to the front (`ESC[I`) or went behind (`ESC[O`). */
64
+ const FOCUS_REPORT = /\x1b\[[IO]/g;
65
+ /** How long the start of a sequence at the end of a read waits for its rest; and how long after a bare ESC went on as the Esc key a `[I` or `[O` is still the rest of a focus report. */
66
+ const FOCUS_LATE_MS = 1000;
59
67
  /** The terminal says when its window comes to the front and goes behind (`[I`, `[O`); and keeps its title, to be given back. */
60
68
  const FOCUS_ON = '\x1b[?1004h';
61
69
  const FOCUS_OFF = '\x1b[?1004l';
@@ -73,7 +81,7 @@ const SCREEN_BACK = '\x1b[?1049l';
73
81
  */
74
82
  const PROGRESS_BUSY = '\x1b]9;4;3;0\x07';
75
83
  const PROGRESS_DONE = '\x1b]9;4;0;0\x07';
76
- export function showsProgress(env = process.env) {
84
+ function showsProgress(env = process.env) {
77
85
  if (env.TMUX || env.STY) return false;
78
86
  if (env.WT_SESSION || env.ConEmuANSI === 'ON' || env.TERM_PROGRAM === 'ghostty') return true;
79
87
  if (env.TERM_PROGRAM === 'iTerm.app') {
@@ -176,7 +184,7 @@ export function replayOf(messages, turns = REPLAY_TURNS) {
176
184
  * Where `/export` writes: the path given — from the project, or from home with `~` — and into a folder given, a file of its
177
185
  * own; with none, the home's exports folder, named by the day and the session.
178
186
  */
179
- export function exportPath(given, cwd, sessionId = null) {
187
+ function exportPath(given, cwd, sessionId = null) {
180
188
  const named = `${new Date().toISOString().slice(0, 10)}-${String(sessionId ?? 'session').slice(0, 8)}.md`;
181
189
  if (!given) return join(paths().home, 'exports', named);
182
190
  const path = given.replace(/^~(?=$|\/)/, homedir());
@@ -206,6 +214,8 @@ function keepHistory(line) {
206
214
  try {
207
215
  mkdirSync(paths().home, { recursive: true, mode: 0o700 });
208
216
  writeFileSync(historyFile(), `${lines.slice(-HISTORY_KEPT).join('\n')}\n`, { mode: 0o600 });
217
+ // The mode is given only to a file being made: one made before it was set is made private here.
218
+ chmodSync(historyFile(), 0o600);
209
219
  } catch {
210
220
  // Nowhere to keep it: the line is still sent.
211
221
  }
@@ -213,20 +223,50 @@ function keepHistory(line) {
213
223
 
214
224
  const thousands = (n) => (n >= 1000 ? `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)}k` : String(n));
215
225
 
226
+ /**
227
+ * A request being sent again, for the scroll: why, in the words a known failure is said in — not what to do about it,
228
+ * since it is being done — and which try this is. One it does not know is said as it came.
229
+ */
230
+ const retryWhy = (reason) => {
231
+ const said = explained(reason);
232
+ return said.detail ? said.text.replace(/^error: /, '').split(' — ')[0] : String(reason ?? '').replace(/\s+/g, ' ').trim().slice(0, 160);
233
+ };
234
+ const retryNote = ({ attempt, limit, reason }) => `${retryWhy(reason)} · retrying (${attempt} of ${limit})`;
235
+
236
+ /**
237
+ * Reverse video, whatever the colour: NO_COLOR asks for no colour, and chalk, told so, drops every style with it — the
238
+ * cursor in the box, and the part of an edit that changed, would be gone. These are not colour, and are kept.
239
+ */
240
+ const reverse = (text) => `\x1b[7m${text}\x1b[27m`;
241
+
216
242
  /**
217
243
  * The lines under a call: what came back, the first of them with the mark. Folded to `columns` here, by the same count the
218
244
  * 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.
245
+ * With `max`, at most that many rows: the last says how many lines were folded away — a line partly shown is shown.
219
246
  */
220
- const linesUnder = (lines, columns, s = styles(false)) =>
221
- lines
222
- .flatMap((line) => {
223
- // An address in what came back opens on a click, whole, however the line is folded.
224
- const text = linked(untab(line.text), s);
225
- // 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.
226
- const hang = /^\s*(?:\d+(?: [-+ ] | {2,})\s*|[•*-] |\d+[.)] )/.exec(text)?.[0].length ?? 0;
227
- return fold(text, Math.max(20, columns - 6), ' '.repeat(Math.min(hang, Math.floor((columns - 6) / 2)))).map((row) => ({ ...line, text: row }));
228
- })
229
- .map((line, i) => h(Text, { key: i, ...TONES[line.tone], wrap: 'truncate' }, `${i === 0 ? ' ⎿ ' : ' '}${line.text}`));
247
+ const linesUnder = (lines, columns, s = styles(false), max = null) => {
248
+ const rows = [];
249
+ let reached = 0;
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, Math.max(20, columns - 6), ' '.repeat(Math.min(hang, Math.floor((columns - 6) / 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
+ return kept.map((line, i) => h(Text, { key: i, ...TONES[line.tone], wrap: 'truncate' }, `${i === 0 ? ` ${s.g.under} ` : ' '}${line.text}`));
269
+ };
230
270
 
231
271
  /**
232
272
  * The last lines a running command has printed, as the screen may show them: without secrets or control characters, a
@@ -237,54 +277,81 @@ function lastLines({ out, cut }) {
237
277
  return (cut ? lines.slice(1) : lines).map((l) => untab(l).trimEnd()).filter(Boolean).slice(-LIVE_LINES);
238
278
  }
239
279
 
240
- /** A command that is running: for how long, and the last of what it has printed so far. */
241
- function Running({ live, label = 'Running…' }) {
242
- // 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.
243
- useAnimation({ interval: 250 });
244
- const ran = live ? Date.now() - live.since : 0;
245
- return h(
246
- Box,
247
- { flexDirection: 'column' },
248
- h(Text, { dimColor: true }, ` ⎿ ${label}${ran >= 1000 ? ` ${elapsed(ran)}` : ''}`),
249
- ...(live ? lastLines(live) : []).map((line, i) => h(Text, { key: i, dimColor: true, wrap: 'truncate' }, ` ${line}`)),
250
- );
251
- }
252
-
253
- /** A tool call: what ran, and under it what came back — or, while it runs, the jobs it started, or what it prints. */
254
280
  /**
255
281
  * What a call ran, as the rows it takes: the tool in bold, what it was given, how much an edit added and took away, how
256
282
  * long it ran — folded here, at the spaces, so a row that goes on starts at the margin, not with the space it broke at.
257
283
  */
258
284
  function titleRows(view, took, s, width) {
259
- const stat = view.stat ? ` ${s.green(`+${view.stat.added}`)} ${s.red(`−${view.stat.removed}`)}` : '';
260
285
  const time = took >= TOOK_SHOWN_MS ? s.dim(` · ${elapsed(took)}`) : '';
261
- return untab(`${s.bold(view.title)}(${view.detail})${stat}${time}`)
286
+ // Several calls drawn as one say what they were in words, not as a call: `Read 3 files (a.js, b.js, +1)`.
287
+ const what = view.group ? `${s.bold(view.title)} (${view.detail})` : `${s.bold(view.title)}(${view.detail})`;
288
+ return untab(`${what}${statOf(view.stat, s)}${time}`)
262
289
  .split('\n')
263
290
  .flatMap((line) => wrap(line, width).split('\n'));
264
291
  }
265
292
 
266
- function Tool({ view, failed = false, running = false, waiting = false, jobs = [], live = null, took = 0, columns, s = styles(false) }) {
293
+ /** A tool call: what ran, and under it what came back — or, while it runs, the jobs it started, or what it prints. */
294
+ function Tool(props) {
295
+ const g = useMarks();
296
+ const step = stepOf(props, g);
297
+ // Drawn again for its clock, a little more often than it turns over, so a second is never skipped.
298
+ useAnimation({ interval: 250, isActive: step.ticking });
267
299
  return h(
268
300
  Box,
269
- { flexDirection: 'column', marginTop: 1 },
301
+ { flexDirection: 'column', marginTop: props.afterBlank ? 0 : 1 },
270
302
  // 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.
303
+ // A failure has a mark of its own: its colour alone says nothing to someone who cannot see it.
271
304
  h(
272
305
  Box,
273
306
  null,
274
- h(Box, { flexShrink: 0 }, h(Text, { color: running ? undefined : failed ? 'red' : 'green', dimColor: running }, '⏺ ')),
275
- // How long it ran, once that is long enough to have been waited on.
307
+ h(Box, { flexShrink: 0 }, h(Text, step.markTone, `${step.mark} `)),
276
308
  // 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.
277
- h(Box, { flexShrink: 1, flexDirection: 'column', width: Math.max(10, columns - 2) }, ...titleRows(view, took, s, Math.max(10, columns - 2)).map((row, i) => h(Text, { key: i }, row))),
309
+ h(Box, { flexShrink: 1, flexDirection: 'column', width: Math.max(10, props.columns - 2) }, ...step.title.map((row, i) => h(Text, { key: i }, row))),
278
310
  ),
279
- // A question put to the user is not running anything: it waits on them, and says so.
280
- // A delegation has no job yet while the router picks the model and effort it runs on.
281
- // So is a call held for the user's word.
282
- running && (view.title === 'Question' || waiting) ? h(Text, { dimColor: true }, ' ⎿ waiting for your answer') : running && jobs.length === 0 ? h(Running, { live, label: view.title === 'Delegate' ? 'picking the model and effort…' : 'Running…' }) : null,
283
- ...jobs.map(([id, job]) => h(JobAtWork, { key: id, id, job })),
284
- ...linesUnder(view.lines, columns, s),
311
+ step.note ? h(Text, { dimColor: true }, ` ${g.under} ${step.note}`) : null,
312
+ ...step.live.map((line, i) => h(Text, { key: `live-${i}`, dimColor: true, wrap: 'truncate' }, ` ${line}`)),
313
+ ...step.jobs.map(([id, job]) => h(JobAtWork, { key: id, id, job })),
314
+ ...step.under,
285
315
  );
286
316
  }
287
317
 
318
+ /**
319
+ * What a step draws, row by row — its title folded, a note, what a command prints, its jobs, what came back — so the step
320
+ * (`Tool`) and the count of rows the work above a question takes are one and the same.
321
+ */
322
+ function stepOf({ view, failed = false, running = false, waiting = false, jobs = [], live = null, took = 0, since = 0, columns, s = styles(false) }, g) {
323
+ const plain = g === glyphs(true);
324
+ // A question put to the user is not running anything: it waits on them, and says so.
325
+ // 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.
326
+ // A delegation has no job yet while the router picks the model and effort it runs on.
327
+ const asking = running && view.title === 'Question' && !waiting;
328
+ const working = running && !waiting && !asking && jobs.length === 0;
329
+ // Only what runs has a clock. Plain, for a screen reader, there is none: the row is drawn again for what the command
330
+ // prints, not for the time.
331
+ const ticking = working && !plain;
332
+ const ran = ticking && since > 0 ? Date.now() - since : 0;
333
+ const width = Math.max(10, columns - 2);
334
+ // 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.
335
+ const rows = titleRows(view, running ? 0 : took, s, width);
336
+ const title = waiting && rows.length > 1 ? [`${titleRows(view, 0, s, width - 2)[0]} …`] : rows;
337
+ return {
338
+ ticking,
339
+ mark: failed && !running ? g.fail : g.tool,
340
+ markTone: { color: running ? undefined : failed ? 'red' : 'green', dimColor: running },
341
+ title,
342
+ note: asking ? 'waiting for your answer' : working ? (view.title === 'Delegate' ? 'picking the model and effort…' : `Running…${ran >= 1000 ? ` ${elapsed(ran)}` : ''}`) : null,
343
+ live: working && live ? lastLines(live) : [],
344
+ jobs,
345
+ under: linesUnder(view.lines, columns, s, view.rows ?? null),
346
+ };
347
+ }
348
+
349
+ /** The rows a step takes on the screen: the blank one over it (unless a reply's blank line is that row), its title, and all that stands under it. */
350
+ const stepRowCount = (props, g) => {
351
+ const step = stepOf(props, g);
352
+ return (props.afterBlank ? 0 : 1) + step.title.length + (step.note ? 1 : 0) + step.live.length + step.jobs.length + step.under.length;
353
+ };
354
+
288
355
  /** A call that took at least this long says how long, beside what ran. */
289
356
  const TOOK_SHOWN_MS = 1000;
290
357
  /** Thought for less than this, the line that says so would say nothing. */
@@ -319,12 +386,15 @@ const TITLE_CHARS = 32;
319
386
  * whose record is open.
320
387
  */
321
388
  function JobAtWork({ id, job, alone = false, picked = false, open = false }) {
322
- useAnimation({ interval: 1000 });
389
+ // Plain, the row says what the job has done, not for how long: a clock would have it read out every second.
390
+ const g = useMarks();
391
+ const plain = g === glyphs(true);
392
+ useAnimation({ interval: 1000, isActive: !plain });
323
393
  const calls = `${job.calls} tool call${job.calls === 1 ? '' : 's'}`;
324
- const mark = alone ? (picked ? ' ❯ ' : ' ⏺ ') : ' ⎿ ';
394
+ const mark = alone ? (picked ? ` ${g.pick} ` : ` ${g.tool} `) : ` ${g.under} `;
325
395
  // 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.
326
396
  const who = alone ? ` ${job.agent} — ${job.title.length > TITLE_CHARS ? `${job.title.slice(0, TITLE_CHARS - 1)}…` : job.title}` : ` ${job.agent} · ${job.route}`;
327
- const lead = `j${id}${who} · ${elapsed(Date.now() - job.since)} · ${calls} · `;
397
+ const lead = `j${id}${who} · ${plain ? '' : `${elapsed(Date.now() - job.since)} · `}${calls} · `;
328
398
  return h(
329
399
  Text,
330
400
  { wrap: 'truncate' },
@@ -340,9 +410,13 @@ const MAIN = 'main';
340
410
 
341
411
  /** 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`). */
342
412
  function MainAtWork({ working, picked = false, shown = false }) {
343
- 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'));
413
+ const g = useMarks();
414
+ return h(Text, { wrap: 'truncate' }, h(Text, picked || shown ? { color: ACCENT } : { dimColor: true }, picked ? ` ${g.pick} ` : ` ${g.tool} `), h(Text, { dimColor: !picked }, 'main · '), h(Text, { dimColor: true }, working ? 'working' : 'idle'));
344
415
  }
345
416
 
417
+ /** A line written with the screen's own marks — a job's record — in the marks this screen draws with. */
418
+ const inMarks = (line, g) => (g.tool === '⏺' ? line : line.replaceAll('⏺', g.tool).replaceAll('⎿', g.under).replaceAll('✗', g.fail).replaceAll('✻', g.thought));
419
+
346
420
  /** 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. */
347
421
  function recordLines(id) {
348
422
  try {
@@ -361,57 +435,184 @@ const openRows = (rows) => Math.max(3, Math.min(rows - 24, Math.floor(rows / 2))
361
435
  */
362
436
  function JobOpen({ id, job, rows }) {
363
437
  useAnimation({ interval: 1000 });
438
+ const g = useMarks();
364
439
  const all = recordLines(id);
365
440
  const seen = all.slice(-openRows(rows));
366
441
  const above = all.length - seen.length;
367
442
  return h(
368
443
  Box,
369
444
  { flexDirection: 'column', marginTop: 1 },
370
- h(Text, { wrap: 'truncate' }, h(Text, { color: jobColour(id) }, '⏺ '), h(Text, { bold: true }, `j${id}`), ` ${job.agent} · ${job.route} — ${job.title}`),
445
+ h(Text, { wrap: 'truncate' }, h(Text, { color: jobColour(id) }, `${g.tool} `), h(Text, { bold: true }, `j${id}`), ` ${job.agent} · ${job.route} — ${job.title}`),
371
446
  above > 0 ? h(Text, { dimColor: true }, ` … +${above} line${above === 1 ? '' : 's'}`) : null,
372
447
  all.length === 0 ? h(Text, { dimColor: true }, ' nothing done yet') : null,
373
- ...seen.map((line, i) => h(Text, { key: i, dimColor: /^\s*⎿/.test(line), wrap: 'truncate' }, untab(line) || ' ')),
448
+ ...seen.map((line, i) => h(Text, { key: i, dimColor: /^\s*⎿/.test(line), wrap: 'truncate' }, inMarks(untab(line), g) || ' ')),
374
449
  );
375
450
  }
376
451
 
377
452
  /** 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. */
378
453
  const ASK_INPUT_MAX = 4_000;
379
454
 
455
+ /**
456
+ * What a question shows, as plain text: no escape of any kind, colours included — a conceal code (`ESC[8m`) would hide
457
+ * 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.
458
+ */
459
+ 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)}`)));
460
+
461
+ /**
462
+ * A change to a file outside the project, as the question shows it: the file and the command, then what is taken out (-)
463
+ * 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
464
+ * it (a guarded one can be), else whole — one file, one spelling.
465
+ */
466
+ function editLines(ask, cwd = null) {
467
+ const input = ask.input ?? {};
468
+ const lines = (text, mark) => asText(text).replace(/\n$/, '').split('\n').map((l) => `${mark} ${l}`);
469
+ // 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.
470
+ // What it does is said in words, not by the editor's own command.
471
+ const verb = { str_replace: 'change', create: 'create', insert: 'insert into' }[input.command] ?? input.command;
472
+ const head = asText(`${verb} ${pathFrom(ask.path, cwd)}${input.command === 'insert' ? ` after line ${input.insert_line ?? 0}` : ''}`);
473
+ if (input.command === 'create') return [head, ...lines(input.file_text, '+')];
474
+ if (input.command === 'insert') return [head, ...lines(input.insert_text ?? input.new_str, '+')];
475
+ return [head, ...lines(input.old_str, '-'), ...lines(input.new_str, '+')];
476
+ }
477
+
478
+ /**
479
+ * The keys that answer a call waiting on the user, and what each answers. A run outside the sandbox is this one run or
480
+ * none; a guarded file is changed this once or not; a file outside the project can be opened for the session, alone or
481
+ * with its directory; an MCP call can be allowed for good.
482
+ */
483
+ function answersTo(ask) {
484
+ // 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.
485
+ if (ask.unsandboxed) return 'y yes · n no · r no, say why';
486
+ if (ask.guarded) return 'y once · n no · r no, say why';
487
+ // The folder by its name: the path just above it in the question is the file's, in that folder.
488
+ 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`;
489
+ return 'y once · a always · n no · r no, say why';
490
+ }
491
+ const KEY_ANSWERS = { y: 'once', a: 'always', d: 'directory', n: 'no', r: 'why' };
492
+ /** The answer a key gives to a waiting call, or undefined when the key answers nothing on it. */
493
+ const answerOf = (ask, key) => (answersTo(ask).split(' · ').some((said) => said.startsWith(`${key} `)) ? KEY_ANSWERS[key] : undefined);
494
+ /** What the panel says when a key answers nothing: each key and what it does, Esc's too. */
495
+ const explainKeys = (ask, aside = false) =>
496
+ `${answersTo(ask)
497
+ .split(' · ')
498
+ .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)
499
+ .join(' · ')} · esc ${aside ? 'refuses it' : 'interrupts the turn'}`;
500
+
501
+ /** How long a run of spaces may be before the question counts it instead of drawing it: blank rows hide what follows them. */
502
+ const SPACES_COUNTED = 16;
503
+ /** A long run of spaces or tabs in what would run, as a count the eye cannot miss: `echo ok ⟨200 spaces⟩ ; curl …`. */
504
+ const spacesCounted = (line) => line.replace(new RegExp(`[ \\t]{${SPACES_COUNTED},}`, 'g'), (run) => ` ⟨${run.length} spaces⟩ `);
505
+
380
506
  /** 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. */
381
- function Ask({ ask, aside = false, columns }) {
507
+ function Ask({ ask, aside = false, waiting = 1, why = null, explain = false, columns, cwd = null, rows = null }) {
382
508
  const who = ask.job ? `j${ask.job}: ` : '';
383
509
  // A command the sandbox blocked is asked as itself: the command, to run once outside the sandbox — yes or no, never always.
384
- const command = ask.unsandboxed ? safeForTerminal(String(ask.input?.command ?? '')) : null;
385
- const whole = command ?? JSON.stringify(ask.input ?? {});
510
+ const command = ask.unsandboxed ? asText(ask.input?.command) : null;
511
+ // 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.
512
+ const edit = ask.path ? editLines(ask, cwd) : null;
513
+ const whole = command ?? edit?.join('\n') ?? JSON.stringify(ask.input ?? {});
386
514
  // Short enough for a line, it is the one line; longer, it is laid out, every field whole, up to the cut.
387
515
  const short = whole.length <= INPUT_SHOWN && !whole.includes('\n');
388
- const laid = short ? [whole] : command !== null ? command.split('\n') : JSON.stringify(ask.input ?? {}, null, 2).split('\n');
516
+ const laid = short ? [whole] : command !== null ? command.split('\n') : edit ?? JSON.stringify(ask.input ?? {}, null, 2).split('\n');
517
+ // 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
518
+ // is counted in characters — a single line can hold what matters past any count of lines.
389
519
  const kept = [];
390
520
  let size = 0;
521
+ let unshown = 0;
391
522
  for (const line of laid) {
392
- if (size + line.length > ASK_INPUT_MAX) break;
393
- kept.push(line);
394
- size += line.length + 1;
523
+ const room = ASK_INPUT_MAX - size;
524
+ if (room <= 0) unshown += line.length + 1;
525
+ else if (line.length > room) {
526
+ kept.push(line.slice(0, room));
527
+ unshown += line.length - room;
528
+ size = ASK_INPUT_MAX;
529
+ } else {
530
+ kept.push(line);
531
+ size += line.length + 1;
532
+ }
395
533
  }
396
- const cut = laid.length - kept.length;
397
- const title = command !== null ? `${who}Run this once outside the sandbox?` : `${who}Allow ${ask.server} · ${ask.tool}?`;
534
+ // A server names its own tools: the title draws them as text, as it draws the input.
535
+ 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}?`);
398
536
  // 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.
399
- const keys = `${command !== null ? 'y yes · n no' : 'y once · a always · n no'} · esc ${aside ? 'no' : 'stop'}`;
400
- // A panel of its own, set apart from the work: what would run, whole, and the keys that answer.
537
+ // Several jobs can ask at once: the ones behind this are counted, so none waits unseen.
538
+ // Saying why, the keys are the line's: Enter refuses with the words, Esc goes back to the question.
539
+ // A key that answers nothing has every key explained here, in the panel's own colour, where nothing is cut to fit.
540
+ // Esc is named as the working line names it, wherever it stops the turn.
541
+ 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` : ''}`;
542
+ // A panel of its own, framed in yellow, set apart from the work: why it asks, faint; what would run, whole and set in; the
543
+ // keys that answer. Plain, it has no frame: a frame is read out as a row of lines.
544
+ const g = useMarks();
545
+ const framed = g === glyphs(false);
546
+ // Everything in it is folded here, at the width it is drawn at, so the rows it takes are known before it is drawn.
547
+ const width = Math.max(20, columns - (framed ? 4 : 0));
548
+ const titled = wrap(`${g.warn} ${title}`, width);
549
+ const refused = ask.unsandboxed && ask.blocked ? fold(asText(`the sandbox refused: ${ask.blocked}`), width - 2) : [];
550
+ const input = whole === '{}' ? null : kept.flatMap((line) => fold(spacesCounted(untab(line)) || ' ', Math.max(10, width - 4)));
551
+ const keyed = keyRows(keys, width);
552
+ const reason = why !== null ? fold(`${asText(why)}▌`, Math.max(10, width - 9)) : [];
553
+ 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 - 4));
554
+ // Given the rows it may take (`rows`), what would run is shown as far as they go: a panel taller than the window makes
555
+ // 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.
556
+ let shown = input ?? [];
557
+ let hidden = unshown;
558
+ // The blank rows around what would run: the first thing a window too short for the panel gives up.
559
+ let around = 1;
560
+ if (rows !== null && input) {
561
+ // A key's words longer than a row go on to the next: counted as they would fold, never fewer.
562
+ const keyRowCount = keyed.reduce((sum, row) => sum + wrap(row, width - 1).split('\n').length, 0);
563
+ let fixed = 1 + (framed ? 2 : 0) + titled.split('\n').length + refused.length + 2 + (reason.length > 0 ? reason.length + 1 : 0) + keyRowCount;
564
+ const fits = () => fixed + input.length + (hidden > 0 ? noted(hidden).length : 0) <= rows;
565
+ if (!fits()) {
566
+ around = 0;
567
+ fixed -= 2;
568
+ }
569
+ if (!fits()) {
570
+ const room = Math.max(1, rows - fixed - noted(hidden + whole.length).length);
571
+ hidden += input.slice(room).reduce((sum, row) => sum + row.trim().length, 0);
572
+ shown = input.slice(0, room);
573
+ }
574
+ }
401
575
  return h(
402
576
  Box,
403
- { marginTop: 1, flexDirection: 'column', borderStyle: 'round', borderColor: 'yellow', paddingX: 1, width: Math.max(20, columns) },
404
- h(Text, { color: 'yellow', bold: true }, `⚠ ${title}`),
577
+ { marginTop: 1, flexDirection: 'column', ...(framed ? { borderStyle: 'round', borderColor: 'yellow', paddingX: 1 } : {}), width: Math.max(20, columns) },
578
+ h(Text, { color: 'yellow', bold: true }, titled),
579
+ // Why a run outside is asked: what the sandbox refused, faint, under the question.
580
+ ...refused.map((row, i) => h(Text, { key: `refused-${i}`, dimColor: true, wrap: 'truncate' }, ` ${row}`)),
581
+ // 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.
405
582
  h(
406
583
  Box,
407
- { flexDirection: 'column', marginY: 1, paddingLeft: 2 },
408
- ...(whole === '{}' ? [h(Text, { key: 'none', dimColor: true }, '(no input)')] : kept.map((line, i) => h(Text, { key: i, wrap: 'truncate-end' }, untab(line) || ' '))),
409
- cut > 0 ? h(Text, { dimColor: true }, `… ${cut} more line${cut === 1 ? '' : 's'} of input not shown — n, and ask the model for less`) : null,
584
+ { flexDirection: 'column', paddingLeft: 4, marginY: around },
585
+ ...(input === null ? [h(Text, { key: 'none', dimColor: true }, '(no input)')] : shown.map((row, i) => h(Text, { key: i, wrap: 'truncate' }, row || ' '))),
586
+ ...(hidden > 0 ? noted(hidden).map((row, i) => h(Text, { key: `noted-${i}`, dimColor: true, wrap: 'truncate' }, row)) : []),
410
587
  ),
411
- h(Text, { dimColor: true }, keys),
588
+ why !== null ? h(Box, { marginBottom: 1 }, h(Box, { flexShrink: 0 }, h(Text, { color: 'yellow' }, 'why not? ')), h(Text, null, reason.join('\n'))) : null,
589
+ // The keys go to as many rows as they need, broken only between keys — at full weight, the key itself bold: they are
590
+ // what the panel asks the user to read and press.
591
+ ...keyed.map((row, i) => h(Text, { key: `keys-${i}`, ...(explain && why === null ? { color: 'yellow' } : {}), wrap: 'wrap' }, ...keysBold(row))),
412
592
  );
413
593
  }
414
594
 
595
+ /** A row of keys, `y once · n no`, with each key in bold: the eye finds the letter to press before what it does. */
596
+ const keysBold = (row) =>
597
+ row.split(' · ').flatMap((unit, i) => {
598
+ const key = /^(?:[a-z]|esc|enter|tab|↑↓)(?= )/.exec(unit)?.[0] ?? '';
599
+ return [i > 0 ? ' · ' : '', key ? h(Text, { key: i, bold: true }, key) : null, key ? unit.slice(key.length) : unit];
600
+ });
601
+
602
+ /**
603
+ * 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
604
+ * row with what it does on the next. A key longer than a row has it to itself.
605
+ */
606
+ export function keyRows(said, width) {
607
+ const rows = [];
608
+ for (const unit of String(said).split(' · ')) {
609
+ const last = rows.at(-1);
610
+ if (last !== undefined && last.length + 3 + unit.length <= width) rows[rows.length - 1] = `${last} · ${unit}`;
611
+ else rows.push(unit);
612
+ }
613
+ return rows;
614
+ }
615
+
415
616
  /** A mark, and words that go on under themselves, never under the mark: the rows of a question and its options. */
416
617
  function Hung({ mark, width, color, children }) {
417
618
  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())));
@@ -419,24 +620,55 @@ function Hung({ mark, width, color, children }) {
419
620
 
420
621
  /** 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. */
421
622
  function Question({ ask, columns }) {
623
+ const g = useMarks();
422
624
  return h(
423
625
  Box,
424
626
  { marginTop: 1, flexDirection: 'column' },
425
627
  h(Hung, { mark: '? ', width: columns, color: 'yellow' }, ask.question),
426
- ...ask.options.map((option, i) => h(Hung, { key: i, mark: ` ${i === ask.at ? '❯' : ' '} ${i + 1}. `, width: columns, color: i === ask.at ? ACCENT : undefined }, option.label, option.detail ? h(Text, { dimColor: true }, ` — ${option.detail}`) : null)),
427
- h(Box, { paddingLeft: 2 }, h(Text, { dimColor: true }, `↑↓ choose · enter picks · 1–${ask.options.length} picks that one · or type your own answer · esc stop`)),
628
+ ...ask.options.map((option, i) => h(Hung, { key: i, mark: ` ${i === ask.at ? g.pick : ' '} ${i + 1}. `, width: columns, color: i === ask.at ? ACCENT : undefined }, option.label, option.detail ? h(Text, { dimColor: true }, ` — ${option.detail}`) : null)),
629
+ // Broken only between keys, as a panel's are: never `esc` at the end of a row and `to interrupt` on the next.
630
+ ...keyRows(`↑↓ choose · enter picks · 1–${ask.options.length} picks that one · or type your own answer · esc to interrupt`, Math.max(20, columns - 2)).map((row, i) => h(Box, { key: `keys-${i}`, paddingLeft: 2 }, h(Text, { dimColor: true }, row))),
428
631
  );
429
632
  }
430
633
 
431
634
  /** One line of a reply; the first of a block carries the mark. */
432
635
  function Reply({ text, first }) {
636
+ const g = useMarks();
433
637
  // The mark keeps its two columns: a line with a word wider than the window must not squeeze it, or every row after it shifts left.
434
- return h(Box, { marginTop: first ? 1 : 0 }, h(Box, { flexShrink: 0 }, h(Text, null, first ? '⏺ ' : ' ')), h(Text, null, text || ' '));
638
+ return h(Box, { marginTop: first ? 1 : 0 }, h(Box, { flexShrink: 0 }, h(Text, null, first ? `${g.tool} ` : ' ')), h(Text, null, text || ' '));
435
639
  }
436
640
 
641
+ /** A folder by where it really is — `/var` is `/private/var` on macOS — or as given, when it is not there to ask. */
642
+ const realOrSame = (folder) => {
643
+ try {
644
+ return realpathSync(folder);
645
+ } catch {
646
+ return resolve(folder);
647
+ }
648
+ };
649
+
650
+ /** Why the tools are not working in the folder the chat was opened in, and what makes them. */
651
+ const awayLine = (folder) => `${folder} is not a project: the tools work in scratch — sumo project add . there makes it one`;
652
+
653
+ /** The header's second row: the project the tools work in and its branch, then — faint — the folder it is. */
654
+ const whereRow = (item) => (item.place ? [item.place, h(Text, { key: 'cwd', dimColor: true }, ` · ${item.cwd}`)] : [h(Text, { key: 'cwd', dimColor: true }, item.cwd)]);
655
+
437
656
  /** Something finished, drawn once and left to scroll. */
438
657
  /** `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. */
439
658
  function Item({ item, columns, s }) {
659
+ // A blank line of a reply right before is the row between them: never two in a row.
660
+ const gap = item.afterBlank ? 0 : 1;
661
+ // Plain, the name is said, not drawn in blocks: a reader would spell out every one of them.
662
+ if (item.kind === 'header' && s.plain) {
663
+ return h(
664
+ Box,
665
+ { flexDirection: 'column', marginTop: 1 },
666
+ h(Text, { wrap: 'truncate-end' }, item.route, VERSION ? h(Text, { dimColor: true }, ` sumo ${VERSION}`) : null),
667
+ h(Text, { wrap: 'truncate-middle' }, ...whereRow(item)),
668
+ item.away ? h(Text, { dimColor: true }, wrap(awayLine(item.away), Math.max(10, columns - 1))) : null,
669
+ item.block ? h(Box, { marginTop: 1 }, h(Text, null, item.block)) : null,
670
+ );
671
+ }
440
672
  if (item.kind === 'header') {
441
673
  return h(
442
674
  Box,
@@ -447,60 +679,125 @@ function Item({ item, columns, s }) {
447
679
  // The sunset runs across the name, gold at the S to crimson at the O.
448
680
  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))))),
449
681
  // Beside the name, as wide as the window leaves: a long path loses its middle, never runs past the edge.
450
- h(Box, { flexDirection: 'column', width: Math.max(10, columns - WORDMARK[0].length - 3) }, h(Text, { wrap: 'truncate-end' }, item.route, VERSION ? h(Text, { dimColor: true }, ` sumo ${VERSION}`) : null), h(Text, { dimColor: true, wrap: 'truncate-middle' }, item.cwd)),
682
+ h(Box, { flexDirection: 'column', width: Math.max(10, columns - WORDMARK[0].length - 3) }, h(Text, { wrap: 'truncate-end' }, item.route, VERSION ? h(Text, { dimColor: true }, ` sumo ${VERSION}`) : null), h(Text, { wrap: 'truncate-middle' }, ...whereRow(item))),
451
683
  ),
684
+ item.away ? h(Box, { marginTop: 1 }, h(Text, { dimColor: true }, wrap(awayLine(item.away), Math.max(10, columns - 1)))) : null,
452
685
  item.block ? h(Box, { marginTop: 1 }, h(Text, null, item.block)) : null,
453
686
  );
454
687
  }
455
- // What the user said is what a scroll back looks for: full weight, a bar of the chat's colour down its side.
688
+ // What the user said is what a scroll back looks for: full weight, a bar of the chat's colour down its side — plain, a `>` before each line.
456
689
  if (item.kind === 'user') {
457
- return h(
458
- Box,
459
- { marginTop: 1, flexDirection: 'column', borderStyle: 'bold', borderColor: ACCENT, borderTop: false, borderRight: false, borderBottom: false, paddingLeft: 1 },
460
- h(Text, null, untab(item.text)),
461
- item.more ? h(Text, { dimColor: true }, `… +${item.more} line${item.more === 1 ? '' : 's'}`) : null,
462
- );
690
+ const more = item.more ? h(Text, { dimColor: true }, `… +${item.more} line${item.more === 1 ? '' : 's'}`) : null;
691
+ if (s.plain) return h(Box, { marginTop: gap, flexDirection: 'column' }, h(Text, null, untab(item.text).split('\n').map((line) => `${s.g.bar} ${line}`).join('\n')), more);
692
+ return h(Box, { marginTop: gap, flexDirection: 'column', borderStyle: 'bold', borderColor: ACCENT, borderTop: false, borderRight: false, borderBottom: false, paddingLeft: 1 }, h(Text, null, untab(item.text)), more);
463
693
  }
464
694
  if (item.kind === 'text') return h(Reply, item);
465
695
  if (item.kind === 'tool') return h(Tool, { ...item, columns, s });
466
696
  if (item.kind === 'output') return h(Box, { flexDirection: 'column' }, ...linesUnder(item.lines, columns, s));
467
- if (item.kind === 'footer') return h(Box, { marginTop: 1 }, h(Text, { dimColor: true }, ` ${item.text}`));
697
+ // Its margin holds on every row it wraps to: the turn summed up stands apart from the work above it.
698
+ if (item.kind === 'footer') return h(Box, { marginTop: gap, paddingLeft: 2 }, h(Text, { dimColor: true }, item.text));
468
699
  // The mark stands apart from the words, so a line that wraps in a narrow window goes on under them, not under it.
469
- if (item.kind === 'job') return h(Box, { marginTop: 1 }, h(Box, { flexShrink: 0 }, h(Text, { color: jobColour(item.id) }, '⏺ ')), h(Box, { width: Math.max(10, columns - 2) }, h(Text, null, h(Text, { bold: true }, `j${item.id}`), ` ${item.agent} · ${item.route} — ${item.title}`, h(Text, { dimColor: true }, ` · ${item.where}`))));
470
- if (item.kind === 'error') return h(Box, { marginTop: 1, flexDirection: 'column' }, h(Text, { color: 'red' }, item.text), item.detail ? h(Box, { paddingLeft: 2 }, h(Text, { dimColor: true }, item.detail)) : null);
700
+ if (item.kind === 'job') return h(Box, { marginTop: gap }, h(Box, { flexShrink: 0 }, h(Text, { color: jobColour(item.id) }, `${s.g.tool} `)), h(Box, { width: Math.max(10, columns - 2) }, h(Text, null, h(Text, { bold: true }, `j${item.id}`), ` ${item.agent} · ${item.route} — ${item.title}`, h(Text, { dimColor: true }, ` · ${item.where}`))));
701
+ // A failure has a mark of its own, as a failed call has, and goes on under its own words, not at the window's edge:
702
+ // folded here, at the spaces. What came back stands faint beneath, at the same margin.
703
+ if (item.kind === 'error') {
704
+ const width = Math.max(10, columns - 2);
705
+ return h(
706
+ Box,
707
+ { marginTop: gap, flexDirection: 'column' },
708
+ h(Box, null, h(Box, { flexShrink: 0 }, h(Text, { color: 'red' }, `${s.g.fail} `)), h(Box, { width }, h(Text, { color: 'red' }, wrap(item.text, width)))),
709
+ item.detail ? h(Box, { paddingLeft: 2 }, h(Text, { dimColor: true }, item.detail)) : null,
710
+ );
711
+ }
712
+ // /help: the command or key in the chat's colour, what it does faint beside it, going on under itself in a narrow window.
713
+ if (item.kind === 'help') {
714
+ const wide = Math.max(...item.rows.filter(Boolean).map((row) => row.key.length)) + 2;
715
+ const room = Math.max(10, columns - 2 - wide);
716
+ 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 }, ' '))));
717
+ }
471
718
  // What the model thought before it answered: how long, here; the thought itself is in the pager.
472
- if (item.kind === 'thought') return h(Box, { marginTop: 1 }, h(Text, { dimColor: true }, `✻ Thought for ${elapsed(item.ms)}`));
719
+ if (item.kind === 'thought') return h(Box, { marginTop: gap }, h(Text, { dimColor: true }, `${s.g.thought} Thought for ${elapsed(item.ms)}`));
473
720
  return h(Box, { flexDirection: 'column' }, ...linesUnder(item.text.split('\n').map((text) => ({ text, tone: 'dim' })), columns, s));
474
721
  }
475
722
 
723
+ /** The fewest characters of its words the working line keeps before what follows them gives way as well. */
724
+ const WORDS_KEPT = 12;
725
+
476
726
  /**
477
727
  * The line that says it is working: your words, the next of them every few seconds, a sunset flowing through them; how
478
728
  * long, how much, and how to stop it. Under it, while the model thinks, the last rows of what it has thought so far.
479
729
  */
480
- function Working({ messages, first, tokens, thought = '', heard = 0, quietAfterMs = QUIET_AFTER_MS, motion = true }) {
481
- // With motion off the words stand in one colour and the line is drawn once a second, for its clock.
482
- const { frame, time } = useAnimation({ interval: motion ? FLOW_STEP_MS : 1000 });
730
+ function Working({ messages, first, tokens, thought = '', heard = 0, quietAfterMs = QUIET_AFTER_MS, motion = true, retry = null, plan = null, waiting = false, afterBlank = false }) {
731
+ // With motion off the words stand in one colour and the line is drawn once a second, for its clock. While a question
732
+ // waits on the user, nothing works: the line steps aside — the question's own rows say it waits, and how Esc stops the
733
+ // turn — and nothing is drawn for it, so the screen holds still while the question is read. It stays in place, its
734
+ // clock running, to come back when the question is answered. Plain, for a screen reader, there is no clock at all: a
735
+ // row written again every second is a row read out again every second.
736
+ const g = useMarks();
737
+ const plain = g === glyphs(true);
738
+ const flowing = motion && !waiting;
739
+ const { frame } = useAnimation({ interval: flowing ? FLOW_STEP_MS : 1000, isActive: !plain && !waiting });
740
+ // Timed from when the line appeared, not by the animation, whose clock starts again whenever its pace changes.
741
+ const began = useRef(Date.now());
742
+ const time = Date.now() - began.current;
483
743
  const { columns } = useWindowSize();
484
- const words = `${messageAt(messages, first, time)}…`;
485
- const spent = tokens > 0 ? ` · ↓ ${thousands(tokens)} tokens` : '';
744
+ if (waiting) return null;
745
+ const said = `${messageAt(messages, first, time)}…`;
486
746
  const thinking = thoughtRows(thought, Math.max(20, columns - 6));
487
747
  // `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.
488
748
  const silent = heard > 0 ? Date.now() - heard : 0;
489
- const quiet = silent >= quietAfterMs ? ` · quiet ${elapsed(silent)}` : '';
749
+ // A request sent again is waited on in the open: how long until it goes, and which try it is.
750
+ const left = retry ? retry.until - Date.now() : 0;
751
+ const parts = {
752
+ clock: plain ? '' : elapsed(time),
753
+ spent: tokens > 0 ? `↓ ${thousands(tokens)} tokens` : '',
754
+ again: retry && plain ? `retrying · attempt ${retry.attempt}/${retry.limit}` : left > 0 ? `retrying in ${Math.ceil(left / 1000)}s · attempt ${retry.attempt}/${retry.limit}` : '',
755
+ quiet: !plain && silent >= quietAfterMs ? `quiet ${elapsed(silent)}` : '',
756
+ };
757
+ const status = () => `(${[parts.clock, parts.spent, parts.again, parts.quiet, 'esc to interrupt'].filter(Boolean).join(' · ')})`;
758
+ // In a narrow window what is least needed gives way first — the tokens, the silence — then the words, to a few of their
759
+ // own, then the clock and the try. How to stop the turn is never what is cut.
760
+ const room = () => columns - status().length - 1;
761
+ for (const part of ['spent', 'quiet']) if (room() < said.length) parts[part] = '';
762
+ for (const part of ['clock', 'again']) if (room() < WORDS_KEPT) parts[part] = '';
763
+ // Cut between words where there is one to cut at: what is left still reads.
764
+ const fits = Math.max(WORDS_KEPT, room());
765
+ const cut = said.slice(0, fits - 1);
766
+ const words = said.length <= fits ? said : `${(cut.lastIndexOf(' ') >= WORDS_KEPT / 2 ? cut.slice(0, cut.lastIndexOf(' ')) : cut).trimEnd()}…`;
490
767
  return h(
491
768
  Box,
492
- { marginTop: 1, flexDirection: 'column' },
493
- // One row: the words whole, and what follows them cut at the edge rather than set in a column of its own beside them.
769
+ { marginTop: afterBlank ? 0 : 1, flexDirection: 'column' },
770
+ // One row: the words, and what follows them cut at the edge rather than set in a column of its own beside them.
494
771
  h(
495
772
  Box,
496
773
  null,
497
- h(Box, { flexShrink: 0 }, motion ? h(Text, null, ...[...words].map((ch, i) => h(Text, { key: i, color: flow(i, frame) }, ch)), ' ') : h(Text, { color: ACCENT }, `${words} `)),
498
- h(Box, { flexShrink: 1 }, h(Text, { dimColor: true, wrap: 'truncate-end' }, `(${elapsed(time)}${spent}${quiet} · esc to interrupt)`)),
774
+ h(Box, { flexShrink: 0 }, flowing ? h(Text, null, ...[...words].map((ch, i) => h(Text, { key: i, color: flow(i, frame) }, ch)), ' ') : h(Text, { color: ACCENT }, `${words} `)),
775
+ h(Box, { flexShrink: 1 }, h(Text, { dimColor: true, wrap: 'truncate-end' }, status())),
499
776
  ),
500
- ...thinking.map((row, i) => h(Text, { key: i, dimColor: true, wrap: 'truncate' }, `${i === 0 ? ' ⎿ ' : ' '}${row}`)),
777
+ // The plan the model keeps in its reply: how far it has got, and what it says comes next.
778
+ plan ? h(Text, { dimColor: true, wrap: 'truncate-end' }, ` plan ${plan.done}/${plan.total}${plan.next ? ` · next: ${plan.next}` : ' · all done'}`) : null,
779
+ ...thinking.map((row, i) => h(Text, { key: i, dimColor: true, wrap: 'truncate' }, `${i === 0 ? ` ${g.under} ` : ' '}${row}`)),
501
780
  );
502
781
  }
503
782
 
783
+ const CHECKLIST_ITEM = /^\s*[-*+]\s+\[([ xX])\]\s+(.+?)\s*$/;
784
+
785
+ /**
786
+ * A checklist in what the model wrote — `- [ ]` and `- [x]` items — as a plan: how many are done, and the first that is
787
+ * not. The latest one is the plan: a checklist written after another replaces it. Null without one.
788
+ */
789
+ export function planOf(text) {
790
+ const lines = String(text ?? '').split('\n');
791
+ let end = lines.length - 1;
792
+ while (end >= 0 && !CHECKLIST_ITEM.test(lines[end])) end--;
793
+ if (end < 0) return null;
794
+ let start = end;
795
+ while (start > 0 && CHECKLIST_ITEM.test(lines[start - 1])) start--;
796
+ const items = lines.slice(start, end + 1).map((line) => CHECKLIST_ITEM.exec(line)).map(([, mark, said]) => ({ done: mark !== ' ', said }));
797
+ const next = items.find((item) => !item.done);
798
+ return { done: items.filter((item) => item.done).length, total: items.length, next: next ? inline(next.said, styles(false)) : null };
799
+ }
800
+
504
801
  /**
505
802
  * 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
506
803
  * 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
@@ -529,12 +826,14 @@ function Input({ state, width, rows, placeholder = '' }) {
529
826
  const shown = on === '' || on === '\n' ? ' ' : on;
530
827
  const after = on === '\n' ? text.slice(cursor) : text.slice(cursor + on.length);
531
828
  const hidden = (n) => (n > 0 ? h(Text, { dimColor: true }, `… +${n} line${n === 1 ? '' : 's'}`) : null);
829
+ // Plain, the box is its prompt alone: a frame is read out as a row of lines.
830
+ const framed = useMarks().tool === '⏺';
532
831
  return h(
533
832
  Box,
534
- { borderStyle: 'round', borderColor: 'gray', paddingX: 1, width },
833
+ { ...(framed ? { borderStyle: 'round', borderColor: 'gray', paddingX: 1 } : {}), width },
535
834
  h(Box, { flexShrink: 0 }, h(Text, null, '> ')),
536
835
  // An empty box says what it is for, faint behind the cursor, until something has been said.
537
- h(Box, { flexGrow: 1, flexShrink: 1, flexDirection: 'column' }, hidden(seen.above), h(Text, { wrap: !text && placeholder ? 'truncate-end' : 'wrap' }, untab(text.slice(0, cursor)), h(Text, { inverse: true }, untab(shown)), untab(after), !text && placeholder ? h(Text, { dimColor: true }, placeholder) : null), hidden(seen.below)),
836
+ 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)),
538
837
  );
539
838
  }
540
839
 
@@ -542,8 +841,27 @@ function Input({ state, width, rows, placeholder = '' }) {
542
841
  const MENU_ROWS = 8;
543
842
 
544
843
  /** 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. */
545
- function Menu({ menu, pick }) {
844
+ /**
845
+ * A description cut to its room where a clause ends — at `;`, `:` or ` — ` — so what is left still says something
846
+ * whole: "the MCP servers", not "the MCP servers: connected or not, their tools, what may run u…". With no such place
847
+ * in reach it is cut between words.
848
+ */
849
+ function clauseFit(text, room) {
850
+ if (text.length <= room) return text;
851
+ let cut = -1;
852
+ for (const mark of ['; ', ': ', ' — ']) {
853
+ for (let at = text.indexOf(mark); at !== -1 && at <= room; at = text.indexOf(mark, at + 1)) cut = Math.max(cut, at);
854
+ }
855
+ if (cut > 0) return text.slice(0, cut);
856
+ const space = text.lastIndexOf(' ', room - 2);
857
+ return space > 0 ? `${text.slice(0, space)} …` : text.slice(0, Math.max(0, room - 1));
858
+ }
859
+
860
+ function Menu({ menu, pick, columns = 80 }) {
861
+ const g = useMarks();
546
862
  const wide = Math.max(...menu.map((c) => c.label.length)) + 2;
863
+ // The row's room for the description: the window less its margins, the mark and the name.
864
+ const room = Math.max(10, columns - 4 - 2 - wide);
547
865
  const first = Math.min(Math.max(0, pick - MENU_ROWS + 1), Math.max(0, menu.length - MENU_ROWS));
548
866
  const shown = menu.slice(first, first + MENU_ROWS);
549
867
  const below = menu.length - first - shown.length;
@@ -552,7 +870,7 @@ function Menu({ menu, pick }) {
552
870
  { flexDirection: 'column', paddingX: 2 },
553
871
  first > 0 ? h(Text, { dimColor: true }, ` ↑ ${first} more`) : null,
554
872
  // A hint is one row: wrapped, its second line would stand under the names, where a name is looked for.
555
- ...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 ? '❯ ' : ' '}${c.label.padEnd(wide)}`, c.hint)),
873
+ ...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)),
556
874
  below > 0 ? h(Text, { dimColor: true }, ` ↓ ${below} more`) : null,
557
875
  );
558
876
  }
@@ -564,7 +882,7 @@ const dollars = (cost) => (cost >= 0.005 ? `$${cost.toFixed(2)}` : '');
564
882
  const KEYS = [
565
883
  ['enter', 'send'],
566
884
  ['\\ enter', 'a new line'],
567
- ['esc', 'stop the turn'],
885
+ ['esc', 'interrupt the turn'],
568
886
  ['↑ ↓', 'what you sent before'],
569
887
  ['ctrl-r', 'search what you sent'],
570
888
  ['ctrl-c', 'clear · twice to leave'],
@@ -591,7 +909,8 @@ function Keys({ columns }) {
591
909
  Box,
592
910
  { flexDirection: 'column', paddingX: 2 },
593
911
  ...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)))))),
594
- h(Text, { dimColor: true }, '/help has every command and key · any key closes this'),
912
+ // Broken only between its parts, as a question's keys are.
913
+ ...keyRows('/help has the commands too · any key closes this', columns - 4).map((row, i) => h(Text, { key: `more-${i}`, dimColor: true }, row)),
595
914
  );
596
915
  }
597
916
 
@@ -609,19 +928,33 @@ function Search({ search }) {
609
928
  );
610
929
  }
611
930
 
612
- /** 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 /new. */
931
+ /** 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. */
613
932
  export function contextTone(tokens) {
614
933
  const band = contextBand(tokens);
615
934
  return band === 'act' ? { color: 'red' } : band === 'watch' ? { color: 'yellow' } : { dimColor: true };
616
935
  }
617
936
 
937
+ /**
938
+ * 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
939
+ * off ("ctrl-o fu…"). One that is too long alone is cut between words, never inside one.
940
+ */
941
+ function fitHint(hint, room) {
942
+ if (hint.length <= room) return hint;
943
+ const parts = hint.split(' · ');
944
+ while (parts.length > 1 && parts.join(' · ').length > room) parts.pop();
945
+ const left = parts.join(' · ');
946
+ if (left.length <= room) return left;
947
+ const space = left.lastIndexOf(' ', room - 2);
948
+ return space > 0 ? `${left.slice(0, space)} …` : '';
949
+ }
950
+
618
951
  function Status({ session, leaving, notice, jobs, aside = [], pick = null, open = null, where, spent, overBudget = false, waiting, columns }) {
619
952
  const tokens = session.contextTokens;
620
- const size = tokens >= 1000 ? ` · ${Math.round(tokens / 1000)}k context${contextBand(tokens) === 'act' ? ' · /new' : ''}` : '';
953
+ const size = tokens >= 1000 ? ` · ${Math.round(tokens / 1000)}k context${contextBand(tokens) === 'act' ? ' · /handoff' : ''}` : '';
621
954
  const cost = dollars(spent) && ` · ${dollars(spent)}`;
622
955
  // Where the tools run: the project and the branch it is on. The header that says it scrolls away; this does not.
623
956
  const place = where ? `${where.name}${where.branch ? ` (${where.branch})` : ''}` : '';
624
- 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 · ? keys · ctrl-o full output';
957
+ 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';
625
958
  // In a narrow window the hints give way, then the place — unless the line has something to say just now, which the place
626
959
  // gives way to; the model, the size of the context and the cost never fold.
627
960
  const route = `${routeLine(session)}${size}${cost}`;
@@ -630,7 +963,7 @@ function Status({ session, leaving, notice, jobs, aside = [], pick = null, open
630
963
  const room = columns - 4 - route.length - 2;
631
964
  const said = leaving || notice;
632
965
  const placed = place && place.length + 3 <= room - (said ? hint.length + 2 : 0) ? place : '';
633
- const hinted = room - (placed ? placed.length + 3 : 0) >= 12 ? hint : '';
966
+ const hinted = room - (placed ? placed.length + 3 : 0) >= 12 ? fitHint(hint, room - (placed ? placed.length + 3 : 0)) : '';
634
967
  // 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
635
968
  // narrow window; the route stands at the right with the place beside it, while the keys keep room for their first words.
636
969
  if (jobs.length > 0) {
@@ -639,7 +972,7 @@ function Status({ session, leaving, notice, jobs, aside = [], pick = null, open
639
972
  return h(
640
973
  Box,
641
974
  { paddingX: 2, justifyContent: 'space-between', gap: 2 },
642
- h(Box, { flexShrink: 1 }, h(Text, { dimColor: true, wrap: 'truncate' }, hint)),
975
+ h(Box, { flexShrink: 1 }, h(Text, { dimColor: true, wrap: 'truncate' }, fitHint(hint, columns - 4 - route.length - 2 - (beside ? place.length + 3 : 0)))),
643
976
  h(Box, { flexShrink: 0, gap: 3 }, routed, beside ? h(Text, { dimColor: true }, place) : null),
644
977
  );
645
978
  }
@@ -652,104 +985,141 @@ function Status({ session, leaving, notice, jobs, aside = [], pick = null, open
652
985
  );
653
986
  }
654
987
 
655
- /** `/help`: every command with what it does, and the keys — written as a reply is, so it is drawn as one. */
656
- function helpText(commands) {
657
- const keys = [
658
- ['Enter', 'send — while the model works, it reads the message with its next step'],
659
- ['\\\\ then Enter · Shift-Enter · Option-Enter · Ctrl-J', 'a new line'],
660
- ['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'],
661
- ['Esc', 'stop the turn (first closes the command menu); what was waiting comes back to the box'],
662
- ['Ctrl-C', 'clear the box; on an empty one, stop the turn, or twice to leave — Ctrl-D leaves too'],
663
- ['Ctrl-O', 'the whole conversation in your pager ($PAGER, or less): every command and all its output, to scroll and search'],
664
- ['Ctrl-G', 'write the message in your editor ($VISUAL or $EDITOR); what you save comes back to the box'],
665
- ['@ 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'],
666
- ['Ctrl-V', 'paste an image from the clipboard; an image file dropped on the box is the image'],
667
- ['Ctrl-R', 'search what you sent before: type to narrow, Ctrl-R again to go further back, Enter keeps it, Esc puts your draft back'],
668
- ['?', 'on an empty box: the keys most reached for'],
669
- ['Ctrl-A · Ctrl-E', 'the start and the end of the line'],
670
- ['Ctrl-B · Ctrl-F', 'a character back, or on'],
671
- ['Ctrl-U · Ctrl-K', 'cut to the start, or to the end, of the line'],
672
- ['Ctrl-W · Option-Backspace · Option-D', 'cut the word before the cursor, or after it'],
673
- ['Ctrl-Y', 'put back what was cut last — Ctrl-C\'s clearing included'],
674
- ['Ctrl-_', 'undo the last change to the box'],
675
- ['Option-Left · Option-Right', 'a word at a time'],
676
- ['1 – 9', 'on a question with an empty box: pick that option'],
677
- ['Ctrl-L', 'draw the screen again'],
678
- ['Ctrl-Z', 'suspend the chat to the shell, when nothing is at work; fg brings it back'],
679
- ['! command', 'run a command yourself, where the agent would be refused; the model sees what it printed'],
680
- ['@ message · @j<id> message', 'say it to the job that is running — the one open, when one is — or to a named one'],
681
- ['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'],
682
- ];
683
- return [
684
- '**Commands**',
685
- '',
686
- '| Command | What it does |',
687
- '|---|---|',
688
- ...commands.map((c) => `| \`/${c.name}\` | ${c.hint.replaceAll('|', '\\|')} |`),
689
- '',
690
- '**Keys**',
691
- '',
692
- '| Key | What it does |',
693
- '|---|---|',
694
- ...keys.map(([key, does]) => `| ${key} | ${does} |`),
695
- '',
696
- ].join('\n');
697
- }
988
+ /** The keys /help lists under the commands, a row each: the ones most reached for. `?` on an empty box shows them at a glance. */
989
+ const HELP_KEYS = [
990
+ ['enter', 'send; while the model works, it reads it next'],
991
+ ['\\ enter', 'a new line (shift-enter and ctrl-j too)'],
992
+ ['esc', 'interrupt the turn, or close a menu'],
993
+ ['↑ ↓', 'what you sent before'],
994
+ ['ctrl-r', 'search what you sent'],
995
+ ['ctrl-c', 'clear the box; twice on an empty one to leave'],
996
+ ['ctrl-o', 'the whole conversation in your pager'],
997
+ ['ctrl-g', 'write the message in your editor'],
998
+ ['ctrl-v', 'paste an image'],
999
+ ['ctrl-z', 'suspend to the shell; fg brings it back'],
1000
+ ['@ file', 'name a file of the project'],
1001
+ ['! command', 'run a command yourself'],
1002
+ ['@j<id> message', 'talk to a job at work'],
1003
+ ];
1004
+
1005
+ /** `/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. */
1006
+ const helpRows = (commands) => [...commands.map((c) => ({ key: `/${c.name}${c.args ? ` ${c.args}` : ''}`, does: c.hint })), null, ...HELP_KEYS.map(([key, does]) => ({ key, does }))];
1007
+
1008
+ /** What an empty chat suggests under its header, faint: something to try, and where the rest is. */
1009
+ const STARTER = 'try "explain this project" or "add a test for @file" · /help for more';
1010
+ /** The rows the suggestion takes at the top of the room, with a blank row on either side of it. */
1011
+ const STARTER_ROWS = 3;
698
1012
 
699
1013
  /**
700
- * The room between the conversation and the box, with the logo behind it: faint, in the middle of the window, where it stays while
701
- * 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.
1014
+ * 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
1015
+ * — faint, in the middle of the window. Whatever takes rows from the room — a menu under the box, what was said — moves the
1016
+ * 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
1017
+ * of the screen starts on.
702
1018
  */
703
- function Room({ logo, rows, from }) {
1019
+ function Room({ logo, rows, from, starter = false }) {
704
1020
  const ref = useRef(null);
705
1021
  const { width, height, top, hasMeasured } = useBoxMetrics(ref);
706
1022
  const wide = Math.max(0, ...logo.map((row) => row.length));
707
- const at = Math.floor((rows - logo.length) / 2) - from - top;
708
- const seen = logo.length > 0 && hasMeasured && width >= wide && at < height && at + logo.length > 0;
1023
+ const clear = starter ? STARTER_ROWS : 0;
1024
+ const at = Math.max(clear, Math.min(Math.floor((rows - logo.length) / 2) - from - top, height - logo.length));
1025
+ const seen = logo.length > 0 && hasMeasured && width >= wide && at + logo.length <= height;
709
1026
  return h(
710
1027
  Box,
711
1028
  { ref, flexGrow: 1, flexDirection: 'column', overflow: 'hidden' },
1029
+ starter ? h(Box, { marginTop: 1 }, h(Text, { dimColor: true, wrap: 'truncate-end' }, STARTER)) : null,
712
1030
  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,
713
1031
  );
714
1032
  }
715
1033
 
716
- function App({ session, events, messages, cwd, block, opening, logo, clipboard, copy, notify: alerts, notifyAfterMs, quietAfterMs, run, listFiles, motion, progress }) {
1034
+ function App({ session, events, messages, cwd, block, opening, logo, clipboard, copy, notify: alerts, notifyAfterMs, quietAfterMs, run, listFiles, motion, progress, plain = false, front = { now: true } }) {
717
1035
  const { exit, suspendTerminal, waitUntilRenderFlush } = useApp();
718
1036
  const { stdout, write } = useStdout();
719
1037
  const { columns, rows } = useWindowSize();
720
1038
  const [, redraw] = useReducer((n) => n + 1, 0);
721
1039
  // Addresses in a reply open on a click; the pager gets none of that, since a pager may draw its codes as text.
722
- const s = styles(colourEnabled(stdout), { links: true });
723
- const paged = styles(colourEnabled(stdout));
724
- const header = (text) => ({ kind: 'header', route: routeLine(session), cwd: tilde(cwd), block: text });
1040
+ const s = styles(colourEnabled(stdout), { links: true, plain });
1041
+ const paged = styles(colourEnabled(stdout), { plain });
1042
+ /**
1043
+ * The top of a session: who answers, and where the tools work — the project, which is not always the folder the chat was
1044
+ * 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.
1045
+ */
1046
+ const header = (text) => {
1047
+ const at = session.where().cwd;
1048
+ const away = at === scratchDir() && realOrSame(cwd) !== at ? tilde(cwd) : null;
1049
+ const where = session.where();
1050
+ return { kind: 'header', route: routeLine(session), place: `${where.name}${where.branch ? ` (${where.branch})` : ''}`, cwd: tilde(at), away, block: text };
1051
+ };
725
1052
  // 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.
726
1053
  // `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.
727
1054
  const st = useRef(null);
728
1055
  // `live` is what each running command has printed so far and since when; `heard`, when the model last said or did anything;
729
1056
  // `turn`, what the turn in hand has done; `talking`, that the model — not a `!` command — is what the screen is working on;
730
1057
  // `pick`, the job under the box that Down has stepped onto; `open`, the one whose record is shown.
731
- 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: [], 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 };
1058
+ 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 };
732
1059
  const state = st.current;
733
1060
  state.columns = columns;
734
1061
  state.rows = rows;
735
1062
 
1063
+ /**
1064
+ * An item as it is placed: its id, and whether a blank line of a reply stands right before it — then that line is the
1065
+ * row between them, and the item's own blank row over it is not drawn: never two blank rows in a row.
1066
+ */
1067
+ const stamped = (item) => {
1068
+ const last = state.items.at(-1);
1069
+ return { id: state.next++, afterBlank: last?.kind === 'text' && !String(last.text ?? '').trim(), ...item };
1070
+ };
736
1071
  const place = (items) => {
737
- const placed = items.map((item) => ({ id: state.next++, ...item }));
738
- state.items = [...state.items, ...placed];
739
- state.unmeasured.push(...placed);
1072
+ for (const item of items) {
1073
+ const placed = stamped(item);
1074
+ state.items = [...state.items, placed];
1075
+ state.unmeasured.push(placed);
1076
+ }
740
1077
  };
741
1078
  /**
742
1079
  * 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
743
1080
  * 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.
1081
+ * 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
1082
+ * `unmeasured` only once it is counted, and a draw it sets off keeps the room shut rather than one row too tall.
744
1083
  */
1084
+ const rowsOf = (item) => renderToString(h(Marks.Provider, { value: s.g }, h(Item, { item, columns: state.columns, s })), { columns: state.columns }).split('\n').length;
745
1085
  const measure = () => {
746
- for (const item of state.unmeasured.splice(0)) {
747
- if (state.used < state.rows) state.used += renderToString(h(Item, { item, columns: state.columns, s }), { columns: state.columns }).split('\n').length;
1086
+ while (state.unmeasured.length > 0) {
1087
+ if (state.used < state.rows) state.used += rowsOf(state.unmeasured[0]);
1088
+ state.unmeasured.shift();
748
1089
  }
749
1090
  };
1091
+ /**
1092
+ * Reads one after another are drawn as one row: they wait here, under the work, until something else comes — and
1093
+ * anything that goes on the screen first puts them there, as the row they make. The log keeps every one of them.
1094
+ */
1095
+ state.reads ??= [];
1096
+ const isRead = (entry) => entry.kind === 'tool' && entry.call.name === EDITOR_TOOL.name && entry.call.input?.command === 'view' && !entry.result.isError && !entry.started?.length;
1097
+ const readsDrawn = (reads) => {
1098
+ if (reads.length === 1) return drawn(reads[0]);
1099
+ // 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.
1100
+ const paths = [...new Set(reads.map((entry) => String(entry.call.input?.path ?? '')))];
1101
+ const names = paths.map((p) => basename(p));
1102
+ const seen = paths.map((p, i) => (names.indexOf(names[i]) === names.lastIndexOf(names[i]) ? names[i] : pathFrom(p, state.where.cwd)));
1103
+ const named = seen.length > 2 ? [...seen.slice(0, 2), `+${seen.length - 2}`] : seen;
1104
+ const lines = reads.reduce((sum, entry) => sum + (entry.result.content === '' ? 0 : entry.result.content.replace(/\n$/, '').split('\n').length), 0);
1105
+ const files = new Set(reads.map((entry) => entry.call.input?.path)).size;
1106
+ return [{ kind: 'tool', view: { title: `Read ${files} file${files === 1 ? '' : 's'}`, detail: named.join(', '), group: true, lines: [{ text: `${lines} lines`, tone: 'dim' }] }, failed: false, took: reads.reduce((sum, entry) => sum + (entry.took ?? 0), 0) }];
1107
+ };
1108
+ const placeReads = () => {
1109
+ if (state.reads.length > 0) place(readsDrawn(state.reads.splice(0)));
1110
+ };
1111
+ /**
1112
+ * Items for the screen, each counted before it is placed: a draw that counting one sets off sees the screen as it was —
1113
+ * 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
1114
+ * and the box is left standing above the foot. What was placed and not counted yet is counted first.
1115
+ */
750
1116
  const show = (items) => {
751
- place(items);
752
1117
  measure();
1118
+ for (const item of [...(state.reads.length > 0 ? readsDrawn(state.reads.splice(0)) : []), ...items]) {
1119
+ const placed = stamped(item);
1120
+ if (state.used < state.rows) state.used += rowsOf(placed);
1121
+ state.items = [...state.items, placed];
1122
+ }
753
1123
  redraw();
754
1124
  };
755
1125
  /** A renderer for a reply: each line it finishes goes on the screen, the first of a block with the mark. */
@@ -786,6 +1156,9 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
786
1156
  { text: `their report comes here when all ${started.length} are done`, tone: 'dim' },
787
1157
  ];
788
1158
  }
1159
+ // A question's answer is the user's: said as theirs, without what rode with it for the model.
1160
+ const answered = entry.call.name === ASK_TOOL.name && !entry.result.isError ? /^The user (chose|answered): ([^\n]*)/.exec(entry.result.content) : null;
1161
+ if (answered) view.lines = [{ text: answered[1] === 'chose' ? `you chose ${answered[2]}` : `you answered: ${answered[2]}`, tone: 'plain' }];
789
1162
  return [{ kind: 'tool', view, failed: entry.result.isError, took: entry.took ?? 0 }];
790
1163
  }
791
1164
  // What the user's own command printed: drawn as a tool's output is, under the line they typed.
@@ -795,6 +1168,8 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
795
1168
  const lines = entry.text.split('\n');
796
1169
  if (lines.length > ECHO_LINES) return [{ ...entry, text: lines.slice(0, ECHO_LINES).join('\n'), more: lines.length - ECHO_LINES }];
797
1170
  }
1171
+ // A note for the pager alone — which guide rode in with a message — is not drawn on the screen.
1172
+ if (entry.kind === 'note' && entry.quiet) return [];
798
1173
  if (entry.kind !== 'reply') return [entry];
799
1174
  const lines = [];
800
1175
  state.fresh = true;
@@ -805,13 +1180,27 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
805
1180
  }
806
1181
  const record = (entry) => {
807
1182
  state.log.push(entry);
808
- show(drawn(entry));
1183
+ if (!isRead(entry)) return show(drawn(entry));
1184
+ state.reads.push(entry);
1185
+ redraw();
1186
+ };
1187
+ /** 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`). */
1188
+ const placeLog = (open = false) => {
1189
+ state.reads = [];
1190
+ for (const entry of state.log) {
1191
+ if (isRead(entry)) state.reads.push(entry);
1192
+ else {
1193
+ placeReads();
1194
+ place(drawn(entry));
1195
+ }
1196
+ }
1197
+ if (!open) placeReads();
809
1198
  };
810
1199
  if (state.log.length === 0) {
811
1200
  state.log.push(header(block));
812
1201
  // 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.
813
1202
  if (opening) state.log.push(...replayOf(session.params.messages), { kind: 'note', text: opening });
814
- for (const entry of state.log) place(drawn(entry));
1203
+ placeLog();
815
1204
  }
816
1205
 
817
1206
  /** The jobs at work with no call standing over them, by id: the ones under the box. */
@@ -843,6 +1232,19 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
843
1232
  state.fresh = true;
844
1233
  };
845
1234
 
1235
+ /**
1236
+ * The reply in hand thrown away, as the loop throws it away: the try it came from failed and is being sent again, or
1237
+ * the model declined it. What has not been drawn is not drawn; none of it joins the log, so the pager, /copy and
1238
+ * /export never have it, and the next text starts a block of its own.
1239
+ */
1240
+ const dropReply = () => {
1241
+ state.raw = '';
1242
+ state.fresh = true;
1243
+ state.thought = '';
1244
+ state.thinking = null;
1245
+ if (state.reply) state.reply = replyTo((item) => show([item]));
1246
+ };
1247
+
846
1248
  /**
847
1249
  * Everything again, from the log, after the window changed size — the window and its scrollback wiped, since what they
848
1250
  * hold is drawn again. A session that starts over has nothing to draw again:
@@ -852,7 +1254,7 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
852
1254
  state.items = [];
853
1255
  state.unmeasured = [];
854
1256
  state.used = 0;
855
- for (const entry of state.log) place(drawn(entry));
1257
+ placeLog(Boolean(state.working));
856
1258
  measure();
857
1259
  state.fresh = true;
858
1260
  if (state.working) {
@@ -871,7 +1273,7 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
871
1273
 
872
1274
  /** A bell and a notification, when the window is not the one in front: the turn is over, or it waits for an answer. */
873
1275
  const alert = (text) => {
874
- if (alerts && !state.focused) tell(`\x1b]9;sumo — ${safeForTerminal(text).replace(/\s+/g, ' ')}\x07\x07`);
1276
+ if (alerts && !front.now) tell(`\x1b]9;sumo — ${safeForTerminal(text).replace(/\s+/g, ' ')}\x07\x07`);
875
1277
  };
876
1278
 
877
1279
  /** 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. */
@@ -880,8 +1282,12 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
880
1282
  state.spent = session.spent();
881
1283
  state.where = session.where();
882
1284
  const { calls, edited } = state.turn;
883
- const files = [...edited];
884
- 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` : ''}` : '', state.tokens > 0 ? `↓ ${thousands(state.tokens)} tokens` : '', dollars(state.spent - before)];
1285
+ // The files by their names, as the rows above them were: each edit's row has its path.
1286
+ const files = [...new Set([...edited].map((path) => basename(path)))];
1287
+ // A turn quicker than a second has no time worth saying: `0s` reads as nothing happened.
1288
+ 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)];
1289
+ // The turn is over: reads still waiting for what comes after them go on the screen now.
1290
+ if (state.reads.length > 0) show([]);
885
1291
  if (calls > 0 || took >= notifyAfterMs) record({ kind: 'footer', text: parts.filter(Boolean).join(' · ') });
886
1292
  if (took >= notifyAfterMs) alert(`${state.where.name}: ${ended}`);
887
1293
  };
@@ -896,6 +1302,7 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
896
1302
 
897
1303
  /** The screen let go: the box and the margin under it are cleared first, so what stays in the terminal is the conversation. */
898
1304
  const close = () => {
1305
+ placeReads();
899
1306
  state.closed = true;
900
1307
  redraw();
901
1308
  // The cleared frame is drawn before the screen lets go, however slow the machine: exit waits for it.
@@ -906,10 +1313,28 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
906
1313
  const settle = (ask, answer) => {
907
1314
  if (!state.asks.includes(ask)) return;
908
1315
  state.asks = state.asks.filter((a) => a !== ask);
1316
+ if (state.why?.ask === ask) state.why = null;
1317
+ if (state.explain?.ask === ask) {
1318
+ clearTimeout(state.explain.timer);
1319
+ state.explain = null;
1320
+ }
909
1321
  ask.resolve(answer);
910
1322
  redraw();
911
1323
  };
912
1324
 
1325
+ /** A key that answers nothing on a waiting call: for a moment the panel says what each key does, in place of its keys. */
1326
+ const explainKeysOf = (ask) => {
1327
+ clearTimeout(state.explain?.timer);
1328
+ state.explain = {
1329
+ ask,
1330
+ timer: setTimeout(() => {
1331
+ state.explain = null;
1332
+ redraw();
1333
+ }, NOTICE_MS),
1334
+ };
1335
+ redraw();
1336
+ };
1337
+
913
1338
  /** Said under the box for a moment, in place of the hints: why a key did nothing. */
914
1339
  const notify = (text) => {
915
1340
  clearTimeout(state.notice?.timer);
@@ -951,46 +1376,65 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
951
1376
  return record({ kind: 'shell', result: { content: await session.shell(line.slice(1).trim()), isError: false } });
952
1377
  }
953
1378
  const { text, said, guide, control, args, error } = session.expand(line);
954
- if (error) return record({ kind: 'error', text: error });
1379
+ // A command mistyped is no failure: what was typed, and the command it was nearest to.
1380
+ if (error) {
1381
+ record({ kind: 'user', text: line });
1382
+ return record({ kind: 'note', text: error });
1383
+ }
955
1384
  if (control === 'quit') return leave();
956
- if (control === 'new') {
957
- session.end();
958
- state.log = [];
1385
+ if (control === 'new' || control === 'handoff') {
1386
+ // 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.
1387
+ let handed = null;
1388
+ if (control === 'handoff') {
1389
+ record({ kind: 'user', text: line });
1390
+ state.working = 'writing the hand-off';
1391
+ state.talking = true;
1392
+ redraw();
1393
+ try {
1394
+ handed = await session.handoff();
1395
+ } finally {
1396
+ state.working = null;
1397
+ state.talking = false;
1398
+ }
1399
+ } else {
1400
+ session.end();
1401
+ }
959
1402
  // The old session's pictures go with it; their numbers stay taken, so a marker recalled from before names nothing.
960
1403
  state.images = state.images.map(() => null);
961
1404
  state.pastes = state.pastes.map(() => null);
962
1405
  state.overBudget = false;
963
- const block = session.start('new');
1406
+ const block = handed ? handed.block : session.start('new');
964
1407
  state.where = session.where();
965
1408
  state.spent = session.spent();
966
- refresh(scrolledClear(state.rows));
967
- return record(header(block));
1409
+ // The new session is in the log before the window is drawn again: one frame, measured under its header. A frame drawn
1410
+ // first for an empty window would be written after the header, still that tall, and scroll the header away.
1411
+ 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}` }] : [])];
1412
+ return refresh(scrolledClear(state.rows));
968
1413
  }
969
1414
  if (control === 'resume') {
970
1415
  record({ kind: 'user', text: line });
971
1416
  if (!args) {
972
1417
  const saved = session.saved();
973
- return record({ kind: 'note', text: saved.length > 0 ? saved.join('\n') : 'no saved sessions' });
1418
+ return record({ kind: 'note', text: saved.length > 0 ? `${saved.join('\n')}\nopen one with /resume <id>` : 'no saved sessions' });
974
1419
  }
975
1420
  // Refused — no such session, or one open elsewhere — nothing changes, and the refusal is shown below like any other error.
976
1421
  const said = session.resume(args);
977
- state.log = [];
978
1422
  state.images = state.images.map(() => null);
979
1423
  state.pastes = state.pastes.map(() => null);
980
1424
  state.overBudget = false;
981
1425
  state.where = session.where();
982
1426
  state.spent = session.spent();
983
- refresh(scrolledClear(state.rows));
984
- record(header(''));
985
1427
  // 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.
986
- for (const entry of replayOf(session.params.messages)) record(entry);
987
- return record({ kind: 'note', text: said });
1428
+ // In the log before the window is drawn again, as for /new.
1429
+ state.log = [header(''), ...replayOf(session.params.messages), { kind: 'note', text: said }];
1430
+ return refresh(scrolledClear(state.rows));
988
1431
  }
989
1432
  if (control === 'copy') {
990
1433
  record({ kind: 'user', text: line });
991
1434
  // A number goes further back: /copy 2 is the reply before the last, /copy code 2 the code block before the last.
992
1435
  const asked = /^(code)?\s*(\d+)?$/.exec(args);
993
- if (!asked || asked[2] === '0') return record({ kind: 'error', text: `/copy takes nothing, "code", a number, or both — /copy 2 is the reply before the last — not "${args}"` });
1436
+ // What /copy cannot take, or has nothing to take, is no failure: it is said as a note.
1437
+ 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}"` });
994
1438
  const [, code, n] = asked;
995
1439
  const back = Number(n ?? 1);
996
1440
  // The reply as the model wrote it, not as the screen drew it: no indent, no line broken to fit the window.
@@ -998,7 +1442,7 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
998
1442
  const blocks = replies.flatMap((entry) => [...entry.raw.matchAll(/^[ \t]*```[^\n]*\n([\s\S]*?)^[ \t]*```[ \t]*$/gm)].map((m) => m[1]));
999
1443
  const text = (code ? blocks.at(-back) : replies.at(-back)?.raw)?.replace(/\n+$/, '');
1000
1444
  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`;
1001
- if (!text) return record({ kind: 'error', 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' });
1445
+ 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' });
1002
1446
  // Where no clipboard command takes it, the terminal is asked to (OSC 52).
1003
1447
  const taken = await copy(text);
1004
1448
  if (!taken) tell(`\x1b]52;c;${Buffer.from(text).toString('base64')}\x07`);
@@ -1022,15 +1466,23 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1022
1466
  const file = exportPath(args, state.where.cwd, session.sessionId);
1023
1467
  mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
1024
1468
  writeFileSync(file, markdownOf(state.log, { cwd: state.where.cwd, title: `Sumo — ${state.where.name}` }), { mode: 0o600 });
1025
- return record({ kind: 'note', text: `the conversation is in ${tilde(file)}` });
1469
+ // Named as the calls name files: from the project when it went there.
1470
+ return record({ kind: 'note', text: `the conversation is in ${pathFrom(file, state.where.cwd)}` });
1026
1471
  }
1472
+ // The chat's own words, not the model's: not drawn as a reply, and not what /copy takes.
1027
1473
  if (control === 'help') {
1028
1474
  record({ kind: 'user', text: line });
1029
- return record({ kind: 'reply', raw: helpText(session.commands), own: true });
1475
+ return record({ kind: 'help', rows: helpRows(session.commands) });
1476
+ }
1477
+ // The route said as the status row says it, and how to change it.
1478
+ if (control === 'model') {
1479
+ record({ kind: 'user', text: line });
1480
+ session.route(args);
1481
+ return record({ kind: 'note', text: args ? `${routeLine(session)} from the next message` : `${routeLine(session)} · /model <model> <effort> changes it` });
1030
1482
  }
1031
- if (control === 'model' || control === 'memory' || control === 'mcp' || control === 'undo') {
1483
+ if (control === 'memory' || control === 'mcp' || control === 'undo') {
1032
1484
  record({ kind: 'user', text: line });
1033
- const text = control === 'model' ? session.route(args) : control === 'undo' ? session.undo() : control === 'mcp' ? (await session.mcp()).join('\n') : await session.memoryPage();
1485
+ const text = control === 'undo' ? session.undo() : control === 'mcp' ? (await session.mcp()).join('\n') : await session.memoryPage();
1034
1486
  return record({ kind: 'note', text });
1035
1487
  }
1036
1488
  record({ kind: 'user', text: line });
@@ -1063,12 +1515,15 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1063
1515
  record({ kind: 'error', ...explained(cause.message) });
1064
1516
  return closeTurn(began, before, 'stopped on an error');
1065
1517
  }
1518
+ // A declined reply is not kept by the loop, and what streamed of it is not an answer: it leaves the screen as well.
1519
+ if (outcome?.stop === 'refusal') dropReply();
1066
1520
  closeReply();
1067
1521
  // Nothing was waiting after all: no turn was run.
1068
1522
  if (!outcome) return undefined;
1069
1523
  if (outcome.stop === 'interrupted') record({ kind: 'note', text: 'Interrupted · say what it should do instead' });
1070
1524
  if (outcome.stop === 'error') record({ kind: 'error', ...explained(outcome.error) });
1071
- if (stopReason(outcome.stop)) record({ kind: 'note', text: stopReason(outcome.stop) });
1525
+ 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` });
1526
+ else if (stopReason(outcome.stop, outcome.stopDetail)) record({ kind: 'note', text: stopReason(outcome.stop, outcome.stopDetail) });
1072
1527
  return closeTurn(began, before, outcome.stop === 'error' ? 'stopped on an error' : outcome.stop === 'interrupted' ? 'interrupted' : 'done');
1073
1528
  }
1074
1529
 
@@ -1085,6 +1540,10 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1085
1540
  state.working = null;
1086
1541
  state.talking = false;
1087
1542
  state.thought = '';
1543
+ // The plan and a countdown were the turn's: the next one starts without them.
1544
+ state.plan = null;
1545
+ state.retry = null;
1546
+ state.retried = null;
1088
1547
  redraw();
1089
1548
  if (state.gone) close();
1090
1549
  }
@@ -1117,9 +1576,10 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1117
1576
  function stopJob(line, given) {
1118
1577
  record({ kind: 'user', text: line });
1119
1578
  const ids = session.running();
1120
- if (ids.length === 0) return record({ kind: 'error', text: 'no job is at work in the background' });
1579
+ // No job to stop, or which one, is a note: nothing went wrong.
1580
+ if (ids.length === 0) return record({ kind: 'note', text: 'no job is at work in the background' });
1121
1581
  const id = given ? Number(/^j?(\d+)$/.exec(given)?.[1]) : ids.length === 1 ? ids[0] : NaN;
1122
- if (!ids.includes(id)) return record({ kind: 'error', text: `which one — ${ids.map((j) => `/stop j${j}`).join(' or ')}` });
1582
+ if (!ids.includes(id)) return record({ kind: 'note', text: `which one — ${ids.map((j) => `/stop j${j}`).join(' or ')}` });
1123
1583
  session.stop(id);
1124
1584
  return record({ kind: 'note', text: `stopping j${id} — it can be picked up again: ask for it by its id` });
1125
1585
  }
@@ -1252,8 +1712,8 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1252
1712
  */
1253
1713
  const suspend = async () => {
1254
1714
  if (state.away) return;
1255
- if (process.platform === 'win32') return notify('Ctrl-Z does not suspend on Windows');
1256
- if (state.working || session.running().length > 0) return notify('Ctrl-Z waits until nothing is at work — esc stops the turn');
1715
+ if (process.platform === 'win32') return notify('ctrl-z does not suspend on Windows');
1716
+ if (state.working || session.running().length > 0) return notify('ctrl-z waits until nothing is at work — esc interrupts the turn');
1257
1717
  state.away = true;
1258
1718
  let stopped = true;
1259
1719
  try {
@@ -1285,7 +1745,7 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1285
1745
  state.away = false;
1286
1746
  refresh();
1287
1747
  }
1288
- if (!stopped) notify('Ctrl-Z: there is no shell here to suspend the chat into');
1748
+ if (!stopped) notify('ctrl-z: there is no shell here to suspend the chat into');
1289
1749
  };
1290
1750
 
1291
1751
  /** 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. */
@@ -1304,6 +1764,10 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1304
1764
  state.thought = '';
1305
1765
  state.raw += chunk;
1306
1766
  state.reply?.write(chunk);
1767
+ // A checklist in the reply is the plan the turn works to: the latest one, under the working line.
1768
+ state.plan = planOf(state.raw) ?? state.plan;
1769
+ // Text came: a request sent again has gone through.
1770
+ state.retry = null;
1307
1771
  redraw();
1308
1772
  };
1309
1773
  // 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.
@@ -1315,7 +1779,20 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1315
1779
  redraw();
1316
1780
  };
1317
1781
  // A request being sent again, or a job's conversation summarized to make room: said where the work shows, with the job's id.
1318
- const onRetry = (r) => record({ kind: 'note', text: `${r.job ? `j${r.job}: ` : ''}${retryLine(r)}` });
1782
+ // A request of the chat's own being sent again counts down on the working line; the scroll says why, in words — once
1783
+ // for a run of tries that fail the same way, again when the reason changes. A reply that broke off half-way is thrown
1784
+ // away, as the loop throws it away, and the scroll says so.
1785
+ const onRetry = (r) => {
1786
+ if (r.job) return record({ kind: 'note', text: `j${r.job}: ${retryNote(r)}` });
1787
+ state.retry = { until: Date.now() + r.delayMs, attempt: r.attempt, limit: r.limit };
1788
+ const broke = Boolean(state.raw);
1789
+ if (broke) dropReply();
1790
+ const why = retryWhy(r.reason);
1791
+ const said = broke ? `the reply broke off: ${why} · asking again` : retryNote(r);
1792
+ if (state.retried === `${broke}${why}`) return redraw();
1793
+ state.retried = `${broke}${why}`;
1794
+ record({ kind: 'note', text: said });
1795
+ };
1319
1796
  const onCompact = (c) => record({ kind: 'note', text: `${c.job ? `j${c.job}: ` : ''}${compactLine(c)}` });
1320
1797
  // The session has passed what it may cost before it is said: said once, where the retries are.
1321
1798
  const onBudget = ({ text }) => {
@@ -1361,16 +1838,20 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1361
1838
  // What the model was handed without being asked: a way of working, or the check it stopped short of.
1362
1839
  const onGuide = ({ name }) => {
1363
1840
  closeReply();
1364
- record({ kind: 'note', text: `guide: ${name}` });
1841
+ // For the pager alone: put in the log, not drawn — drawing nothing would still close a row of reads still growing.
1842
+ state.log.push({ kind: 'note', text: `guide: ${name}`, quiet: true });
1365
1843
  };
1366
1844
  // The pages a reply cites, under it. A title is a page's own words: nothing in it may drive the terminal.
1367
1845
  const onSources = ({ sources }) => {
1368
1846
  closeReply();
1369
1847
  record({ kind: 'note', text: `sources:\n${sources.map((page) => safeForTerminal(`${page.title} — ${page.url}`).replace(/\s+/g, ' ')).join('\n')}` });
1370
1848
  };
1849
+ // The turn goes on once: what it edited, what has not checked it, and what the model is asked to do about that.
1371
1850
  const onCheck = ({ edited, checks }) => {
1372
1851
  closeReply();
1373
- record({ kind: 'note', text: `held: ${edited.length} file${edited.length === 1 ? '' : 's'} edited, ${checks.length > 0 ? `${checks.join(' and ')} not run` : 'no check declared'}` });
1852
+ const what = edited.length === 1 ? basename(edited[0]) : `${edited.length} files`;
1853
+ const them = edited.length === 1 ? 'it' : 'them';
1854
+ 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}` });
1374
1855
  };
1375
1856
  // 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.
1376
1857
  const onResult = ({ call, result, job }) => {
@@ -1414,6 +1895,8 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1414
1895
  redraw();
1415
1896
  };
1416
1897
  const onUsage = ({ totals }) => {
1898
+ // A reply came back: a request that fails after it is a new run of tries, and its reason is said again.
1899
+ state.retried = null;
1417
1900
  state.tokens = totals.outputTokens;
1418
1901
  state.heard = Date.now();
1419
1902
  state.spent = session.spent();
@@ -1423,7 +1906,7 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1423
1906
  const onApprove = (ask) => {
1424
1907
  state.asks.push(ask);
1425
1908
  ask.signal?.addEventListener('abort', () => settle(ask, 'no'), { once: true });
1426
- alert(`${state.where.name}: ${ask.unsandboxed ? 'a command waits to run outside the sandbox' : `${ask.server} · ${ask.tool} waits for your answer`}`);
1909
+ 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`}`);
1427
1910
  redraw();
1428
1911
  };
1429
1912
  // A question of the model's: shown with its options, the first one picked, until a pick or a typed answer settles it.
@@ -1444,6 +1927,7 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1444
1927
  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);
1445
1928
  clearTimeout(state.leaving);
1446
1929
  clearTimeout(state.notice?.timer);
1930
+ clearTimeout(state.explain?.timer);
1447
1931
  clearTimeout(state.drawSoon);
1448
1932
  // The terminal as it was found: no more word of its focus, and its own title back.
1449
1933
  tell(`${FOCUS_OFF}${TITLE_BACK}`);
@@ -1496,11 +1980,6 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1496
1980
  useInput((input, key) => {
1497
1981
  // The terminal's answer to Ink's keyboard-protocol query, when it comes after Ink stopped waiting for it.
1498
1982
  if (/^\[\?\d+u$/.test(input)) return;
1499
- // The terminal saying its window came to the front, or went behind: not something typed.
1500
- if (input === '[I' || input === '[O') {
1501
- state.focused = input === '[I';
1502
- return;
1503
- }
1504
1983
  for (const [one, oneKey] of keysOf(input, key)) {
1505
1984
  // Ctrl-R looking back through what was sent takes every key, Esc and Ctrl-C too: they put the draft back, and stop nothing.
1506
1985
  if (state.ed.search) {
@@ -1527,13 +2006,24 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1527
2006
  else asked.at = Math.max(0, Math.min(asked.options.length - 1, asked.at + (oneKey.downArrow ? 1 : -1)));
1528
2007
  continue;
1529
2008
  }
2009
+ // 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.
2010
+ if (state.why && state.why.ask === state.asks[0] && !(oneKey.ctrl && (one === 'c' || one === 'd'))) {
2011
+ if (oneKey.escape) state.why = null;
2012
+ else if (oneKey.return) settle(state.why.ask, state.why.text.trim() ? { no: state.why.text.trim() } : 'no');
2013
+ else if (oneKey.backspace || oneKey.delete) state.why.text = state.why.text.slice(0, -1);
2014
+ else if (!oneKey.ctrl && !oneKey.meta && one) state.why.text += one.replace(/[\r\n]+/g, ' ');
2015
+ redraw();
2016
+ continue;
2017
+ }
1530
2018
  // 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.
1531
2019
  if (!asked && state.asks.length > 0 && !oneKey.escape && !(oneKey.ctrl && (one === 'c' || one === 'd'))) {
1532
- // A run outside the sandbox is this one run or none: there is no always for it.
1533
- const unsandboxed = state.asks[0].unsandboxed;
1534
- const answer = (unsandboxed ? { y: 'once', n: 'no' } : { y: 'once', a: 'always', n: 'no' })[one];
1535
- if (answer) settle(state.asks[0], answer);
1536
- 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');
2020
+ // 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.
2021
+ const answer = answerOf(state.asks[0], one);
2022
+ if (answer === 'why') {
2023
+ state.why = { ask: state.asks[0], text: '' };
2024
+ redraw();
2025
+ } else if (answer) settle(state.asks[0], answer);
2026
+ else explainKeysOf(state.asks[0]);
1537
2027
  continue;
1538
2028
  }
1539
2029
  // A question from a job in the background: Esc refuses that one call, and stops nothing.
@@ -1625,6 +2115,12 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1625
2115
  });
1626
2116
  // A file dropped on the terminal arrives pasted as its path: an image's path becomes the image.
1627
2117
  usePaste((text) => {
2118
+ // Saying why a call is refused, a paste is part of the reason — on one line — and never lands in the box behind it.
2119
+ if (state.why && state.why.ask === state.asks[0]) {
2120
+ state.why.text += cleanPaste(text).text.replace(/\s+/g, ' ');
2121
+ redraw();
2122
+ return;
2123
+ }
1628
2124
  let images;
1629
2125
  try {
1630
2126
  images = droppedImages(text);
@@ -1656,42 +2152,73 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1656
2152
  const said = state.log.some((entry) => entry.kind === 'user');
1657
2153
  // Ink adds a line under the frame; a frame that reached the last row would be drawn as a full screen.
1658
2154
  const room = state.unmeasured.length > 0 ? 0 : Math.max(0, rows - state.used - 1);
2155
+ // Reads that wait for what comes after them, drawn as the row they will make.
2156
+ // A reply's blank line just placed is the row before what is live under it, as it is before what is placed.
2157
+ const blankBefore = state.items.at(-1)?.kind === 'text' && !String(state.items.at(-1).text ?? '').trim();
2158
+ const reads = state.reads.length > 0 ? readsDrawn(state.reads).map((item, i) => (i === 0 ? { ...item, afterBlank: blankBefore } : item)) : [];
2159
+ // What runs now, and under a delegate call the jobs it started.
2160
+ // 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.
2161
+ const steps = [...state.running.values()]
2162
+ .filter((call) => !(call.name === ASK_TOOL.name && state.asks[0]?.options))
2163
+ .map((call, i) => ({ key: call.id, columns, s, view: toolView(call, null, { cwd: state.where.cwd }), running: true, afterBlank: i === 0 && blankBefore && reads.length === 0 && !tail, 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) }));
2164
+ // A question to approve takes the rows the window has left — less the work over it and what stands under it — and never
2165
+ // more: a frame that filled the window would have Ink wipe the screen and its scrollback to draw it. Counted from the
2166
+ // same layout the rows are drawn from; a line of a reply still arriving is counted as it would fold, never fewer.
2167
+ const approving = state.asks.length > 0 && !state.asks[0].options;
2168
+ const recorded = approving && state.open !== null ? recordLines(state.open).length : 0;
2169
+ const over = approving
2170
+ ? reads.reduce((sum, item) => sum + stepRowCount({ ...item, columns, s }, s.g), 0) +
2171
+ (tail ? (state.fresh ? 1 : 0) + wrap(untab(tail), Math.max(10, columns - 2)).split('\n').length : 0) +
2172
+ steps.reduce((sum, step) => sum + stepRowCount(step, s.g), 0)
2173
+ : 0;
2174
+ 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;
2175
+ const asked = approving ? rows - 1 - over - under : null;
1659
2176
  return h(
1660
2177
  Box,
1661
2178
  { flexDirection: 'column', minHeight: room },
1662
2179
  h(Static, { key: state.epoch, items: state.items }, (item) => h(Item, { key: item.id, item, columns, s })),
2180
+ ...reads.map((item, i) => h(Item, { key: `reads-${i}`, item, columns, s })),
1663
2181
  tail ? h(Reply, { text: tail, first: state.fresh }) : null,
1664
- // What runs now, and under a delegate call the jobs it started. In one box of their own, so the lines coming and going
1665
- // never move what follows — the working line keeps its clock.
1666
- h(
1667
- Box,
1668
- { flexDirection: 'column' },
1669
- ...[...state.running.values()].map((call) => h(Tool, { key: call.id, columns, s, view: toolView(call, null, { cwd: state.where.cwd }), running: true, waiting: state.asks.some((a) => !a.options && !a.job && (!a.name || a.name === call.name)), live: state.live.get(call.id), jobs: [...state.jobs].filter(([, job]) => job.parent === call.id) })),
1670
- // A job no call here started — none should be — still shows that it works.
1671
- ),
2182
+ // In one box of their own, so the lines coming and going never move what follows — the working line keeps its clock.
2183
+ h(Box, { flexDirection: 'column' }, ...steps.map((step) => h(Tool, step))),
1672
2184
  // 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.
1673
- state.working ? h(Working, { messages, first: state.working, tokens: state.tokens, thought: state.showThinking ? state.thought : '', quietAfterMs, motion, heard: state.talking && state.running.size === 0 && state.jobs.size === 0 && state.asks.length === 0 ? state.heard : 0 }) : null,
1674
- 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), columns })) : null,
2185
+ state.working ? h(Working, { afterBlank: blankBefore && reads.length === 0 && !tail && steps.length === 0, 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,
2186
+ 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,
1675
2187
  // The record of the job that is open, under everything the turn is doing: its end, as it grows.
1676
2188
  state.open !== null ? h(JobOpen, { id: state.open, job: state.jobs.get(state.open), rows }) : null,
1677
- // The logo is the empty room's: once something has been said, the room is the conversation's.
1678
- h(Room, { logo: said ? [] : logo, rows, from: state.used }),
2189
+ // The logo and what to try are the empty room's: once something has been said, the room is the conversation's.
2190
+ h(Room, { logo: said ? [] : logo, rows, from: state.used, starter: !said }),
1679
2191
  h(
1680
2192
  Box,
1681
2193
  { flexDirection: 'column', marginTop: 1 },
1682
2194
  // A message for the model is read with its next request — which, while it waits on a delegated job, is when that job reports.
1683
2195
  ...state.queue.map(({ line, steer }, i) => h(Text, { key: i, dimColor: true, wrap: 'truncate' }, ` ${steer ? reading : 'queued'}: ${line.split('\n')[0]}${line.includes('\n') ? ' …' : ''}`)),
1684
2196
  // While a call waits on the user's word every key is the answer's: no box stands there to type into.
1685
- state.asks.length > 0 && !state.asks[0].options ? null : h(Input, { state: state.ed, width: columns, rows, placeholder: said ? '' : 'Ask anything · / commands · @ files · ? keys' }),
2197
+ state.asks.length > 0 && !state.asks[0].options ? null : h(Input, { state: state.ed, width: columns, rows, placeholder: said ? '' : 'Ask anything' }),
1686
2198
  // 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.
1687
2199
  ...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 }))),
1688
- menu.length > 0 ? h(Menu, { menu, pick: state.ed.pick }) : 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 }),
2200
+ // While a call waits on the user's word there is no box, and so nothing of the box's under it: the status row alone.
2201
+ menu.length > 0 && !approving ? h(Menu, { menu, pick: state.ed.pick, columns }) : state.ed.search && !approving ? h(Search, { search: state.ed.search }) : state.keys && !approving ? 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 }),
1689
2202
  ),
1690
2203
  );
1691
2204
  }
1692
2205
 
1693
2206
  /** Starts the session and draws it. The returned instance's `waitUntilExit()` settles when the user leaves. */
1694
- 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 }) {
2207
+ /**
2208
+ * Ink writes a changed line as: to its first column, the line, erase to the end. After a line exactly as wide as the
2209
+ * window the cursor waits on its last column, and an xterm-like terminal erases that column with it — the right edge
2210
+ * of every box, gone. The erase goes first instead: the same line drawn, nothing after it erased.
2211
+ */
2212
+ const ERASE_AFTER_LINE = /\x1b\[1G((?:(?!\x1b\[1G)[^\n])*?)\x1b\[K/g;
2213
+ export const eraseFirst = (chunk) => (typeof chunk === 'string' ? chunk.replace(ERASE_AFTER_LINE, (_whole, line) => `\x1b[1G\x1b[K${line}`) : chunk);
2214
+ /**
2215
+ * Ink steps over a line that has not changed with "next line" (`ESC[E`), which at the foot of the window goes nowhere: a
2216
+ * 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
2217
+ * it, which stays. A line feed is the same step everywhere else, and at the foot it scrolls, as a frame that grows needs.
2218
+ */
2219
+ export const nextLineScrolls = (chunk) => (typeof chunk === 'string' ? chunk.replaceAll('\x1b[E', '\r\n') : chunk);
2220
+
2221
+ 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 }) {
1695
2222
  // 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.
1696
2223
  const opening = resume === null ? null : session.resume(resume);
1697
2224
  const block = opening ? '' : session.start('startup');
@@ -1712,5 +2239,68 @@ export function runUi({ session, events, resume = null, stdin = process.stdin, s
1712
2239
  stdin.unshift = putBack;
1713
2240
  }, KITTY_WAIT_MS).unref();
1714
2241
  }
1715
- return render(h(App, { session, events, messages, cwd, block, opening, logo, clipboard, copy, notify, notifyAfterMs, quietAfterMs, run, listFiles, motion, progress }), { stdin, stdout, debug, exitOnCtrlC: false, kittyKeyboard: { mode: 'auto' } });
2242
+ // The terminal says when its window comes to the front and when it goes behind (`ESC[I`, `ESC[O`): a long turn that ends
2243
+ // behind rings. The reports are taken out of what is read here, before Ink sees it. Ink drops a whole one, but one that
2244
+ // comes in two reads — the ESC, then `[I` more than 20 ms later, as a multiplexer or a busy terminal may send it — it
2245
+ // reads as the Esc key and then `[I` typed into the box: Esc stopped the turn, and every switch of tabs typed more.
2246
+ // A terminal that speaks the kitty keyboard protocol (Ghostty, kitty, WezTerm: Ink turns it on) sends the Esc key as
2247
+ // `ESC[27u`, never a bare ESC: there a bare ESC at the end of a read is the start of something, and waits for its rest.
2248
+ // Elsewhere a bare ESC is the Esc key and goes on at once; a `[I` or `[O` just after it is still not typed.
2249
+ const front = { now: true };
2250
+ if (typeof stdin.read === 'function') {
2251
+ const read = stdin.read.bind(stdin);
2252
+ let kitty = false;
2253
+ let held = '';
2254
+ let ready = null;
2255
+ let timer = null;
2256
+ let bare = 0;
2257
+ stdin.read = (...args) => {
2258
+ if (ready !== null) {
2259
+ const out = ready;
2260
+ ready = null;
2261
+ return out;
2262
+ }
2263
+ const chunk = read(...args);
2264
+ if (chunk === null || chunk === undefined) return chunk;
2265
+ clearTimeout(timer);
2266
+ let text = held + String(chunk);
2267
+ held = '';
2268
+ // Ink asks whether the terminal speaks the protocol; the answer comes by here on its way to Ink.
2269
+ if (/\x1b\[\?\d+u/.test(text)) kitty = true;
2270
+ // The rest of a report whose ESC went on as a key: still the report's, not something typed.
2271
+ if (Date.now() - bare < FOCUS_LATE_MS && /^\[[IO]/.test(text)) {
2272
+ front.now = text[1] === 'I';
2273
+ text = text.slice(2);
2274
+ }
2275
+ bare = 0;
2276
+ text = text.replace(FOCUS_REPORT, (report) => {
2277
+ front.now = report[2] === 'I';
2278
+ return '';
2279
+ });
2280
+ const tail = /\x1b\[?$/.exec(text);
2281
+ if (tail && (kitty || tail[0] !== '\x1b')) {
2282
+ // Held for its rest; given on as it came if none comes.
2283
+ held = tail[0];
2284
+ text = text.slice(0, tail.index);
2285
+ timer = setTimeout(() => {
2286
+ ready = held;
2287
+ held = '';
2288
+ stdin.emit('readable');
2289
+ }, FOCUS_LATE_MS);
2290
+ timer.unref?.();
2291
+ } else if (tail) bare = Date.now();
2292
+ return text;
2293
+ };
2294
+ }
2295
+ // Plain (`chat.screen plain`), for a screen reader: ASCII marks, no frames, no pictures, and nothing moving.
2296
+ 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 });
2297
+ // Only the lines that changed are written again: a keystroke in the box rewrites the box's line, not the logo above it,
2298
+ // 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
2299
+ // 200 bytes; on a slow or remote terminal the whole frame drawn again on every key is what flickers. Each line is
2300
+ // erased before it is written, not after (eraseFirst), and a line stepped over steps down even at the foot (nextLineScrolls).
2301
+ const write = stdout.write.bind(stdout);
2302
+ stdout.write = (chunk, ...rest) => write(nextLineScrolls(eraseFirst(chunk)), ...rest);
2303
+ // At a terminal the screen is interactive, whatever the environment says: Ink reads a CI variable as a cue to draw only
2304
+ // the last frame, and a shell that exports one (a CI runner, some setups) would get a chat that never shows its work.
2305
+ return render(h(Marks.Provider, { value: glyphs(plain) }, app), { stdin, stdout, debug, exitOnCtrlC: false, kittyKeyboard: { mode: 'auto' }, incrementalRendering: true, interactive: Boolean(stdout.isTTY) });
1716
2306
  }