sumo-agents 0.1.0 → 0.4.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.
package/src/ui.mjs CHANGED
@@ -1,19 +1,21 @@
1
1
  import { Box, render, renderToString, Static, Text, useAnimation, useApp, useBoxMetrics, useInput, usePaste, useStdout, useWindowSize } from 'ink';
2
2
  import { execFile, spawn } from 'node:child_process';
3
- import { closeSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
- import { join } from 'node:path';
3
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
4
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
5
+ import { homedir } from 'node:os';
5
6
  import { createElement as h, useEffect, useReducer, useRef } from 'react';
6
- import { compactLine, retryLine, routeLine, routeOf } from './chat.mjs';
7
+ import { compactLine, contextReport, retryLine, routeLine, routeOf } from './chat.mjs';
8
+ import { contextBand } from './sessions.mjs';
7
9
  import { liveFile } from './jobs.mjs';
8
10
  import { stopReason } from './loop.mjs';
9
- import { compactInput } from './mcp.mjs';
11
+ import { compactInput, INPUT_SHOWN } from './mcp.mjs';
10
12
  import { paths } from './paths.mjs';
11
13
  import { redact } from './redact.mjs';
12
14
  import { elapsed } from './text.mjs';
13
- import { editor, keysOf, matchFiles, menuOf, paste, press, under } from './editor.mjs';
15
+ import { cleanPaste, editor, keysOf, matchFiles, menuOf, paste, press, under } from './editor.mjs';
14
16
  import { clipboardImage, copyText, droppedImages } from './images.mjs';
15
17
  import { BASH_TOOL, DELEGATE_TOOL, EDITOR_TOOL } from './tools.mjs';
16
- import { colourEnabled, createRenderer, flow, fold, logoLines, messageAt, pathFrom, pickMessage, renderBlock, safeForTerminal, spinnerMessages, styles, sunset, tilde, toolView, transcript, untab, wrap } from './tty.mjs';
18
+ import { 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';
17
19
 
18
20
  /**
19
21
  * The chat on a real terminal. What is finished scrolls away above — what
@@ -65,6 +67,25 @@ const TITLE_BACK = '\x1b[23;0t';
65
67
  */
66
68
  const SCREEN_ASIDE = '\x1b[?1049h';
67
69
  const SCREEN_BACK = '\x1b[?1049l';
70
+ /**
71
+ * The tab's own progress mark (OSC 9;4): busy while the chat works, gone when it is done. Only where the terminal is known to
72
+ * draw it — elsewhere the same sequence is a notification, or text.
73
+ */
74
+ const PROGRESS_BUSY = '\x1b]9;4;3;0\x07';
75
+ const PROGRESS_DONE = '\x1b]9;4;0;0\x07';
76
+ export function showsProgress(env = process.env) {
77
+ if (env.TMUX || env.STY) return false;
78
+ if (env.WT_SESSION || env.ConEmuANSI === 'ON' || env.TERM_PROGRAM === 'ghostty') return true;
79
+ if (env.TERM_PROGRAM === 'iTerm.app') {
80
+ const [major, minor] = String(env.TERM_PROGRAM_VERSION ?? '').split('.').map(Number);
81
+ return major > 3 || (major === 3 && minor >= 6);
82
+ }
83
+ return false;
84
+ }
85
+
86
+ /** How long Ctrl-Z waits to be stopped before it takes it that nothing will stop it. */
87
+ const SUSPEND_CHECK_MS = 300;
88
+
68
89
  /** Longer than Ink waits for the terminal to say how its keyboard speaks (200 ms): see `runUi`. */
69
90
  const KITTY_WAIT_MS = 300;
70
91
  /** A turn at least this long ends on a bell when the window is not in front, and on its footer whatever it did. */
@@ -78,6 +99,9 @@ const LIVE_DRAW_MS = 100;
78
99
  /** The most rows of the box, and of a message once sent, that are drawn: a long paste must not push the screen past the window. */
79
100
  const INPUT_ROWS = 10;
80
101
  const ECHO_LINES = 10;
102
+ /** A paste longer than this stands in the box as a marker — `[Pasted text #1 +120 lines]` — and goes whole with the message. */
103
+ const PASTE_LINES = 12;
104
+ const PASTE_CHARS = 2000;
81
105
  /** How long the list of a project's files is good for, while a file is being named with `@`. */
82
106
  const FILES_FRESH_MS = 15_000;
83
107
  /** How many of a resumed session's turns are drawn again: enough to see where it stopped. */
@@ -148,6 +172,18 @@ export function replayOf(messages, turns = REPLAY_TURNS) {
148
172
  return [{ kind: 'note', text: `${hidden} earlier turn${hidden === 1 ? '' : 's'} not drawn again — the model has all of them` }, ...entries.slice(starts.at(-turns))];
149
173
  }
150
174
 
175
+ /**
176
+ * Where `/export` writes: the path given — from the project, or from home with `~` — and into a folder given, a file of its
177
+ * own; with none, the home's exports folder, named by the day and the session.
178
+ */
179
+ export function exportPath(given, cwd, sessionId = null) {
180
+ const named = `${new Date().toISOString().slice(0, 10)}-${String(sessionId ?? 'session').slice(0, 8)}.md`;
181
+ if (!given) return join(paths().home, 'exports', named);
182
+ const path = given.replace(/^~(?=$|\/)/, homedir());
183
+ const full = isAbsolute(path) ? path : resolve(cwd, path);
184
+ return existsSync(full) && statSync(full).isDirectory() ? join(full, named) : full;
185
+ }
186
+
151
187
  /** What Up recalls across sessions: the last lines typed, one a line, in the home. */
152
188
  const HISTORY_KEPT = 50;
153
189
  const historyFile = () => join(paths().home, 'history');
@@ -181,9 +217,15 @@ const thousands = (n) => (n >= 1000 ? `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)
181
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
182
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.
183
219
  */
184
- const linesUnder = (lines, columns) =>
220
+ const linesUnder = (lines, columns, s = styles(false)) =>
185
221
  lines
186
- .flatMap((line) => fold(untab(line.text), Math.max(20, columns - 6)).map((text) => ({ ...line, text })))
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
+ })
187
229
  .map((line, i) => h(Text, { key: i, ...TONES[line.tone], wrap: 'truncate' }, `${i === 0 ? ' ⎿ ' : ' '}${line.text}`));
188
230
 
189
231
  /**
@@ -191,25 +233,37 @@ const linesUnder = (lines, columns) =>
191
233
  * progress bar as its latest state. What was kept may begin mid-line — or mid-secret — so its first line is not shown.
192
234
  */
193
235
  function lastLines({ out, cut }) {
194
- const lines = safeForTerminal(redact(out).text).split(/\r?\n|\r/);
236
+ const lines = withoutColourCodes(safeForTerminal(redact(out).text)).split(/\r?\n|\r/);
195
237
  return (cut ? lines.slice(1) : lines).map((l) => untab(l).trimEnd()).filter(Boolean).slice(-LIVE_LINES);
196
238
  }
197
239
 
198
240
  /** A command that is running: for how long, and the last of what it has printed so far. */
199
- function Running({ live }) {
241
+ function Running({ live, label = 'Running…' }) {
200
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.
201
243
  useAnimation({ interval: 250 });
202
244
  const ran = live ? Date.now() - live.since : 0;
203
245
  return h(
204
246
  Box,
205
247
  { flexDirection: 'column' },
206
- h(Text, { dimColor: true }, ` ⎿ Running…${ran >= 1000 ? ` ${elapsed(ran)}` : ''}`),
248
+ h(Text, { dimColor: true }, ` ⎿ ${label}${ran >= 1000 ? ` ${elapsed(ran)}` : ''}`),
207
249
  ...(live ? lastLines(live) : []).map((line, i) => h(Text, { key: i, dimColor: true, wrap: 'truncate' }, ` ${line}`)),
208
250
  );
209
251
  }
210
252
 
211
253
  /** A tool call: what ran, and under it what came back — or, while it runs, the jobs it started, or what it prints. */
212
- function Tool({ view, failed = false, running = false, jobs = [], live = null, columns }) {
254
+ /**
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.
257
+ */
258
+ function titleRows(view, took, s, width) {
259
+ const stat = view.stat ? ` ${s.green(`+${view.stat.added}`)} ${s.red(`−${view.stat.removed}`)}` : '';
260
+ const time = took >= TOOK_SHOWN_MS ? s.dim(` · ${elapsed(took)}`) : '';
261
+ return untab(`${s.bold(view.title)}(${view.detail})${stat}${time}`)
262
+ .split('\n')
263
+ .flatMap((line) => wrap(line, width).split('\n'));
264
+ }
265
+
266
+ function Tool({ view, failed = false, running = false, waiting = false, jobs = [], live = null, took = 0, columns, s = styles(false) }) {
213
267
  return h(
214
268
  Box,
215
269
  { flexDirection: 'column', marginTop: 1 },
@@ -218,14 +272,24 @@ function Tool({ view, failed = false, running = false, jobs = [], live = null, c
218
272
  Box,
219
273
  null,
220
274
  h(Box, { flexShrink: 0 }, h(Text, { color: running ? undefined : failed ? 'red' : 'green', dimColor: running }, '⏺ ')),
221
- h(Box, { flexShrink: 1 }, h(Text, null, h(Text, { bold: true }, view.title), `(${untab(view.detail)})`, view.stat ? h(Text, null, ' ', h(Text, { color: 'green' }, `+${view.stat.added}`), ' ', h(Text, { color: 'red' }, `−${view.stat.removed}`)) : null)),
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))),
222
278
  ),
223
- running && jobs.length === 0 ? h(Running, { live }) : null,
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,
224
283
  ...jobs.map(([id, job]) => h(JobAtWork, { key: id, id, job })),
225
- ...linesUnder(view.lines, columns),
284
+ ...linesUnder(view.lines, columns, s),
226
285
  );
227
286
  }
228
287
 
288
+ /** A call that took at least this long says how long, beside what ran. */
289
+ const TOOK_SHOWN_MS = 1000;
290
+ /** Thought for less than this, the line that says so would say nothing. */
291
+ const THOUGHT_SHOWN_MS = 1000;
292
+
229
293
  /** The rows the screen gives to what the model is thinking. */
230
294
  const THOUGHT_ROWS = 3;
231
295
 
@@ -241,6 +305,10 @@ const thoughtRows = (text, width, rows = THOUGHT_ROWS) =>
241
305
  .flatMap((line) => wrap(line, width).split('\n'))
242
306
  .slice(-rows);
243
307
 
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
+
244
312
  /** The most of a job's title its row under the box shows. */
245
313
  const TITLE_CHARS = 32;
246
314
 
@@ -254,14 +322,16 @@ function JobAtWork({ id, job, alone = false, picked = false, open = false }) {
254
322
  useAnimation({ interval: 1000 });
255
323
  const calls = `${job.calls} tool call${job.calls === 1 ? '' : 's'}`;
256
324
  const mark = alone ? (picked ? ' ❯ ' : ' ⏺ ') : ' ⎿ ';
257
- const who = alone ? ` ${job.agent} — ${job.title.length > TITLE_CHARS ? `${job.title.slice(0, TITLE_CHARS - 1)}…` : job.title}` : '';
325
+ // 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}`;
258
327
  const lead = `j${id}${who} · ${elapsed(Date.now() - job.since)} · ${calls} · `;
259
328
  return h(
260
329
  Text,
261
330
  { wrap: 'truncate' },
262
- h(Text, picked || open ? { color: ACCENT } : { dimColor: true }, mark),
331
+ h(Text, picked || open ? { color: ACCENT } : { color: jobColour(id) }, mark),
263
332
  h(Text, { dimColor: !picked }, lead),
264
333
  h(Text, { dimColor: true }, 'working'),
334
+ !alone && job.where ? h(Text, { dimColor: true }, ` · ${job.where.replace(/^follow it: /, '')}`) : null,
265
335
  );
266
336
  }
267
337
 
@@ -297,28 +367,76 @@ function JobOpen({ id, job, rows }) {
297
367
  return h(
298
368
  Box,
299
369
  { flexDirection: 'column', marginTop: 1 },
300
- h(Text, { wrap: 'truncate' }, h(Text, { color: ACCENT }, '⏺ '), h(Text, { bold: true }, `j${id}`), ` ${job.agent} · ${job.route} — ${job.title}`),
370
+ h(Text, { wrap: 'truncate' }, h(Text, { color: jobColour(id) }, '⏺ '), h(Text, { bold: true }, `j${id}`), ` ${job.agent} · ${job.route} — ${job.title}`),
301
371
  above > 0 ? h(Text, { dimColor: true }, ` … +${above} line${above === 1 ? '' : 's'}`) : null,
302
372
  all.length === 0 ? h(Text, { dimColor: true }, ' nothing done yet') : null,
303
373
  ...seen.map((line, i) => h(Text, { key: i, dimColor: /^\s*⎿/.test(line), wrap: 'truncate' }, untab(line) || ' ')),
304
374
  );
305
375
  }
306
376
 
307
- /** A call waiting on the user's word: who asks, what would run with what, and the keys that answer. */
308
- function Ask({ ask, aside = false }) {
377
+ /** 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
+ const ASK_INPUT_MAX = 4_000;
379
+
380
+ /** 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 }) {
309
382
  const who = ask.job ? `j${ask.job}: ` : '';
383
+ // 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 ?? {});
386
+ // Short enough for a line, it is the one line; longer, it is laid out, every field whole, up to the cut.
387
+ 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');
389
+ const kept = [];
390
+ let size = 0;
391
+ for (const line of laid) {
392
+ if (size + line.length > ASK_INPUT_MAX) break;
393
+ kept.push(line);
394
+ size += line.length + 1;
395
+ }
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}?`;
310
398
  // 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.
311
- return h(Box, { marginTop: 1, flexDirection: 'column' }, h(Text, { color: 'yellow' }, `⚠ ${who}allow ${ask.server} · ${ask.tool}(${compactInput(ask.input)})?`), h(Text, { dimColor: true }, ` y once · a always · n no · esc ${aside ? 'no' : 'stop'}`));
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.
401
+ return h(
402
+ 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}`),
405
+ h(
406
+ 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,
410
+ ),
411
+ h(Text, { dimColor: true }, keys),
412
+ );
413
+ }
414
+
415
+ /** A mark, and words that go on under themselves, never under the mark: the rows of a question and its options. */
416
+ function Hung({ mark, width, color, children }) {
417
+ 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
+ }
419
+
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. */
421
+ function Question({ ask, columns }) {
422
+ return h(
423
+ Box,
424
+ { 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`)),
428
+ );
312
429
  }
313
430
 
314
431
  /** One line of a reply; the first of a block carries the mark. */
315
432
  function Reply({ text, first }) {
316
- return h(Box, { marginTop: first ? 1 : 0 }, h(Text, null, first ? '⏺ ' : ' '), h(Text, null, text || ' '));
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 || ' '));
317
435
  }
318
436
 
319
437
  /** Something finished, drawn once and left to scroll. */
320
438
  /** `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. */
321
- function Item({ item, columns }) {
439
+ function Item({ item, columns, s }) {
322
440
  if (item.kind === 'header') {
323
441
  return h(
324
442
  Box,
@@ -328,7 +446,8 @@ function Item({ item, columns }) {
328
446
  { gap: 3, marginTop: 1 },
329
447
  // The sunset runs across the name, gold at the S to crimson at the O.
330
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))))),
331
- h(Box, { flexDirection: 'column' }, h(Text, null, item.route), h(Text, { dimColor: true }, item.cwd)),
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)),
332
451
  ),
333
452
  item.block ? h(Box, { marginTop: 1 }, h(Text, null, item.block)) : null,
334
453
  );
@@ -343,21 +462,24 @@ function Item({ item, columns }) {
343
462
  );
344
463
  }
345
464
  if (item.kind === 'text') return h(Reply, item);
346
- if (item.kind === 'tool') return h(Tool, { ...item, columns });
347
- if (item.kind === 'output') return h(Box, { flexDirection: 'column' }, ...linesUnder(item.lines, columns));
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));
348
467
  if (item.kind === 'footer') return h(Box, { marginTop: 1 }, h(Text, { dimColor: true }, ` ${item.text}`));
