sumo-agents 0.4.0 → 0.5.0

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