349
468
  // The mark stands apart from the words, so a line that wraps in a narrow window goes on under them, not under it.
350
- if (item.kind === 'job') return h(Box, { marginTop: 1 }, h(Text, { color: ACCENT }, '⏺ '), h(Text, null, h(Text, { bold: true }, `j${item.id}`), ` ${item.agent} · ${item.route} — ${item.title}`, h(Text, { dimColor: true }, ` · ${item.where}`)));
351
- if (item.kind === 'error') return h(Box, { marginTop: 1 }, h(Text, { color: 'red' }, item.text));
352
- return h(Box, { flexDirection: 'column' }, ...linesUnder(item.text.split('\n').map((text) => ({ text, tone: 'dim' })), columns));
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);
471
+ // 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));
353
474
  }
354
475
 
355
476
  /**
356
477
  * The line that says it is working: your words, the next of them every few seconds, a sunset flowing through them; how
357
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.
358
479
  */
359
- function Working({ messages, first, tokens, thought = '', heard = 0, quietAfterMs = QUIET_AFTER_MS }) {
360
- const { frame, time } = useAnimation({ interval: FLOW_STEP_MS });
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 });
361
483
  const { columns } = useWindowSize();
362
484
  const words = `${messageAt(messages, first, time)}…`;
363
485
  const spent = tokens > 0 ? ` · ↓ ${thousands(tokens)} tokens` : '';
@@ -368,7 +490,13 @@ function Working({ messages, first, tokens, thought = '', heard = 0, quietAfterM
368
490
  return h(
369
491
  Box,
370
492
  { marginTop: 1, flexDirection: 'column' },
371
- h(Box, null, h(Text, null, ...[...words].map((ch, i) => h(Text, { key: i, color: flow(i, frame) }, ch)), ' '), h(Text, { dimColor: true }, `(${Math.floor(time / 1000)}s${spent}${quiet} · esc to interrupt)`)),
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.
494
+ 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)`)),
499
+ ),
372
500
  ...thinking.map((row, i) => h(Text, { key: i, dimColor: true, wrap: 'truncate' }, `${i === 0 ? ' ⎿ ' : ' '}${row}`)),
373
501
  );
374
502
  }
@@ -393,7 +521,7 @@ export function inView({ text, cursor }, width, max) {
393
521
  }
394
522
 
395
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. */
396
- function Input({ state, width, rows }) {
524
+ function Input({ state, width, rows, placeholder = '' }) {
397
525
  const seen = inView(state, Math.max(10, width - 6), Math.max(3, Math.min(INPUT_ROWS, rows - 12)));
398
526
  const { text, cursor } = seen;
399
527
  const on = under(seen);
@@ -404,51 +532,122 @@ function Input({ state, width, rows }) {
404
532
  return h(
405
533
  Box,
406
534
  { borderStyle: 'round', borderColor: 'gray', paddingX: 1, width },
407
- h(Text, null, '> '),
408
- h(Box, { flexGrow: 1, flexShrink: 1, flexDirection: 'column' }, hidden(seen.above), h(Text, null, untab(text.slice(0, cursor)), h(Text, { inverse: true }, untab(shown)), untab(after)), hidden(seen.below)),
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)),
409
538
  );
410
539
  }
411
540
 
541
+ /** The most rows of a menu drawn at once: a long one scrolls with the pick, so opening it never pushes the conversation far up. */
542
+ const MENU_ROWS = 8;
543
+
544
+ /** 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. */
412
545
  function Menu({ menu, pick }) {
413
546
  const wide = Math.max(...menu.map((c) => c.label.length)) + 2;
547
+ const first = Math.min(Math.max(0, pick - MENU_ROWS + 1), Math.max(0, menu.length - MENU_ROWS));
548
+ const shown = menu.slice(first, first + MENU_ROWS);
549
+ const below = menu.length - first - shown.length;
414
550
  return h(
415
551
  Box,
416
552
  { flexDirection: 'column', paddingX: 2 },
417
- ...menu.map((c, i) => h(Text, { key: c.name, color: i === pick ? ACCENT : undefined, dimColor: i !== pick }, c.label.padEnd(wide), c.hint)),
553
+ first > 0 ? h(Text, { dimColor: true }, ` ↑ ${first} more`) : null,
554
+ // 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)),
556
+ below > 0 ? h(Text, { dimColor: true }, ` ↓ ${below} more`) : null,
418
557
  );
419
558
  }
420
559
 
421
560
  /** A sum of money for a margin: nothing until it is a cent. */
422
561
  const dollars = (cost) => (cost >= 0.005 ? `$${cost.toFixed(2)}` : '');
423
562
 
424
- function Status({ session, leaving, notice, jobs, aside = [], pick = null, open = null, where, spent, waiting, columns }) {
425
- const size = session.contextTokens >= 1000 ? ` · ${Math.round(session.contextTokens / 1000)}k context` : '';
563
+ /** The keys most reached for, as `?` shows them: the key, then what it does. /help has all of them. */
564
+ const KEYS = [
565
+ ['enter', 'send'],
566
+ ['\\ enter', 'a new line'],
567
+ ['esc', 'stop the turn'],
568
+ ['↑ ↓', 'what you sent before'],
569
+ ['ctrl-r', 'search what you sent'],
570
+ ['ctrl-c', 'clear · twice to leave'],
571
+ ['ctrl-o', 'the whole transcript'],
572
+ ['ctrl-g', 'write in your editor'],
573
+ ['ctrl-v', 'paste an image'],
574
+ ['ctrl-y', 'put back what was cut'],
575
+ ['ctrl-_', 'undo in the box'],
576
+ ['ctrl-l', 'draw the screen again'],
577
+ ['/', 'commands'],
578
+ ['@', 'name a file'],
579
+ ['!', 'run a command yourself'],
580
+ ];
581
+
582
+ const KEY_WIDTH = Math.max(...KEYS.map(([key]) => key.length)) + 2;
583
+
584
+ /** `?` on an empty box: the keys, in as many columns as the window holds, until the next key. */
585
+ function Keys({ columns }) {
586
+ const per = columns >= 96 ? 3 : columns >= 64 ? 2 : 1;
587
+ const width = Math.floor((columns - 4) / per);
588
+ const rows = [];
589
+ for (let i = 0; i < KEYS.length; i += per) rows.push(KEYS.slice(i, i + per));
590
+ return h(
591
+ Box,
592
+ { flexDirection: 'column', paddingX: 2 },
593
+ ...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'),
595
+ );
596
+ }
597
+
598
+ /** Ctrl-R at work: what has been typed to find, and how to go on; the box shows what it found. */
599
+ function Search({ search }) {
600
+ return h(
601
+ Box,
602
+ { paddingX: 2 },
603
+ h(
604
+ Text,
605
+ { wrap: 'truncate-end' },
606
+ h(Text, { color: search.failed ? 'red' : ACCENT }, `search: ${search.query}`),
607
+ h(Text, { dimColor: true }, search.failed ? ' — nothing you sent holds that' : !search.query ? 'type what to find in what you sent · esc puts your draft back' : `${search.end ? ' — nothing further back' : ' · ctrl-r further back'} · enter keeps it · esc puts your draft back`),
608
+ ),
609
+ );
610
+ }
611
+
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. */
613
+ export function contextTone(tokens) {
614
+ const band = contextBand(tokens);
615
+ return band === 'act' ? { color: 'red' } : band === 'watch' ? { color: 'yellow' } : { dimColor: true };
616
+ }
617
+
618
+ function Status({ session, leaving, notice, jobs, aside = [], pick = null, open = null, where, spent, overBudget = false, waiting, columns }) {
619
+ const tokens = session.contextTokens;
620
+ const size = tokens >= 1000 ? ` · ${Math.round(tokens / 1000)}k context${contextBand(tokens) === 'act' ? ' · /new' : ''}` : '';
426
621
  const cost = dollars(spent) && ` · ${dollars(spent)}`;
427
622
  // Where the tools run: the project and the branch it is on. The header that says it scrolls away; this does not.
428
623
  const place = where ? `${where.name}${where.branch ? ` (${where.branch})` : ''}` : '';
429
- const hint = leaving ? `Ctrl-C again to leave${aside.length > 0 ? ` — it stops ${aside.map((id) => `j${id}`).join(', ')}, to be picked up again later` : ''}` : notice ? notice : pick === MAIN ? 'enter shows main · ↑ back to the box' : pick !== null ? `enter opens j${pick} · ↑ back to the box` : open !== null ? `esc closes j${open} · ctrl-o all of its record · @ message talks to it` : jobs.length > 0 ? `${jobs.length === 1 ? `@ message talks to j${jobs[0]}` : '@j<id> message talks to that job'} · ${aside.length > 0 ? `↓ enter opens ${aside.length === 1 ? 'it' : 'one'} · /stop stops it` : 'ctrl-o full output'}` : waiting ? '↑ takes back what is waiting' : '/ commands · /help · ctrl-o full output';
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';
430
625
  // In a narrow window the hints give way, then the place — unless the line has something to say just now, which the place
431
626
  // gives way to; the model, the size of the context and the cost never fold.
432
627
  const route = `${routeLine(session)}${size}${cost}`;
628
+ // 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
+ 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);
433
630
  const room = columns - 4 - route.length - 2;
434
631
  const said = leaving || notice;
435
- const placed = place && place.length <= room - (said ? hint.length + 2 : 0) ? place : '';
436
- const hinted = room - (placed ? placed.length + 2 : 0) >= 12 ? hint : '';
437
- // With jobs at work the keys are what is needed, and they are long: the route keeps its line, from the left, and they take the line under it.
632
+ const placed = place && place.length + 3 <= room - (said ? hint.length + 2 : 0) ? place : '';
633
+ const hinted = room - (placed ? placed.length + 3 : 0) >= 12 ? hint : '';
634
+ // 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
+ // narrow window; the route stands at the right with the place beside it, while the keys keep room for their first words.
438
636
  if (jobs.length > 0) {
439
- const beside = place && place.length <= room ? place : '';
637
+ // 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;
440
639
  return h(
441
640
  Box,
442
- { paddingX: 2, flexDirection: 'column' },
443
- h(Box, { justifyContent: 'space-between', gap: 2 }, h(Box, { flexShrink: 0 }, h(Text, { dimColor: true }, route)), beside ? h(Box, { flexShrink: 0 }, h(Text, { dimColor: true }, beside)) : null),
444
- h(Text, { dimColor: true, wrap: 'truncate' }, hint),
641
+ { paddingX: 2, justifyContent: 'space-between', gap: 2 },
642
+ h(Box, { flexShrink: 1 }, h(Text, { dimColor: true, wrap: 'truncate' }, hint)),
643
+ h(Box, { flexShrink: 0, gap: 3 }, routed, beside ? h(Text, { dimColor: true }, place) : null),
445
644
  );
446
645
  }
646
+ // The place stands with the route it belongs to, on the left; the keys at the right.
447
647
  return h(
448
648
  Box,
449
649
  { paddingX: 2, justifyContent: 'space-between', gap: 2 },
450
- h(Box, { flexShrink: 0 }, h(Text, { dimColor: true }, route)),
451
- placed ? h(Box, { flexShrink: 0 }, h(Text, { dimColor: true }, placed)) : null,
650
+ h(Box, { flexShrink: 0, gap: 3 }, routed, placed ? h(Text, { dimColor: true }, placed) : null),
452
651
  hinted ? h(Box, { flexShrink: 1 }, h(Text, { dimColor: true, wrap: 'truncate' }, hinted)) : null,
453
652
  );
454
653
  }
@@ -465,10 +664,18 @@ function helpText(commands) {
465
664
  ['Ctrl-G', 'write the message in your editor ($VISUAL or $EDITOR); what you save comes back to the box'],
466
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'],
467
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'],
468
669
  ['Ctrl-A · Ctrl-E', 'the start and the end of the line'],
670
+ ['Ctrl-B · Ctrl-F', 'a character back, or on'],
469
671
  ['Ctrl-U · Ctrl-K', 'cut to the start, or to the end, of the line'],
470
- ['Ctrl-W · Option-Backspace', 'cut the word before the cursor'],
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'],
471
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'],
472
679
  ['! command', 'run a command yourself, where the agent would be refused; the model sees what it printed'],
473
680
  ['@ message · @j<id> message', 'say it to the job that is running — the one open, when one is — or to a named one'],
474
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'],
@@ -506,12 +713,14 @@ function Room({ logo, rows, from }) {
506
713
  );
507
714
  }
508
715
 
509
- function App({ session, events, messages, cwd, block, opening, logo, clipboard, copy, notify: alerts, notifyAfterMs, quietAfterMs, run, listFiles }) {
510
- const { exit, suspendTerminal } = useApp();
716
+ function App({ session, events, messages, cwd, block, opening, logo, clipboard, copy, notify: alerts, notifyAfterMs, quietAfterMs, run, listFiles, motion, progress }) {
717
+ const { exit, suspendTerminal, waitUntilRenderFlush } = useApp();
511
718
  const { stdout, write } = useStdout();
512
719
  const { columns, rows } = useWindowSize();
513
720
  const [, redraw] = useReducer((n) => n + 1, 0);
514
- const s = styles(colourEnabled(stdout));
721
+ // 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));
515
724
  const header = (text) => ({ kind: 'header', route: routeLine(session), cwd: tilde(cwd), block: text });
516
725
  // 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.
517
726
  // `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.
@@ -519,7 +728,7 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
519
728
  // `live` is what each running command has printed so far and since when; `heard`, when the model last said or did anything;
520
729
  // `turn`, what the turn in hand has done; `talking`, that the model — not a `!` command — is what the screen is working on;
521
730
  // `pick`, the job under the box that Down has stepped onto; `open`, the one whose record is shown.
522
- st.current ??= { log: [], items: [], unmeasured: [], used: 0, next: 0, epoch: 0, raw: '', ed: editor(readHistory()), images: [], notice: null, queue: [], working: null, talking: false, tokens: 0, thought: '', heard: 0, running: new Map(), live: new Map(), drawSoon: null, jobs: new Map(), pick: null, open: null, asks: [], reply: null, fresh: true, leaving: null, gone: false, focused: true, title: null, turn: null, where: session.where(), spent: session.spent(), files: { cwd: null, at: 0, list: [] }, away: false };
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 };
523
732
  const state = st.current;
524
733
  state.columns = columns;
525
734
  state.rows = rows;
@@ -535,7 +744,7 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
535
744
  */
536
745
  const measure = () => {
537
746
  for (const item of state.unmeasured.splice(0)) {
538
- if (state.used < state.rows) state.used += renderToString(h(Item, { item, columns: state.columns }), { columns: state.columns }).split('\n').length;
747
+ if (state.used < state.rows) state.used += renderToString(h(Item, { item, columns: state.columns, s }), { columns: state.columns }).split('\n').length;
539
748
  }
540
749
  };
541
750
  const show = (items) => {
@@ -561,7 +770,23 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
561
770
  return [{ ...entry, block: warnings && renderBlock(warnings, s, { width: state.columns - 1 }) }];
562
771
  }
563
772
  if (entry.kind === 'tool') {
564
- return [{ kind: 'tool', view: toolView(entry.call, entry.result, { cwd: state.where.cwd }), failed: entry.result.isError }];
773
+ const view = toolView(entry.call, entry.result, { cwd: state.where.cwd });
774
+ // A job the call started in the background is told under it: who, on what, and where to follow it — not on a line of its own above the call.
775
+ const started = entry.started ?? [];
776
+ if (started.length === 1 && /^j\d+ is running in the background/.test(entry.result.content)) {
777
+ const [job] = started;
778
+ view.lines = [
779
+ { text: `j${job.id} ${job.agent} · ${job.route} — running in the background`, tone: 'plain' },
780
+ { text: `its report comes here when it is done · ${job.where}`, tone: 'dim' },
781
+ ];
782
+ } else if (started.length > 1 && /^j\d+ is running in the background/.test(entry.result.content)) {
783
+ // Attempts side by side: a line each, and one for the report they make together.
784
+ view.lines = [
785
+ ...started.map((job) => ({ text: `j${job.id} ${job.agent} · ${job.route} — running in the background · ${job.where.replace(/^follow it: /, '')}`, tone: 'plain' })),
786
+ { text: `their report comes here when all ${started.length} are done`, tone: 'dim' },
787
+ ];
788
+ }
789
+ return [{ kind: 'tool', view, failed: entry.result.isError, took: entry.took ?? 0 }];
565
790
  }
566
791
  // What the user's own command printed: drawn as a tool's output is, under the line they typed.
567
792
  if (entry.kind === 'shell') return [{ kind: 'output', lines: toolView({ name: BASH_TOOL.name }, entry.result).lines }];
@@ -602,6 +827,14 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
602
827
  if (!state.jobs.has(state.open)) state.open = null;
603
828
  };
604
829
 
830
+ /** The model has stopped thinking and acts: how long it thought stays on the screen, and what it thought goes in the log for the pager. */
831
+ const thoughtDone = () => {
832
+ if (state.thinking === null) return;
833
+ const ms = Date.now() - state.thinking;
834
+ state.thinking = null;
835
+ if (ms >= THOUGHT_SHOWN_MS) record({ kind: 'thought', ms, text: state.thought });
836
+ };
837
+
605
838
  /** The reply so far is whole: its last line is drawn, it joins the log, and the next text starts a new block. */
606
839
  const closeReply = () => {
607
840
  state.reply?.flush();
@@ -648,7 +881,7 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
648
881
  state.where = session.where();
649
882
  const { calls, edited } = state.turn;
650
883
  const files = [...edited];
651
- const parts = [elapsed(took), calls > 0 ? `${calls} call${calls === 1 ? '' : 's'}` : '', files.length > 0 ? `edited ${files.slice(0, 3).join(', ')}${files.length > 3 ? ` +${files.length - 3} more` : ''}` : '', dollars(state.spent - before)];
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)];
652
885
  if (calls > 0 || took >= notifyAfterMs) record({ kind: 'footer', text: parts.filter(Boolean).join(' · ') });
653
886
  if (took >= notifyAfterMs) alert(`${state.where.name}: ${ended}`);
654
887
  };
@@ -658,7 +891,15 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
658
891
  state.gone = true;
659
892
  state.queue = [];
660
893
  if (state.working) session.interrupt();
661
- else exit();
894
+ else close();
895
+ };
896
+
897
+ /** The screen let go: the box and the margin under it are cleared first, so what stays in the terminal is the conversation. */
898
+ const close = () => {
899
+ state.closed = true;
900
+ redraw();
901
+ // The cleared frame is drawn before the screen lets go, however slow the machine: exit waits for it.
902
+ waitUntilRenderFlush().then(() => exit(), () => exit());
662
903
  };
663
904
 
664
905
  /** The user's answer to a call waiting on it; one answered already — by Esc, say — is left alone. */
@@ -717,6 +958,8 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
717
958
  state.log = [];
718
959
  // The old session's pictures go with it; their numbers stay taken, so a marker recalled from before names nothing.
719
960
  state.images = state.images.map(() => null);
961
+ state.pastes = state.pastes.map(() => null);
962
+ state.overBudget = false;
720
963
  const block = session.start('new');
721
964
  state.where = session.where();
722
965
  state.spent = session.spent();
@@ -733,6 +976,8 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
733
976
  const said = session.resume(args);
734
977
  state.log = [];
735
978
  state.images = state.images.map(() => null);
979
+ state.pastes = state.pastes.map(() => null);
980
+ state.overBudget = false;
736
981
  state.where = session.where();
737
982
  state.spent = session.spent();
738
983
  refresh(scrolledClear(state.rows));
@@ -743,32 +988,56 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
743
988
  }
744
989
  if (control === 'copy') {
745
990
  record({ kind: 'user', text: line });
746
- if (args && args !== 'code') return record({ kind: 'error', text: `/copy takes nothing, or "code" — not "${args}"` });
991
+ // A number goes further back: /copy 2 is the reply before the last, /copy code 2 the code block before the last.
992
+ 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}"` });
994
+ const [, code, n] = asked;
995
+ const back = Number(n ?? 1);
747
996
  // The reply as the model wrote it, not as the screen drew it: no indent, no line broken to fit the window.
748
997
  const replies = state.log.filter((entry) => entry.kind === 'reply' && !entry.own);
749
998
  const blocks = replies.flatMap((entry) => [...entry.raw.matchAll(/^[ \t]*```[^\n]*\n([\s\S]*?)^[ \t]*```[ \t]*$/gm)].map((m) => m[1]));
750
- const text = (args === 'code' ? blocks.at(-1) : replies.at(-1)?.raw)?.replace(/\n+$/, '');
751
- if (!text) return record({ kind: 'error', text: args === 'code' ? 'no code block in the conversation yet' : 'no reply to copy yet' });
999
+ const text = (code ? blocks.at(-back) : replies.at(-back)?.raw)?.replace(/\n+$/, '');
1000
+ 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' });
752
1002
  // Where no clipboard command takes it, the terminal is asked to (OSC 52).
753
1003
  const taken = await copy(text);
754
1004
  if (!taken) tell(`\x1b]52;c;${Buffer.from(text).toString('base64')}\x07`);
755
1005
  const lines = text.split('\n').length;
756
- return record({ kind: 'note', text: `copied ${args === 'code' ? 'the last code block' : 'the last reply'} — ${lines} line${lines === 1 ? '' : 's'}${taken ? '' : ", through the terminal's clipboard"}` });
1006
+ return record({ kind: 'note', text: `copied ${which} — ${lines} line${lines === 1 ? '' : 's'}${taken ? '' : ", through the terminal's clipboard"}` });
1007
+ }
1008
+ if (control === 'context') {
1009
+ record({ kind: 'user', text: line });
1010
+ const turns = state.log.filter((entry) => entry.kind === 'user' && !/^[/!]/.test(entry.text)).length;
1011
+ const calls = state.log.filter((entry) => entry.kind === 'tool').length;
1012
+ return record({ kind: 'reply', raw: contextReport({ contextTokens: session.contextTokens, rows: session.usage(), turns, calls }), own: true });
1013
+ }
1014
+ if (control === 'thinking') {
1015
+ record({ kind: 'user', text: line });
1016
+ if (args !== 'on' && args !== 'off') return record({ kind: 'note', text: `thinking is ${state.showThinking ? 'shown' : 'hidden'} under the working line — /thinking on or /thinking off` });
1017
+ state.showThinking = args === 'on';
1018
+ return record({ kind: 'note', text: state.showThinking ? 'the model\'s thinking is shown under the working line' : 'the model\'s thinking is hidden — the pager (ctrl-o) still has it' });
1019
+ }
1020
+ if (control === 'export') {
1021
+ record({ kind: 'user', text: line });
1022
+ const file = exportPath(args, state.where.cwd, session.sessionId);
1023
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
1024
+ 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)}` });
757
1026
  }
758
1027
  if (control === 'help') {
759
1028
  record({ kind: 'user', text: line });
760
1029
  return record({ kind: 'reply', raw: helpText(session.commands), own: true });
761
1030
  }
762
- if (control === 'model' || control === 'memory' || control === 'mcp') {
1031
+ if (control === 'model' || control === 'memory' || control === 'mcp' || control === 'undo') {
763
1032
  record({ kind: 'user', text: line });
764
- const text = control === 'model' ? session.route(args) : control === 'mcp' ? (await session.mcp()).join('\n') : await session.memoryPage();
1033
+ const text = control === 'model' ? session.route(args) : control === 'undo' ? session.undo() : control === 'mcp' ? (await session.mcp()).join('\n') : await session.memoryPage();
765
1034
  return record({ kind: 'note', text });
766
1035
  }
767
1036
  record({ kind: 'user', text: line });
768
1037
  await modelTurn(() => session.say(text, said, images, { guide }));
769
1038
  } catch (cause) {
770
1039
  closeReply();
771
- record({ kind: 'error', text: `error: ${cause.message}` });
1040
+ record({ kind: 'error', ...explained(cause.message) });
772
1041
  } finally {
773
1042
  endTurn();
774
1043
  }
@@ -791,14 +1060,14 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
791
1060
  outcome = await run();
792
1061
  } catch (cause) {
793
1062
  closeReply();
794
- record({ kind: 'error', text: `error: ${cause.message}` });
1063
+ record({ kind: 'error', ...explained(cause.message) });
795
1064
  return closeTurn(began, before, 'stopped on an error');
796
1065
  }
797
1066
  closeReply();
798
1067
  // Nothing was waiting after all: no turn was run.
799
1068
  if (!outcome) return undefined;
800
- if (outcome.stop === 'interrupted') record({ kind: 'note', text: 'Interrupted' });
801
- if (outcome.stop === 'error') record({ kind: 'error', text: `error: ${outcome.error}` });
1069
+ if (outcome.stop === 'interrupted') record({ kind: 'note', text: 'Interrupted · say what it should do instead' });
1070
+ if (outcome.stop === 'error') record({ kind: 'error', ...explained(outcome.error) });
802
1071
  if (stopReason(outcome.stop)) record({ kind: 'note', text: stopReason(outcome.stop) });
803
1072
  return closeTurn(began, before, outcome.stop === 'error' ? 'stopped on an error' : outcome.stop === 'interrupted' ? 'interrupted' : 'done');
804
1073
  }
@@ -812,11 +1081,12 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
812
1081
  state.live.clear();
813
1082
  for (const id of [...state.jobs.keys()]) if (!aside.includes(id)) state.jobs.delete(id);
814
1083
  dropEnded();
1084
+ thoughtDone();
815
1085
  state.working = null;
816
1086
  state.talking = false;
817
1087
  state.thought = '';
818
1088
  redraw();
819
- if (state.gone) exit();
1089
+ if (state.gone) close();
820
1090
  }
821
1091
 
822
1092
  /** A turn nobody typed: what the background jobs reported, read by the model as soon as it is free to. */
@@ -825,7 +1095,7 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
825
1095
  await modelTurn(() => session.wake());
826
1096
  } catch (cause) {
827
1097
  closeReply();
828
- record({ kind: 'error', text: `error: ${cause.message}` });
1098
+ record({ kind: 'error', ...explained(cause.message) });
829
1099
  } finally {
830
1100
  endTurn();
831
1101
  }
@@ -855,7 +1125,9 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
855
1125
  }
856
1126
 
857
1127
  /** What was typed: now if nothing is running, after the turn in hand if something is. */
858
- async function submit(line) {
1128
+ async function submit(typed) {
1129
+ // A long paste stood in the box as a marker; what is sent is the paste itself.
1130
+ const line = typed.replace(/\[Pasted text #(\d+)[^\]\n]*\]/g, (marker, n) => state.pastes[n - 1] ?? marker);
859
1131
  keepHistory(line);
860
1132
  const asked = line.startsWith('/') ? session.expand(line) : {};
861
1133
  if (asked.control === 'stop') return stopJob(line, asked.args);
@@ -943,7 +1215,7 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
943
1215
  writeFileSync(file, state.ed.text, { mode: 0o600 });
944
1216
  if (!(await handOver(process.env.VISUAL || process.env.EDITOR || 'vi', file, 'the editor'))) return;
945
1217
  const text = readFileSync(file, 'utf8').replace(/\r\n?/g, '\n').replace(/\n+$/, '');
946
- state.ed = { ...editor(state.ed.history), text, cursor: text.length };
1218
+ state.ed = { ...editor(state.ed.history, state.ed.kill), text, cursor: text.length };
947
1219
  } catch (cause) {
948
1220
  notify(cause.message);
949
1221
  } finally {
@@ -963,7 +1235,7 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
963
1235
  mkdirSync(paths().logs, { recursive: true, mode: 0o700 });
964
1236
  const live = state.raw ? [{ kind: 'reply', raw: state.raw }] : [];
965
1237
  // What a job wrote is shown, never obeyed: its record goes to the pager as it goes to the screen.
966
- const text = state.open === null ? transcript([...state.log, ...live], s, { width: state.columns, cwd: state.where.cwd }) : safeForTerminal(readFileSync(liveFile(state.open), 'utf8'));
1238
+ const text = state.open === null ? transcript([...state.log, ...live], paged, { width: state.columns, cwd: state.where.cwd }) : safeForTerminal(readFileSync(liveFile(state.open), 'utf8'));
967
1239
  writeFileSync(file, text, { mode: 0o600 });
968
1240
  // Opened at its end: what was asked about is nearly always the last thing that happened.
969
1241
  await handOver(process.env.PAGER || 'less -R +G', file, 'the pager');
@@ -974,16 +1246,59 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
974
1246
  }
975
1247
  };
976
1248
 
1249
+ /**
1250
+ * Ctrl-Z: the chat stopped and the shell given back, as any program in a terminal is; `fg` brings it back drawn. Not while
1251
+ * anything is at work: a turn or a job stopped with the process would hold its command, or its API request, half done.
1252
+ */
1253
+ const suspend = async () => {
1254
+ 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');
1257
+ state.away = true;
1258
+ let stopped = true;
1259
+ try {
1260
+ tell(FOCUS_OFF);
1261
+ await suspendTerminal(
1262
+ () =>
1263
+ new Promise((resolve) => {
1264
+ // The timer keeps the process alive while it waits — the screen has let go of the keyboard, the one thing that did —
1265
+ // and tells a stop that never came, as under a parent with no job control, from one that did.
1266
+ const began = Date.now();
1267
+ let continued = false;
1268
+ const done = () => {
1269
+ clearTimeout(check);
1270
+ process.off('SIGCONT', woke);
1271
+ stopped = continued || Date.now() - began >= SUSPEND_CHECK_MS * 3;
1272
+ resolve();
1273
+ };
1274
+ const woke = () => {
1275
+ continued = true;
1276
+ done();
1277
+ };
1278
+ const check = setTimeout(done, SUSPEND_CHECK_MS);
1279
+ process.once('SIGCONT', woke);
1280
+ process.kill(process.pid, 'SIGTSTP');
1281
+ }),
1282
+ );
1283
+ } finally {
1284
+ tell(FOCUS_ON);
1285
+ state.away = false;
1286
+ refresh();
1287
+ }
1288
+ if (!stopped) notify('Ctrl-Z: there is no shell here to suspend the chat into');
1289
+ };
1290
+
977
1291
  /** 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. */
978
1292
  const takeBack = (entries) => {
979
1293
  for (const entry of entries) if (entry.steer) session.unsteer(entry.line);
980
1294
  state.queue = state.queue.filter((entry) => !entries.includes(entry));
981
1295
  const text = [...entries.map((entry) => entry.line), state.ed.text].filter(Boolean).join('\n');
982
- state.ed = { ...editor(state.ed.history), text, cursor: text.length };
1296
+ state.ed = { ...editor(state.ed.history, state.ed.kill), text, cursor: text.length };
983
1297
  };
984
1298
 
985
1299
  useEffect(() => {
986
1300
  const onText = (chunk) => {
1301
+ thoughtDone();
987
1302
  state.heard = Date.now();
988
1303
  // The reply has begun: what was thought before it is no longer the news.
989
1304
  state.thought = '';
@@ -994,6 +1309,7 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
994
1309
  // 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.
995
1310
  const onThinking = ({ text, job }) => {
996
1311
  if (job) return;
1312
+ state.thinking ??= Date.now();
997
1313
  state.thought = text;
998
1314
  state.heard = Date.now();
999
1315
  redraw();
@@ -1001,10 +1317,16 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1001
1317
  // A request being sent again, or a job's conversation summarized to make room: said where the work shows, with the job's id.
1002
1318
  const onRetry = (r) => record({ kind: 'note', text: `${r.job ? `j${r.job}: ` : ''}${retryLine(r)}` });
1003
1319
  const onCompact = (c) => record({ kind: 'note', text: `${c.job ? `j${c.job}: ` : ''}${compactLine(c)}` });
1320
+ // The session has passed what it may cost before it is said: said once, where the retries are.
1321
+ const onBudget = ({ text }) => {
1322
+ state.overBudget = true;
1323
+ record({ kind: 'note', text });
1324
+ };
1004
1325
  const onTool = ({ call, job }) => {
1005
1326
  const at = state.jobs.get(job);
1006
1327
  if (at) at.calls++;
1007
1328
  else if (!job) {
1329
+ thoughtDone();
1008
1330
  state.thought = '';
1009
1331
  closeReply();
1010
1332
  state.running.set(call.id, call);
@@ -1054,21 +1376,33 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1054
1376
  const onResult = ({ call, result, job }) => {
1055
1377
  if (job) return;
1056
1378
  // Delegated jobs run side by side: one ending leaves the others' calls on the screen.
1379
+ const took = state.live.has(call.id) ? Date.now() - state.live.get(call.id).since : 0;
1057
1380
  state.running.delete(call.id);
1058
1381
  state.live.delete(call.id);
1059
1382
  state.heard = Date.now();
1060
1383
  if (state.turn && call.name === EDITOR_TOOL.name && call.input?.command !== 'view' && !result.isError) state.turn.edited.add(pathFrom(call.input?.path ?? '', state.where.cwd));
1061
- record({ kind: 'tool', call, result });
1384
+ const started = state.started.get(call.id) ?? [];
1385
+ state.started.delete(call.id);
1386
+ record({ kind: 'tool', call, result, took, started });
1062
1387
  };
1063
1388
  const onJob = ({ job, call = null, tab = null }) => {
1064
- state.jobs.set(job.id, { parent: call, calls: 0, since: Date.now(), agent: job.agent, title: job.title, route: routeOf(job) });
1065
1389
  const where = tab?.pane ? 'working in its Herdr tab' : tab?.error ? `no Herdr tab (${tab.error}) — sumo job watch ${job.id}` : `follow it: sumo job watch ${job.id}`;
1066
- record({ kind: 'job', id: job.id, agent: job.agent, title: job.title, route: routeOf(job), where });
1390
+ const info = { id: job.id, agent: job.agent, title: job.title, route: routeOf(job), where };
1391
+ state.jobs.set(job.id, { parent: call, calls: 0, since: Date.now(), agent: job.agent, title: job.title, route: info.route, where });
1392
+ state.known.set(job.id, info);
1393
+ // Started by a call still on the screen: it is told under that call, at work and once the call is answered.
1394
+ if (call && state.running.has(call)) {
1395
+ state.started.set(call, [...(state.started.get(call) ?? []), info]);
1396
+ return redraw();
1397
+ }
1398
+ record({ kind: 'job', ...info });
1067
1399
  };
1068
1400
  // A job in the background has reported: how it went is drawn where the conversation has got to, and the model reads the
1069
1401
  // report with its next request — or, when nothing is at work, in a turn started here for it. One the user stopped starts none.
1070
- const onJobReport = ({ job, result }) => {
1071
- record({ kind: 'tool', call: { id: `report-${job}`, name: DELEGATE_TOOL.name, input: { job } }, result });
1402
+ const onJobReport = ({ job, result, quiet = false }) => {
1403
+ const known = state.known.get(job);
1404
+ // A job the user stopped is said to be stopped, not left open.
1405
+ record({ kind: 'tool', call: { id: `report-${job}`, name: DELEGATE_TOOL.name, input: { job, report: true, agent: known?.agent, title: known?.title, stopped: Boolean(quiet) } }, result });
1072
1406
  alert(`${state.where.name}: j${job} has reported`);
1073
1407
  if (!state.working) drain();
1074
1408
  };
@@ -1089,7 +1423,15 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1089
1423
  const onApprove = (ask) => {
1090
1424
  state.asks.push(ask);
1091
1425
  ask.signal?.addEventListener('abort', () => settle(ask, 'no'), { once: true });
1092
- alert(`${state.where.name}: ${ask.server} · ${ask.tool} waits for your answer`);
1426
+ alert(`${state.where.name}: ${ask.unsandboxed ? 'a command waits to run outside the sandbox' : `${ask.server} · ${ask.tool} waits for your answer`}`);
1427
+ redraw();
1428
+ };
1429
+ // A question of the model's: shown with its options, the first one picked, until a pick or a typed answer settles it.
1430
+ const onAsk = (ask) => {
1431
+ const standing = { ...ask, at: 0 };
1432
+ state.asks.push(standing);
1433
+ ask.signal?.addEventListener('abort', () => settle(standing, 'no'), { once: true });
1434
+ alert(`${state.where.name}: a question waits for your answer`);
1093
1435
  redraw();
1094
1436
  };
1095
1437
  // An MCP server that is not there is the user's to see; the model is simply not offered its tools.
@@ -1097,9 +1439,9 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1097
1439
  if (error) record({ kind: 'error', text: `mcp: ${error}` });
1098
1440
  for (const server of servers.filter((s) => !s.ok)) record({ kind: 'error', text: `mcp ${server.name}: ${server.error} — sumo mcp shows every server` });
1099
1441
  };
1100
- events.on('text', onText).on('thinking', onThinking).on('retry', onRetry).on('compact', onCompact).on('tool', onTool).on('output', onOutput).on('heard', onHeard).on('guide', onGuide).on('sources', onSources).on('check', onCheck).on('result', onResult).on('usage', onUsage).on('job', onJob).on('tab-failed', onTabFailed).on('job-end', onJobEnd).on('job-report', onJobReport).on('approve', onApprove).on('mcp', onMcp);
1442
+ events.on('text', onText).on('thinking', onThinking).on('retry', onRetry).on('compact', onCompact).on('budget', onBudget).on('tool', onTool).on('output', onOutput).on('heard', onHeard).on('guide', onGuide).on('sources', onSources).on('check', onCheck).on('result', onResult).on('usage', onUsage).on('job', onJob).on('tab-failed', onTabFailed).on('job-end', onJobEnd).on('job-report', onJobReport).on('approve', onApprove).on('ask', onAsk).on('mcp', onMcp);
1101
1443
  return () => {
1102
- events.off('text', onText).off('thinking', onThinking).off('retry', onRetry).off('compact', onCompact).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('mcp', onMcp);
1444
+ 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);
1103
1445
  clearTimeout(state.leaving);
1104
1446
  clearTimeout(state.notice?.timer);
1105
1447
  clearTimeout(state.drawSoon);
@@ -1108,6 +1450,21 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1108
1450
  };
1109
1451
  }, []);
1110
1452
 
1453
+ // The tab's progress mark follows the work: busy from the first word sent to the last, and cleared when the chat closes.
1454
+ const busy = Boolean(state.working) && state.asks.length === 0;
1455
+ const marked = useRef(false);
1456
+ useEffect(() => {
1457
+ if (!progress || marked.current === busy) return;
1458
+ marked.current = busy;
1459
+ tell(busy ? PROGRESS_BUSY : PROGRESS_DONE);
1460
+ }, [busy]);
1461
+ useEffect(
1462
+ () => () => {
1463
+ if (marked.current) tell(PROGRESS_DONE);
1464
+ },
1465
+ [],
1466
+ );
1467
+
1111
1468
  // 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.
1112
1469
  useEffect(() => {
1113
1470
  const title = `${state.asks.length > 0 ? '? ' : state.working ? '✳ ' : ''}sumo · ${state.where.name}`;
@@ -1145,11 +1502,38 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1145
1502
  return;
1146
1503
  }
1147
1504
  for (const [one, oneKey] of keysOf(input, key)) {
1148
- // A question standing takes the key: an answer, or Esc and Ctrl-C, which go on to stop the turn; nothing lands in the box.
1149
- if (state.asks.length > 0 && !oneKey.escape && !(oneKey.ctrl && (one === 'c' || one === 'd'))) {
1150
- const answer = { y: 'once', a: 'always', n: 'no' }[one];
1505
+ // 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
+ if (state.ed.search) {
1507
+ state.ed = press(state.ed, one, oneKey, session.commands, files).state;
1508
+ continue;
1509
+ }
1510
+ // The keys, shown for `?` on an empty box until the next key — which goes on to do what it does, but Esc, which only closes them.
1511
+ if (state.keys) {
1512
+ state.keys = false;
1513
+ if (oneKey.escape || one === '?') continue;
1514
+ } else if (one === '?' && !state.ed.text && !oneKey.ctrl && !oneKey.meta && state.asks.length === 0 && state.pick === null) {
1515
+ state.keys = true;
1516
+ continue;
1517
+ }
1518
+ // A question of the model's: on an empty box the arrows move the pick and Enter takes it, or a number picks that option.
1519
+ // Anything else is the box's, and Enter there sends what was typed as the answer; Esc and Ctrl-C go on to stop the turn.
1520
+ const asked = state.asks[0]?.options ? state.asks[0] : null;
1521
+ if (asked && !state.ed.text && /^[1-9]$/.test(one) && Number(one) <= asked.options.length && !oneKey.ctrl && !oneKey.meta) {
1522
+ settle(asked, { label: asked.options[Number(one) - 1].label });
1523
+ continue;
1524
+ }
1525
+ if (asked && !state.ed.text && (oneKey.upArrow || oneKey.downArrow || (oneKey.return && !oneKey.shift && !oneKey.meta))) {
1526
+ if (oneKey.return) settle(asked, { label: asked.options[asked.at].label });
1527
+ else asked.at = Math.max(0, Math.min(asked.options.length - 1, asked.at + (oneKey.downArrow ? 1 : -1)));
1528
+ continue;
1529
+ }
1530
+ // 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
+ 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];
1151
1535
  if (answer) settle(state.asks[0], answer);
1152
- else notify('y allows it once · a always · n refuses it · esc stops the turn');
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');
1153
1537
  continue;
1154
1538
  }
1155
1539
  // A question from a job in the background: Esc refuses that one call, and stops nothing.
@@ -1175,8 +1559,9 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1175
1559
  // What is nearest goes first: Ctrl-C clears what is typed, Esc closes the menu, and only then is the turn stopped.
1176
1560
  // A menu of files is shut without a word of the message lost; a command half typed is all there is to lose.
1177
1561
  const open = oneKey.escape ? menuOf(state.ed, session.commands, files) : [];
1178
- if (oneKey.ctrl && state.ed.text) state.ed = editor(state.ed.history);
1179
- else if (open.length > 0) state.ed = open[0].file ? { ...state.ed, shut: state.ed.text } : editor(state.ed.history);
1562
+ // What Ctrl-C clears is not lost: Up brings it back, and so does Ctrl-Y.
1563
+ if (oneKey.ctrl && state.ed.text) state.ed = editor([...state.ed.history, state.ed.text], state.ed.text);
1564
+ else if (open.length > 0) state.ed = open[0].file ? { ...state.ed, shut: state.ed.text } : editor(state.ed.history, state.ed.kill);
1180
1565
  else if (state.working) {
1181
1566
  // Stopping the turn stops what was waiting on it too: it comes back to the box, to be sent again or not.
1182
1567
  takeBack([...state.queue]);
@@ -1199,6 +1584,15 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1199
1584
  openPager();
1200
1585
  continue;
1201
1586
  }
1587
+ // Ctrl-L: everything drawn again, for a screen something else wrote over.
1588
+ if (oneKey.ctrl && one === 'l') {
1589
+ refresh();
1590
+ continue;
1591
+ }
1592
+ if (oneKey.ctrl && one === 'z') {
1593
+ suspend();
1594
+ continue;
1595
+ }
1202
1596
  if (oneKey.ctrl && one === 'g') {
1203
1597
  openEditor();
1204
1598
  continue;
@@ -1224,7 +1618,8 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1224
1618
  // The first step is onto the row that is not on the screen already: a job from the chat, the chat from a job's record.
1225
1619
  if (oneKey.downArrow && pressed.state === state.ed && listed.length > 0) state.pick = state.open === null ? listed[1] : MAIN;
1226
1620
  state.ed = pressed.state;
1227
- if (pressed.submit !== undefined) submit(pressed.submit);
1621
+ if (pressed.submit !== undefined && asked) settle(asked, { text: pressed.submit });
1622
+ else if (pressed.submit !== undefined) submit(pressed.submit);
1228
1623
  }
1229
1624
  redraw();
1230
1625
  });
@@ -1237,52 +1632,66 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1237
1632
  return notify(cause.message);
1238
1633
  }
1239
1634
  if (images) for (const image of images) attach(image);
1240
- else state.ed = paste(state.ed, text);
1635
+ else {
1636
+ // What nobody can see in a paste — a direction override, a hidden tag — never reaches the model unseen.
1637
+ const { text: clean, removed } = cleanPaste(text);
1638
+ if (removed > 0) notify(`${removed} hidden character${removed === 1 ? '' : 's'} taken out of the paste`);
1639
+ const lines = clean.replace(/\r\n?/g, '\n').split('\n').length;
1640
+ if (lines > PASTE_LINES || clean.length > PASTE_CHARS) {
1641
+ // A long paste stands as a marker the box can hold; it goes whole with the message, and Backspace takes it out whole.
1642
+ state.pastes.push(clean.replace(/\r\n?/g, '\n'));
1643
+ state.ed = paste(state.ed, `[Pasted text #${state.pastes.length} ${lines > 1 ? `+${lines} lines` : `${clean.length} chars`}] `);
1644
+ } else state.ed = paste(state.ed, clean);
1645
+ }
1241
1646
  redraw();
1242
1647
  });
1243
1648
 
1649
+ if (state.closed) return h(Box, { flexDirection: 'column' }, h(Static, { key: state.epoch, items: state.items }, (item) => h(Item, { key: item.id, item, columns, s })));
1244
1650
  const menu = menuOf(state.ed, session.commands, files);
1245
1651
  const tail = state.reply?.tail ?? '';
1246
1652
  // The jobs the turn waits on: the ones whose call is still out. A job in the background holds nothing up.
1247
1653
  const atWork = [...state.jobs].filter(([, job]) => state.running.has(job.parent)).map(([id]) => `j${id}`);
1248
1654
  const reading = atWork.length === 0 ? 'next step' : `when ${atWork.join(', ')} report${atWork.length === 1 ? 's' : ''}`;
1655
+ // Once something has been said, the room is the conversation's: no logo, and no word in the box of what it is for.
1656
+ const said = state.log.some((entry) => entry.kind === 'user');
1249
1657
  // Ink adds a line under the frame; a frame that reached the last row would be drawn as a full screen.
1250
1658
  const room = state.unmeasured.length > 0 ? 0 : Math.max(0, rows - state.used - 1);
1251
1659
  return h(
1252
1660
  Box,
1253
1661
  { flexDirection: 'column', minHeight: room },
1254
- h(Static, { key: state.epoch, items: state.items }, (item) => h(Item, { key: item.id, item, columns })),
1662
+ h(Static, { key: state.epoch, items: state.items }, (item) => h(Item, { key: item.id, item, columns, s })),
1255
1663
  tail ? h(Reply, { text: tail, first: state.fresh }) : null,
1256
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
1257
1665
  // never move what follows — the working line keeps its clock.
1258
1666
  h(
1259
1667
  Box,
1260
1668
  { flexDirection: 'column' },
1261
- ...[...state.running.values()].map((call) => h(Tool, { key: call.id, columns, view: toolView(call, null, { cwd: state.where.cwd }), running: true, live: state.live.get(call.id), jobs: [...state.jobs].filter(([, job]) => job.parent === call.id) })),
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) })),
1262
1670
  // A job no call here started — none should be — still shows that it works.
1263
1671
  ),
1264
1672
  // 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.
1265
- state.working ? h(Working, { messages, first: state.working, tokens: state.tokens, thought: state.thought, quietAfterMs, heard: state.talking && state.running.size === 0 && state.jobs.size === 0 && state.asks.length === 0 ? state.heard : 0 }) : null,
1266
- state.asks.length > 0 ? h(Ask, { ask: state.asks[0], aside: session.running().includes(state.asks[0].job) }) : null,
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,
1267
1675
  // The record of the job that is open, under everything the turn is doing: its end, as it grows.
1268
1676
  state.open !== null ? h(JobOpen, { id: state.open, job: state.jobs.get(state.open), rows }) : null,
1269
1677
  // The logo is the empty room's: once something has been said, the room is the conversation's.
1270
- h(Room, { logo: state.log.some((entry) => entry.kind === 'user') ? [] : logo, rows, from: state.used }),
1678
+ h(Room, { logo: said ? [] : logo, rows, from: state.used }),
1271
1679
  h(
1272
1680
  Box,
1273
1681
  { flexDirection: 'column', marginTop: 1 },
1274
1682
  // A message for the model is read with its next request — which, while it waits on a delegated job, is when that job reports.
1275
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') ? ' …' : ''}`)),
1276
- h(Input, { state: state.ed, width: columns, rows }),
1684
+ // While a call waits on the user's word every key is the answer's: no box stands there to type into.
1685
+ state.asks.length > 0 && !state.asks[0].options ? null : h(Input, { state: state.ed, width: columns, rows, placeholder: said ? '' : 'Ask anything · / commands · @ files · ? keys' }),
1277
1686
  // 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.
1278
1687
  ...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 }))),
1279
- menu.length > 0 ? h(Menu, { menu, pick: state.ed.pick }) : h(Status, { session, leaving: Boolean(state.leaving), notice: state.notice?.text, jobs: [...state.jobs.keys()], aside: session.running(), pick: state.pick, open: state.open, where: state.where, spent: state.spent, waiting: state.queue.length > 0, columns }),
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 }),
1280
1689
  ),
1281
1690
  );
1282
1691
  }
1283
1692
 
1284
1693
  /** Starts the session and draws it. The returned instance's `waitUntilExit()` settles when the user leaves. */
1285
- export function runUi({ session, events, resume = null, stdin = process.stdin, stdout = process.stdout, messages = spinnerMessages(), cwd = process.cwd(), logo = logoLines(), clipboard = clipboardImage, copy = copyText, notify = true, notifyAfterMs = NOTIFY_AFTER_MS, quietAfterMs = QUIET_AFTER_MS, run = inTerminal, listFiles = gitFiles, debug = false }) {
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 }) {
1286
1695
  // 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.
1287
1696
  const opening = resume === null ? null : session.resume(resume);
1288
1697
  const block = opening ? '' : session.start('startup');
@@ -1303,5 +1712,5 @@ export function runUi({ session, events, resume = null, stdin = process.stdin, s
1303
1712
  stdin.unshift = putBack;
1304
1713
  }, KITTY_WAIT_MS).unref();
1305
1714
  }
1306
- return render(h(App, { session, events, messages, cwd, block, opening, logo, clipboard, copy, notify, notifyAfterMs, quietAfterMs, run, listFiles }), { stdin, stdout, debug, exitOnCtrlC: false, kittyKeyboard: { mode: 'auto' } });
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' } });
1307
1716
  }