sumo-agents 0.0.0-stage → 0.3.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 (66) hide show
  1. package/AGENTS.md +38 -0
  2. package/LICENSE +21 -0
  3. package/README.md +111 -2
  4. package/bin/sumo.mjs +33 -0
  5. package/guides/delegation.md +33 -0
  6. package/guides/feature.md +14 -0
  7. package/guides/fix.md +14 -0
  8. package/guides/memory.md +23 -0
  9. package/guides/projects.md +27 -0
  10. package/guides/review.md +16 -0
  11. package/guides/workflows.md +26 -0
  12. package/logo.txt +19 -0
  13. package/package.json +42 -4
  14. package/prompts/agent.md +7 -0
  15. package/prompts/dream.md +13 -0
  16. package/prompts/scribe.md +21 -0
  17. package/spinner.txt +90 -0
  18. package/src/advisor.mjs +59 -0
  19. package/src/apply.mjs +368 -0
  20. package/src/auth.mjs +80 -0
  21. package/src/card.mjs +72 -0
  22. package/src/catalog.mjs +167 -0
  23. package/src/chat.mjs +1162 -0
  24. package/src/cli.mjs +815 -0
  25. package/src/cost.mjs +128 -0
  26. package/src/db.mjs +384 -0
  27. package/src/dream.mjs +97 -0
  28. package/src/editor.mjs +198 -0
  29. package/src/export.mjs +132 -0
  30. package/src/guard.mjs +121 -0
  31. package/src/guides.mjs +86 -0
  32. package/src/herdr.mjs +117 -0
  33. package/src/hooks.mjs +270 -0
  34. package/src/images.mjs +89 -0
  35. package/src/jobs.mjs +1184 -0
  36. package/src/jobtools.mjs +82 -0
  37. package/src/local-server.mjs +169 -0
  38. package/src/lock.mjs +45 -0
  39. package/src/loop.mjs +838 -0
  40. package/src/mcp.mjs +604 -0
  41. package/src/memory.mjs +400 -0
  42. package/src/model.mjs +270 -0
  43. package/src/page.html +304 -0
  44. package/src/page.mjs +135 -0
  45. package/src/paths.mjs +33 -0
  46. package/src/prime.mjs +177 -0
  47. package/src/projects.mjs +232 -0
  48. package/src/recall.mjs +45 -0
  49. package/src/redact.mjs +173 -0
  50. package/src/render.mjs +45 -0
  51. package/src/route.mjs +287 -0
  52. package/src/sandbox.mjs +173 -0
  53. package/src/scan.mjs +204 -0
  54. package/src/scribe.mjs +349 -0
  55. package/src/sessions.mjs +371 -0
  56. package/src/setup.mjs +528 -0
  57. package/src/sqlite.mjs +66 -0
  58. package/src/text.mjs +97 -0
  59. package/src/tools.mjs +987 -0
  60. package/src/transcript.mjs +106 -0
  61. package/src/tty.mjs +529 -0
  62. package/src/ui.mjs +1363 -0
  63. package/src/verify.mjs +369 -0
  64. package/src/web.mjs +49 -0
  65. package/src/workflows.mjs +270 -0
  66. package/src/worktree.mjs +128 -0
package/src/ui.mjs ADDED
@@ -0,0 +1,1363 @@
1
+ import { Box, render, renderToString, Static, Text, useAnimation, useApp, useBoxMetrics, useInput, usePaste, useStdout, useWindowSize } from 'ink';
2
+ import { execFile, spawn } from 'node:child_process';
3
+ import { closeSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { createElement as h, useEffect, useReducer, useRef } from 'react';
6
+ import { compactLine, retryLine, routeLine, routeOf } from './chat.mjs';
7
+ import { liveFile } from './jobs.mjs';
8
+ import { stopReason } from './loop.mjs';
9
+ import { compactInput, INPUT_SHOWN } from './mcp.mjs';
10
+ import { paths } from './paths.mjs';
11
+ import { redact } from './redact.mjs';
12
+ import { elapsed } from './text.mjs';
13
+ import { editor, keysOf, matchFiles, menuOf, paste, press, under } from './editor.mjs';
14
+ import { clipboardImage, copyText, droppedImages } from './images.mjs';
15
+ import { BASH_TOOL, DELEGATE_TOOL, EDITOR_TOOL } from './tools.mjs';
16
+ import { colourEnabled, createRenderer, flow, fold, logoLines, messageAt, pathFrom, pickMessage, renderBlock, safeForTerminal, spinnerMessages, styles, sunset, tilde, toolView, transcript, untab, wrap } from './tty.mjs';
17
+
18
+ /**
19
+ * The chat on a real terminal. What is finished scrolls away above — what
20
+ * was typed, each line of a reply, each tool call with the top of its result;
21
+ * of the memory block, which is the model's, only a warning — and what is live
22
+ * stays at the bottom: the line being
23
+ * written, the command running, the working line, the box to type in. Typing
24
+ * never waits for the model: a message sent mid-turn is queued, Esc stops the
25
+ * turn. A job run in the chat is shown the same way, set in under a line that
26
+ * says who it is — each call on one line, its output behind Ctrl-O — and a
27
+ * line starting with @ is said to it. An image pasted with Ctrl-V, or a file
28
+ * dropped on the box, stands in it as `[Image #n]` and goes with the message
29
+ * that names it. The chat opens on its name in blocks, in a sunset; while the
30
+ * conversation is short the box stands at the foot of the window, and until the
31
+ * first message is sent the logo stands faint in the room above it. A command
32
+ * shows what it prints while it runs; a message sent while the model works is
33
+ * read with its next request; a turn ends on a line that says how long it took,
34
+ * what it changed and what it cost, and — when the window is not the one in
35
+ * front — on a bell. A job delegated in the background does not hold the turn:
36
+ * it stands under the box while it works, the chat goes on, and when it reports
37
+ * the screen starts the turn that reads the report. Down steps onto a job there
38
+ * and Enter opens it: the end of its record above the box, until Esc. All of it
39
+ * is drawing; the session in chat.mjs does the work.
40
+ */
41
+
42
+ const ACCENT = '#d77757';
43
+ /** The name at the top of the chat, two rows of blocks. */
44
+ const WORDMARK = ['█▀▀ █ █ █▀▄▀█ █▀█', '▄▄█ █▄█ █ ▀ █ █▄█'];
45
+ const FLOW_STEP_MS = 100;
46
+ const TONES = { plain: {}, dim: { dimColor: true }, error: { color: 'red' }, add: { color: 'green' }, del: { color: 'red' }, ask: { color: 'yellow' } };
47
+ const LEAVE_WINDOW_MS = 2000;
48
+ const NOTICE_MS = 3000;
49
+ const RESIZE_SETTLE_MS = 120;
50
+ /** Wipes the window and what has scrolled off it, before everything is drawn again. */
51
+ const CLEAR = '\x1b[2J\x1b[3J\x1b[H';
52
+ /**
53
+ * The window scrolled clear: what it showed goes up into the terminal's scrollback, where it can still be read, and
54
+ * the drawing starts at the top. For a chat that opens, or starts over — nothing that was on the terminal is lost to it.
55
+ */
56
+ const scrolledClear = (rows) => `\x1b[${rows};1H${'\n'.repeat(rows)}\x1b[H`;
57
+ /** The terminal says when its window comes to the front and goes behind (`[I`, `[O`); and keeps its title, to be given back. */
58
+ const FOCUS_ON = '\x1b[?1004h';
59
+ const FOCUS_OFF = '\x1b[?1004l';
60
+ const TITLE_KEEP = '\x1b[22;0t';
61
+ const TITLE_BACK = '\x1b[23;0t';
62
+ /**
63
+ * The terminal's second screen, for a program handed the terminal: whatever it prints is gone with it, and the chat is as
64
+ * it was. The cursor is not moved here: a terminal with no second screen would take that for a move on this one.
65
+ */
66
+ const SCREEN_ASIDE = '\x1b[?1049h';
67
+ const SCREEN_BACK = '\x1b[?1049l';
68
+ /** Longer than Ink waits for the terminal to say how its keyboard speaks (200 ms): see `runUi`. */
69
+ const KITTY_WAIT_MS = 300;
70
+ /** A turn at least this long ends on a bell when the window is not in front, and on its footer whatever it did. */
71
+ const NOTIFY_AFTER_MS = 10_000;
72
+ /** No word from the model for this long, with nothing running, is said on the working line. */
73
+ const QUIET_AFTER_MS = 20_000;
74
+ /** Of what a running command prints, the last lines are shown; this much of it is kept to find them in. */
75
+ const LIVE_LINES = 3;
76
+ const LIVE_KEPT_CHARS = 4000;
77
+ const LIVE_DRAW_MS = 100;
78
+ /** 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
+ const INPUT_ROWS = 10;
80
+ const ECHO_LINES = 10;
81
+ /** How long the list of a project's files is good for, while a file is being named with `@`. */
82
+ const FILES_FRESH_MS = 15_000;
83
+ /** How many of a resumed session's turns are drawn again: enough to see where it stopped. */
84
+ const REPLAY_TURNS = 5;
85
+
86
+ /**
87
+ * A program given the terminal — an editor, a pager — until it exits. The program is the user's own setting, so a shell
88
+ * reads it: `code -w`, `less -R`. It is given the terminal opened afresh, not this process's own three descriptors: a
89
+ * child that inherits those has them set to block, for this process too, and the first read after it has gone would
90
+ * hold everything here until a key was pressed.
91
+ */
92
+ const inTerminal = (program, file) =>
93
+ new Promise((resolve, reject) => {
94
+ let own = null;
95
+ try {
96
+ own = openSync('/dev/tty', 'r+');
97
+ } catch {
98
+ // No terminal to open by name: the program has this process's, as it would from a shell.
99
+ }
100
+ const done = (settle) => (value) => {
101
+ if (own !== null) closeSync(own);
102
+ own = null;
103
+ settle(value);
104
+ };
105
+ const child = spawn('sh', ['-c', `${program} "$0"`, file], { stdio: own === null ? 'inherit' : [own, own, own] });
106
+ child.on('error', done(reject));
107
+ child.on('close', done(resolve));
108
+ });
109
+
110
+ /** The files of the project at `cwd` as git knows them, the untracked ones it does not ignore included; none where there is no repository. */
111
+ const gitFiles = (cwd) =>
112
+ new Promise((resolve) => {
113
+ execFile('git', ['ls-files', '-co', '--exclude-standard'], { cwd, maxBuffer: 32 * 1024 * 1024 }, (error, out) => resolve(error ? [] : out.split('\n').filter(Boolean)));
114
+ });
115
+
116
+ /**
117
+ * A saved conversation as the entries the screen draws, for a session picked up again: the last `turns` things the user
118
+ * said, each with what was answered and done after it. The memory block, the operator's words and a job's report are the
119
+ * model's to read, not the user's to see again; a message read mid-turn is shown as what was said.
120
+ */
121
+ export function replayOf(messages, turns = REPLAY_TURNS) {
122
+ const entries = [];
123
+ const starts = [];
124
+ const calls = new Map();
125
+ for (const message of messages) {
126
+ if (message.role === 'system') continue;
127
+ const blocks = typeof message.content === 'string' ? [{ type: 'text', text: message.content }] : message.content;
128
+ if (message.role === 'assistant') {
129
+ const raw = blocks.filter((b) => b.type === 'text').map((b) => b.text).join('\n').trim();
130
+ if (raw) entries.push({ kind: 'reply', raw });
131
+ for (const b of blocks) if (b.type === 'tool_use') calls.set(b.id, b);
132
+ continue;
133
+ }
134
+ for (const b of blocks) {
135
+ if (b.type === 'tool_result' && calls.has(b.tool_use_id)) {
136
+ const content = typeof b.content === 'string' ? b.content : (b.content ?? []).map((c) => c.text ?? '').join('\n');
137
+ entries.push({ kind: 'tool', call: calls.get(b.tool_use_id), result: { content, isError: Boolean(b.is_error) } });
138
+ } else if (b.type === 'text') {
139
+ const said = /^The user says, while you work: ([\s\S]*)$/.exec(b.text)?.[1].replace(/\n<sumo>[\s\S]*$/, '') ?? b.text;
140
+ if (/^<sumo[->]|^An automated event|^\[Image #\d+\]$/.test(said)) continue;
141
+ starts.push(entries.length);
142
+ entries.push({ kind: 'user', text: said });
143
+ }
144
+ }
145
+ }
146
+ if (starts.length <= turns) return entries;
147
+ const hidden = starts.length - turns;
148
+ 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
+ }
150
+
151
+ /** What Up recalls across sessions: the last lines typed, one a line, in the home. */
152
+ const HISTORY_KEPT = 50;
153
+ const historyFile = () => join(paths().home, 'history');
154
+ function readHistory() {
155
+ try {
156
+ return readFileSync(historyFile(), 'utf8').split('\n').filter(Boolean).slice(-HISTORY_KEPT);
157
+ } catch {
158
+ return [];
159
+ }
160
+ }
161
+ /**
162
+ * A line typed joins the file; a line that repeats the last is not written twice; the file never holds more than the kept count.
163
+ * It is what the user typed, so it is for its owner only — and it is a convenience: a file that cannot be written costs the recall, never the turn.
164
+ */
165
+ function keepHistory(line) {
166
+ const one = line.replace(/\n/g, ' ');
167
+ const lines = readHistory();
168
+ if (lines.at(-1) === one) return;
169
+ lines.push(one);
170
+ try {
171
+ mkdirSync(paths().home, { recursive: true, mode: 0o700 });
172
+ writeFileSync(historyFile(), `${lines.slice(-HISTORY_KEPT).join('\n')}\n`, { mode: 0o600 });
173
+ } catch {
174
+ // Nowhere to keep it: the line is still sent.
175
+ }
176
+ }
177
+
178
+ const thousands = (n) => (n >= 1000 ? `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)}k` : String(n));
179
+
180
+ /**
181
+ * The lines under a call: what came back, the first of them with the mark. Folded to `columns` here, by the same count the
182
+ * replies are folded by, so a line too long for the window goes on under itself — not under the mark, and not past the edge.
183
+ */
184
+ const linesUnder = (lines, columns) =>
185
+ lines
186
+ .flatMap((line) => fold(untab(line.text), Math.max(20, columns - 6)).map((text) => ({ ...line, text })))
187
+ .map((line, i) => h(Text, { key: i, ...TONES[line.tone], wrap: 'truncate' }, `${i === 0 ? ' ⎿ ' : ' '}${line.text}`));
188
+
189
+ /**
190
+ * The last lines a running command has printed, as the screen may show them: without secrets or control characters, a
191
+ * progress bar as its latest state. What was kept may begin mid-line — or mid-secret — so its first line is not shown.
192
+ */
193
+ function lastLines({ out, cut }) {
194
+ const lines = safeForTerminal(redact(out).text).split(/\r?\n|\r/);
195
+ return (cut ? lines.slice(1) : lines).map((l) => untab(l).trimEnd()).filter(Boolean).slice(-LIVE_LINES);
196
+ }
197
+
198
+ /** A command that is running: for how long, and the last of what it has printed so far. */
199
+ function Running({ live }) {
200
+ // Drawn again more often than the clock it shows turns over, so a second is not skipped by a tick that came just short of it.
201
+ useAnimation({ interval: 250 });
202
+ const ran = live ? Date.now() - live.since : 0;
203
+ return h(
204
+ Box,
205
+ { flexDirection: 'column' },
206
+ h(Text, { dimColor: true }, ` ⎿ Running…${ran >= 1000 ? ` ${elapsed(ran)}` : ''}`),
207
+ ...(live ? lastLines(live) : []).map((line, i) => h(Text, { key: i, dimColor: true, wrap: 'truncate' }, ` ${line}`)),
208
+ );
209
+ }
210
+
211
+ /** A tool call: what ran, and under it what came back — or, while it runs, the jobs it started, or what it prints. */
212
+ function Tool({ view, failed = false, running = false, jobs = [], live = null, columns }) {
213
+ return h(
214
+ Box,
215
+ { flexDirection: 'column', marginTop: 1 },
216
+ // The mark stands apart from the words, so a command that wraps, or has lines of its own, goes on under them, not under it.
217
+ h(
218
+ Box,
219
+ null,
220
+ h(Box, { flexShrink: 0 }, h(Text, { color: running ? undefined : failed ? 'red' : 'green', dimColor: running }, '⏺ ')),
221
+ h(Box, { flexShrink: 1 }, h(Text, null, h(Text, { bold: true }, view.title), `(${untab(view.detail)})`, view.stat ? h(Text, null, ' ', h(Text, { color: 'green' }, `+${view.stat.added}`), ' ', h(Text, { color: 'red' }, `−${view.stat.removed}`)) : null)),
222
+ ),
223
+ running && jobs.length === 0 ? h(Running, { live }) : null,
224
+ ...jobs.map(([id, job]) => h(JobAtWork, { key: id, id, job })),
225
+ ...linesUnder(view.lines, columns),
226
+ );
227
+ }
228
+
229
+ /** The rows the screen gives to what the model is thinking. */
230
+ const THOUGHT_ROWS = 3;
231
+
232
+ /**
233
+ * The end of what the model has thought so far, folded to `width`: its last rows, because what it is thinking now is at
234
+ * the end — a summary is one long paragraph, and cut at the window's edge only its first words would ever show.
235
+ */
236
+ const thoughtRows = (text, width, rows = THOUGHT_ROWS) =>
237
+ String(text ?? '')
238
+ .split('\n')
239
+ .map((line) => line.replace(/\s+/g, ' ').trim())
240
+ .filter(Boolean)
241
+ .flatMap((line) => wrap(line, width).split('\n'))
242
+ .slice(-rows);
243
+
244
+ /** The most of a job's title its row under the box shows. */
245
+ const TITLE_CHARS = 32;
246
+
247
+ /**
248
+ * A job at work, in one line: how long, how many calls, and that it is working — what it runs and thinks is in its record,
249
+ * a step and Enter away, not here. Under the call that waits for it; or — at work in the background, with no call standing
250
+ * over it — in a row of its own under the box, with who it is, marked when it is the one stepped on (`picked`) or the one
251
+ * whose record is open.
252
+ */
253
+ function JobAtWork({ id, job, alone = false, picked = false, open = false }) {
254
+ useAnimation({ interval: 1000 });
255
+ const calls = `${job.calls} tool call${job.calls === 1 ? '' : 's'}`;
256
+ const mark = alone ? (picked ? ' ❯ ' : ' ⏺ ') : ' ⎿ ';
257
+ const who = alone ? ` ${job.agent} — ${job.title.length > TITLE_CHARS ? `${job.title.slice(0, TITLE_CHARS - 1)}…` : job.title}` : '';
258
+ const lead = `j${id}${who} · ${elapsed(Date.now() - job.since)} · ${calls} · `;
259
+ return h(
260
+ Text,
261
+ { wrap: 'truncate' },
262
+ h(Text, picked || open ? { color: ACCENT } : { dimColor: true }, mark),
263
+ h(Text, { dimColor: !picked }, lead),
264
+ h(Text, { dimColor: true }, 'working'),
265
+ );
266
+ }
267
+
268
+ /** The chat itself, as the first of the rows under the box: the place Enter comes back to from a job's record. */
269
+ const MAIN = 'main';
270
+
271
+ /** The chat's own row, over the jobs it delegated: marked when it is the one stepped on (`picked`), or the one on the screen (`shown`). */
272
+ function MainAtWork({ working, picked = false, shown = false }) {
273
+ return h(Text, { wrap: 'truncate' }, h(Text, picked || shown ? { color: ACCENT } : { dimColor: true }, picked ? ' ❯ ' : ' ⏺ '), h(Text, { dimColor: !picked }, 'main · '), h(Text, { dimColor: true }, working ? 'working' : 'idle'));
274
+ }
275
+
276
+ /** What a job at work has written down so far, as the screen may show it: its lines, under the one that says who it is. None where there is no record yet. */
277
+ function recordLines(id) {
278
+ try {
279
+ return safeForTerminal(readFileSync(liveFile(id), 'utf8')).trimEnd().split('\n').slice(1);
280
+ } catch {
281
+ return [];
282
+ }
283
+ }
284
+
285
+ /** The rows of the window an open job's record may take: the turn's own work, the box and the rows under it need the rest. */
286
+ const openRows = (rows) => Math.max(3, Math.min(rows - 24, Math.floor(rows / 2)));
287
+
288
+ /**
289
+ * A job opened from under the box: who it is, and the end of what it has written down — each call with the top of what
290
+ * came back, and what it said — read again as its clock ticks. It is the record `sumo job watch` follows; Ctrl-O has all of it.
291
+ */
292
+ function JobOpen({ id, job, rows }) {
293
+ useAnimation({ interval: 1000 });
294
+ const all = recordLines(id);
295
+ const seen = all.slice(-openRows(rows));
296
+ const above = all.length - seen.length;
297
+ return h(
298
+ Box,
299
+ { flexDirection: 'column', marginTop: 1 },
300
+ h(Text, { wrap: 'truncate' }, h(Text, { color: ACCENT }, '⏺ '), h(Text, { bold: true }, `j${id}`), ` ${job.agent} · ${job.route} — ${job.title}`),
301
+ above > 0 ? h(Text, { dimColor: true }, ` … +${above} line${above === 1 ? '' : 's'}`) : null,
302
+ all.length === 0 ? h(Text, { dimColor: true }, ' nothing done yet') : null,
303
+ ...seen.map((line, i) => h(Text, { key: i, dimColor: /^\s*⎿/.test(line), wrap: 'truncate' }, untab(line) || ' ')),
304
+ );
305
+ }
306
+
307
+ /** The most of a call's input the question shows in full; past it, the cut is said. A recipient or a body hidden past the cut is one the user never approved. */
308
+ const ASK_INPUT_MAX = 4_000;
309
+
310
+ /** A call waiting on the user's word: who asks, what would run with what — the whole input, not its first line — and the keys that answer. */
311
+ function Ask({ ask, aside = false }) {
312
+ const who = ask.job ? `j${ask.job}: ` : '';
313
+ // A command the sandbox blocked is asked as itself: the command, to run once outside the sandbox — yes or no, never always.
314
+ const command = ask.unsandboxed ? safeForTerminal(String(ask.input?.command ?? '')) : null;
315
+ const whole = command ?? JSON.stringify(ask.input ?? {});
316
+ // Short enough for the line, it is on the line; longer, it is laid out under it, every field whole, up to the cut.
317
+ const short = whole.length <= INPUT_SHOWN && !whole.includes('\n');
318
+ const laid = short ? [] : command !== null ? command.split('\n') : JSON.stringify(ask.input ?? {}, null, 2).split('\n');
319
+ const kept = [];
320
+ let size = 0;
321
+ for (const line of laid) {
322
+ if (size + line.length > ASK_INPUT_MAX) break;
323
+ kept.push(line);
324
+ size += line.length + 1;
325
+ }
326
+ const cut = laid.length - kept.length;
327
+ // 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.
328
+ return h(
329
+ Box,
330
+ { marginTop: 1, flexDirection: 'column' },
331
+ h(Text, { color: 'yellow' }, command !== null ? `⚠ ${who}run this once outside the sandbox?${short ? ` ${whole}` : ''}` : `⚠ ${who}allow ${ask.server} · ${ask.tool}(${short ? whole : '…'})?`),
332
+ ...kept.map((line, i) => h(Text, { key: i, color: 'yellow', wrap: 'truncate-end' }, ` ${line}`)),
333
+ cut > 0 ? h(Text, { color: 'yellow', dimColor: true }, ` … ${cut} more line${cut === 1 ? '' : 's'} of input not shown — n, and ask the model for less`) : null,
334
+ h(Text, { dimColor: true }, ` ${command !== null ? 'y yes · n no' : 'y once · a always · n no'} · esc ${aside ? 'no' : 'stop'}`),
335
+ );
336
+ }
337
+
338
+ /** A question of the model's: its options, the one the arrows are on, and the keys that answer — a pick, or words typed in the box. */
339
+ function Question({ ask }) {
340
+ return h(
341
+ Box,
342
+ { marginTop: 1, flexDirection: 'column' },
343
+ h(Text, { color: 'yellow' }, `? ${ask.question}`),
344
+ ...ask.options.map((option, i) => h(Text, { key: i, color: i === ask.at ? ACCENT : undefined }, ` ${i === ask.at ? '❯' : ' '} ${option.label}`, option.detail ? h(Text, { dimColor: true }, ` — ${option.detail}`) : null)),
345
+ h(Text, { dimColor: true }, ' ↑↓ choose · enter picks · or type your own answer · esc stop'),
346
+ );
347
+ }
348
+
349
+ /** One line of a reply; the first of a block carries the mark. */
350
+ function Reply({ text, first }) {
351
+ return h(Box, { marginTop: first ? 1 : 0 }, h(Text, null, first ? '⏺ ' : ' '), h(Text, null, text || ' '));
352
+ }
353
+
354
+ /** Something finished, drawn once and left to scroll. */
355
+ /** `columns` is the window's width, handed down: every item asking the terminal for it would be a listener each, on a stream that takes ten. */
356
+ function Item({ item, columns }) {
357
+ if (item.kind === 'header') {
358
+ return h(
359
+ Box,
360
+ { flexDirection: 'column' },
361
+ h(
362
+ Box,
363
+ { gap: 3, marginTop: 1 },
364
+ // The sunset runs across the name, gold at the S to crimson at the O.
365
+ h(Box, { flexDirection: 'column', flexShrink: 0 }, ...WORDMARK.map((row, r) => h(Text, { key: r }, ...[...row].map((ch, i) => h(Text, { key: i, color: sunset(i / (row.length - 1)) }, ch))))),
366
+ h(Box, { flexDirection: 'column' }, h(Text, null, item.route), h(Text, { dimColor: true }, item.cwd)),
367
+ ),
368
+ item.block ? h(Box, { marginTop: 1 }, h(Text, null, item.block)) : null,
369
+ );
370
+ }
371
+ // What the user said is what a scroll back looks for: full weight, a bar of the chat's colour down its side.
372
+ if (item.kind === 'user') {
373
+ return h(
374
+ Box,
375
+ { marginTop: 1, flexDirection: 'column', borderStyle: 'bold', borderColor: ACCENT, borderTop: false, borderRight: false, borderBottom: false, paddingLeft: 1 },
376
+ h(Text, null, untab(item.text)),
377
+ item.more ? h(Text, { dimColor: true }, `… +${item.more} line${item.more === 1 ? '' : 's'}`) : null,
378
+ );
379
+ }
380
+ if (item.kind === 'text') return h(Reply, item);
381
+ if (item.kind === 'tool') return h(Tool, { ...item, columns });
382
+ if (item.kind === 'output') return h(Box, { flexDirection: 'column' }, ...linesUnder(item.lines, columns));
383
+ if (item.kind === 'footer') return h(Box, { marginTop: 1 }, h(Text, { dimColor: true }, ` ${item.text}`));
384
+ // The mark stands apart from the words, so a line that wraps in a narrow window goes on under them, not under it.
385
+ if (item.kind === 'job') return h(Box, { marginTop: 1 }, h(Text, { color: ACCENT }, '⏺ '), h(Text, null, h(Text, { bold: true }, `j${item.id}`), ` ${item.agent} · ${item.route} — ${item.title}`, h(Text, { dimColor: true }, ` · ${item.where}`)));
386
+ if (item.kind === 'error') return h(Box, { marginTop: 1 }, h(Text, { color: 'red' }, item.text));
387
+ return h(Box, { flexDirection: 'column' }, ...linesUnder(item.text.split('\n').map((text) => ({ text, tone: 'dim' })), columns));
388
+ }
389
+
390
+ /**
391
+ * The line that says it is working: your words, the next of them every few seconds, a sunset flowing through them; how
392
+ * long, how much, and how to stop it. Under it, while the model thinks, the last rows of what it has thought so far.
393
+ */
394
+ function Working({ messages, first, tokens, thought = '', heard = 0, quietAfterMs = QUIET_AFTER_MS }) {
395
+ const { frame, time } = useAnimation({ interval: FLOW_STEP_MS });
396
+ const { columns } = useWindowSize();
397
+ const words = `${messageAt(messages, first, time)}…`;
398
+ const spent = tokens > 0 ? ` · ↓ ${thousands(tokens)} tokens` : '';
399
+ const thinking = thoughtRows(thought, Math.max(20, columns - 6));
400
+ // `heard` is when the model last said or did anything, while nothing of its own is running: a long silence is said, so a stream that died is told from one that thinks.
401
+ const silent = heard > 0 ? Date.now() - heard : 0;
402
+ const quiet = silent >= quietAfterMs ? ` · quiet ${elapsed(silent)}` : '';
403
+ return h(
404
+ Box,
405
+ { marginTop: 1, flexDirection: 'column' },
406
+ h(Box, null, h(Text, null, ...[...words].map((ch, i) => h(Text, { key: i, color: flow(i, frame) }, ch)), ' '), h(Text, { dimColor: true }, `(${Math.floor(time / 1000)}s${spent}${quiet} · esc to interrupt)`)),
407
+ ...thinking.map((row, i) => h(Text, { key: i, dimColor: true, wrap: 'truncate' }, `${i === 0 ? ' ⎿ ' : ' '}${row}`)),
408
+ );
409
+ }
410
+
411
+ /**
412
+ * The part of the text the box draws when it is too long to draw whole: `max` rows of it around the cursor, a row being
413
+ * 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
414
+ * is not touched: this is only what is shown of it.
415
+ */
416
+ export function inView({ text, cursor }, width, max) {
417
+ const rows = [];
418
+ let at = 0;
419
+ for (const line of text.split('\n')) {
420
+ for (let i = 0; i === 0 || i < line.length; i += width) rows.push([at + i, at + Math.min(line.length, i + width)]);
421
+ at += line.length + 1;
422
+ }
423
+ if (rows.length <= max) return { text, cursor, above: 0, below: 0 };
424
+ const on = Math.max(0, rows.findLastIndex(([from]) => from <= cursor));
425
+ const first = Math.min(Math.max(0, on - (max - 2)), rows.length - max);
426
+ const last = first + max - 1;
427
+ return { text: text.slice(rows[first][0], rows[last][1]), cursor: cursor - rows[first][0], above: first, below: rows.length - 1 - last };
428
+ }
429
+
430
+ /** The box to type in, the cursor drawn where the next key lands; of a text too long for it, the rows around the cursor. */
431
+ function Input({ state, width, rows }) {
432
+ const seen = inView(state, Math.max(10, width - 6), Math.max(3, Math.min(INPUT_ROWS, rows - 12)));
433
+ const { text, cursor } = seen;
434
+ const on = under(seen);
435
+ // A cursor on a line end, or past the last character, is drawn as a space of its own.
436
+ const shown = on === '' || on === '\n' ? ' ' : on;
437
+ const after = on === '\n' ? text.slice(cursor) : text.slice(cursor + on.length);
438
+ const hidden = (n) => (n > 0 ? h(Text, { dimColor: true }, `… +${n} line${n === 1 ? '' : 's'}`) : null);
439
+ return h(
440
+ Box,
441
+ { borderStyle: 'round', borderColor: 'gray', paddingX: 1, width },
442
+ h(Text, null, '> '),
443
+ h(Box, { flexGrow: 1, flexShrink: 1, flexDirection: 'column' }, hidden(seen.above), h(Text, null, untab(text.slice(0, cursor)), h(Text, { inverse: true }, untab(shown)), untab(after)), hidden(seen.below)),
444
+ );
445
+ }
446
+
447
+ function Menu({ menu, pick }) {
448
+ const wide = Math.max(...menu.map((c) => c.label.length)) + 2;
449
+ return h(
450
+ Box,
451
+ { flexDirection: 'column', paddingX: 2 },
452
+ ...menu.map((c, i) => h(Text, { key: c.name, color: i === pick ? ACCENT : undefined, dimColor: i !== pick }, c.label.padEnd(wide), c.hint)),
453
+ );
454
+ }
455
+
456
+ /** A sum of money for a margin: nothing until it is a cent. */
457
+ const dollars = (cost) => (cost >= 0.005 ? `$${cost.toFixed(2)}` : '');
458
+
459
+ function Status({ session, leaving, notice, jobs, aside = [], pick = null, open = null, where, spent, waiting, columns }) {
460
+ const size = session.contextTokens >= 1000 ? ` · ${Math.round(session.contextTokens / 1000)}k context` : '';
461
+ const cost = dollars(spent) && ` · ${dollars(spent)}`;
462
+ // Where the tools run: the project and the branch it is on. The header that says it scrolls away; this does not.
463
+ const place = where ? `${where.name}${where.branch ? ` (${where.branch})` : ''}` : '';
464
+ const hint = leaving ? `Ctrl-C again to leave${aside.length > 0 ? ` — it stops ${aside.map((id) => `j${id}`).join(', ')}, to be picked up again later` : ''}` : notice ? notice : pick === MAIN ? 'enter shows main · ↑ back to the box' : pick !== null ? `enter opens j${pick} · ↑ back to the box` : open !== null ? `esc closes j${open} · ctrl-o all of its record · @ message talks to it` : jobs.length > 0 ? `${jobs.length === 1 ? `@ message talks to j${jobs[0]}` : '@j<id> message talks to that job'} · ${aside.length > 0 ? `↓ enter opens ${aside.length === 1 ? 'it' : 'one'} · /stop stops it` : 'ctrl-o full output'}` : waiting ? '↑ takes back what is waiting' : '/ commands · /help · ctrl-o full output';
465
+ // In a narrow window the hints give way, then the place — unless the line has something to say just now, which the place
466
+ // gives way to; the model, the size of the context and the cost never fold.
467
+ const route = `${routeLine(session)}${size}${cost}`;
468
+ const room = columns - 4 - route.length - 2;
469
+ const said = leaving || notice;
470
+ const placed = place && place.length <= room - (said ? hint.length + 2 : 0) ? place : '';
471
+ const hinted = room - (placed ? placed.length + 2 : 0) >= 12 ? hint : '';
472
+ // With jobs at work the keys are what is needed, and they are long: they follow the jobs, from the left, and give way in a
473
+ // narrow window; the route stands at the right, over the place, so nothing under the jobs reads as one more of them.
474
+ if (jobs.length > 0) {
475
+ return h(
476
+ Box,
477
+ { paddingX: 2, flexDirection: 'column' },
478
+ h(Box, { justifyContent: 'space-between', gap: 2 }, h(Box, { flexShrink: 1 }, h(Text, { dimColor: true, wrap: 'truncate' }, hint)), h(Box, { flexShrink: 0 }, h(Text, { dimColor: true }, route))),
479
+ place && place.length <= columns - 4 ? h(Box, { justifyContent: 'flex-end' }, h(Text, { dimColor: true }, place)) : null,
480
+ );
481
+ }
482
+ return h(
483
+ Box,
484
+ { paddingX: 2, justifyContent: 'space-between', gap: 2 },
485
+ h(Box, { flexShrink: 0 }, h(Text, { dimColor: true }, route)),
486
+ placed ? h(Box, { flexShrink: 0 }, h(Text, { dimColor: true }, placed)) : null,
487
+ hinted ? h(Box, { flexShrink: 1 }, h(Text, { dimColor: true, wrap: 'truncate' }, hinted)) : null,
488
+ );
489
+ }
490
+
491
+ /** `/help`: every command with what it does, and the keys — written as a reply is, so it is drawn as one. */
492
+ function helpText(commands) {
493
+ const keys = [
494
+ ['Enter', 'send — while the model works, it reads the message with its next step'],
495
+ ['\\\\ then Enter · Shift-Enter · Option-Enter · Ctrl-J', 'a new line'],
496
+ ['Up · Down', 'between the lines of the text, then through what you sent before; on an empty box, Up takes back a message that is waiting'],
497
+ ['Esc', 'stop the turn (first closes the command menu); what was waiting comes back to the box'],
498
+ ['Ctrl-C', 'clear the box; on an empty one, stop the turn, or twice to leave — Ctrl-D leaves too'],
499
+ ['Ctrl-O', 'the whole conversation in your pager ($PAGER, or less): every command and all its output, to scroll and search'],
500
+ ['Ctrl-G', 'write the message in your editor ($VISUAL or $EDITOR); what you save comes back to the box'],
501
+ ['@ and a few letters', 'name a file of the project: the menu offers the ones they could mean, and Enter or Tab puts the path in'],
502
+ ['Ctrl-V', 'paste an image from the clipboard; an image file dropped on the box is the image'],
503
+ ['Ctrl-A · Ctrl-E', 'the start and the end of the line'],
504
+ ['Ctrl-U · Ctrl-K', 'cut to the start, or to the end, of the line'],
505
+ ['Ctrl-W · Option-Backspace', 'cut the word before the cursor'],
506
+ ['Option-Left · Option-Right', 'a word at a time'],
507
+ ['! command', 'run a command yourself, where the agent would be refused; the model sees what it printed'],
508
+ ['@ message · @j<id> message', 'say it to the job that is running — the one open, when one is — or to a named one'],
509
+ ['Down, then Enter', 'from the box onto the jobs at work under it, and open the one stepped on: the end of its record, as it grows; Esc closes it, Ctrl-O shows all of it'],
510
+ ];
511
+ return [
512
+ '**Commands**',
513
+ '',
514
+ '| Command | What it does |',
515
+ '|---|---|',
516
+ ...commands.map((c) => `| \`/${c.name}\` | ${c.hint.replaceAll('|', '\\|')} |`),
517
+ '',
518
+ '**Keys**',
519
+ '',
520
+ '| Key | What it does |',
521
+ '|---|---|',
522
+ ...keys.map(([key, does]) => `| ${key} | ${does} |`),
523
+ '',
524
+ ].join('\n');
525
+ }
526
+
527
+ /**
528
+ * The room between the conversation and the box, with the logo behind it: faint, in the middle of the window, where it stays while
529
+ * the conversation grows over it — what reaches it covers it. `from` is the row of the window the live part of the screen starts on.
530
+ */
531
+ function Room({ logo, rows, from }) {
532
+ const ref = useRef(null);
533
+ const { width, height, top, hasMeasured } = useBoxMetrics(ref);
534
+ const wide = Math.max(0, ...logo.map((row) => row.length));
535
+ const at = Math.floor((rows - logo.length) / 2) - from - top;
536
+ const seen = logo.length > 0 && hasMeasured && width >= wide && at < height && at + logo.length > 0;
537
+ return h(
538
+ Box,
539
+ { ref, flexGrow: 1, flexDirection: 'column', overflow: 'hidden' },
540
+ seen ? h(Box, { position: 'absolute', top: at, left: Math.floor((width - wide) / 2), flexDirection: 'column' }, ...logo.map((row, i) => h(Text, { key: i, color: 'gray', dimColor: true }, row || ' '))) : null,
541
+ );
542
+ }
543
+
544
+ function App({ session, events, messages, cwd, block, opening, logo, clipboard, copy, notify: alerts, notifyAfterMs, quietAfterMs, run, listFiles }) {
545
+ const { exit, suspendTerminal } = useApp();
546
+ const { stdout, write } = useStdout();
547
+ const { columns, rows } = useWindowSize();
548
+ const [, redraw] = useReducer((n) => n + 1, 0);
549
+ const s = styles(colourEnabled(stdout));
550
+ const header = (text) => ({ kind: 'header', route: routeLine(session), cwd: tilde(cwd), block: text });
551
+ // What the screen holds between draws. Keys and the session's events both write here, in the order they happen, and then ask for a draw.
552
+ // `log` is what happened, as it was said; `items` is the log drawn for this window, and is drawn again when the window or the view changes.
553
+ const st = useRef(null);
554
+ // `live` is what each running command has printed so far and since when; `heard`, when the model last said or did anything;
555
+ // `turn`, what the turn in hand has done; `talking`, that the model — not a `!` command — is what the screen is working on;
556
+ // `pick`, the job under the box that Down has stepped onto; `open`, the one whose record is shown.
557
+ st.current ??= { log: [], items: [], unmeasured: [], used: 0, next: 0, epoch: 0, raw: '', ed: editor(readHistory()), images: [], notice: null, queue: [], working: null, talking: false, tokens: 0, thought: '', heard: 0, running: new Map(), live: new Map(), drawSoon: null, jobs: new Map(), pick: null, open: null, asks: [], reply: null, fresh: true, leaving: null, gone: false, focused: true, title: null, turn: null, where: session.where(), spent: session.spent(), files: { cwd: null, at: 0, list: [] }, away: false };
558
+ const state = st.current;
559
+ state.columns = columns;
560
+ state.rows = rows;
561
+
562
+ const place = (items) => {
563
+ const placed = items.map((item) => ({ id: state.next++, ...item }));
564
+ state.items = [...state.items, ...placed];
565
+ state.unmeasured.push(...placed);
566
+ };
567
+ /**
568
+ * The rows what is finished takes on the screen since it was last cleared, counted until it fills the window: the room under it is
569
+ * 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.
570
+ */
571
+ const measure = () => {
572
+ for (const item of state.unmeasured.splice(0)) {
573
+ if (state.used < state.rows) state.used += renderToString(h(Item, { item, columns: state.columns }), { columns: state.columns }).split('\n').length;
574
+ }
575
+ };
576
+ const show = (items) => {
577
+ place(items);
578
+ measure();
579
+ redraw();
580
+ };
581
+ /** A renderer for a reply: each line it finishes goes on the screen, the first of a block with the mark. */
582
+ const replyTo = (put) =>
583
+ createRenderer(
584
+ (rendered) => {
585
+ put({ kind: 'text', text: rendered.replace(/\n$/, ''), first: state.fresh });
586
+ state.fresh = false;
587
+ },
588
+ s,
589
+ { width: state.columns - 3 },
590
+ );
591
+ /** One entry of the log as the lines this window shows for it. */
592
+ function drawn(entry) {
593
+ if (entry.kind === 'header') {
594
+ // The memory block is the model's; what is wrong in it is the user's to see.
595
+ const warnings = entry.block.split('\n').filter((line) => line.startsWith('Warning')).join('\n');
596
+ return [{ ...entry, block: warnings && renderBlock(warnings, s, { width: state.columns - 1 }) }];
597
+ }
598
+ if (entry.kind === 'tool') {
599
+ return [{ kind: 'tool', view: toolView(entry.call, entry.result, { cwd: state.where.cwd }), failed: entry.result.isError }];
600
+ }
601
+ // What the user's own command printed: drawn as a tool's output is, under the line they typed.
602
+ if (entry.kind === 'shell') return [{ kind: 'output', lines: toolView({ name: BASH_TOOL.name }, entry.result).lines }];
603
+ // A long message — a paste — is drawn by its top; all of it went to the model, and Ctrl-O shows it.
604
+ if (entry.kind === 'user') {
605
+ const lines = entry.text.split('\n');
606
+ if (lines.length > ECHO_LINES) return [{ ...entry, text: lines.slice(0, ECHO_LINES).join('\n'), more: lines.length - ECHO_LINES }];
607
+ }
608
+ if (entry.kind !== 'reply') return [entry];
609
+ const lines = [];
610
+ state.fresh = true;
611
+ const reply = replyTo((item) => lines.push(item));
612
+ reply.write(entry.raw);
613
+ reply.flush();
614
+ return lines;
615
+ }
616
+ const record = (entry) => {
617
+ state.log.push(entry);
618
+ show(drawn(entry));
619
+ };
620
+ if (state.log.length === 0) {
621
+ state.log.push(header(block));
622
+ // A chat opened on a saved session shows where it stopped and says which, under the header, where a fresh one shows the block's warnings.
623
+ if (opening) state.log.push(...replayOf(session.params.messages), { kind: 'note', text: opening });
624
+ for (const entry of state.log) place(drawn(entry));
625
+ }
626
+
627
+ /** The jobs at work with no call standing over them, by id: the ones under the box. */
628
+ const underBox = () => [...state.jobs].filter(([, job]) => !state.running.has(job.parent)).map(([id]) => id);
629
+ /** The rows under the box: the chat itself, then those jobs. None when no job is there: the chat alone needs no row. */
630
+ const rowsUnderBox = () => {
631
+ const jobs = underBox();
632
+ return jobs.length > 0 ? [MAIN, ...jobs] : [];
633
+ };
634
+ /** A job that has ended is no longer stepped on, nor open; nor is the chat's row once the last job is gone. */
635
+ const dropEnded = () => {
636
+ if (!rowsUnderBox().includes(state.pick)) state.pick = null;
637
+ if (!state.jobs.has(state.open)) state.open = null;
638
+ };
639
+
640
+ /** The reply so far is whole: its last line is drawn, it joins the log, and the next text starts a new block. */
641
+ const closeReply = () => {
642
+ state.reply?.flush();
643
+ if (state.raw) state.log.push({ kind: 'reply', raw: state.raw });
644
+ state.raw = '';
645
+ state.fresh = true;
646
+ };
647
+
648
+ /**
649
+ * Everything again, from the log, after the window changed size — the window and its scrollback wiped, since what they
650
+ * hold is drawn again. A session that starts over has nothing to draw again:
651
+ * `clear` then only scrolls the old one away, where it can still be read.
652
+ */
653
+ const refresh = (clear = CLEAR) => {
654
+ state.items = [];
655
+ state.unmeasured = [];
656
+ state.used = 0;
657
+ for (const entry of state.log) place(drawn(entry));
658
+ measure();
659
+ state.fresh = true;
660
+ if (state.working) {
661
+ state.reply = replyTo((item) => show([item]));
662
+ state.reply.write(state.raw);
663
+ }
664
+ state.epoch++;
665
+ write(clear);
666
+ redraw();
667
+ };
668
+
669
+ /** Straight to the terminal, for what draws nothing: the bell, the title. Ink's own writer would take it for a line of the screen. */
670
+ const tell = (sequence) => {
671
+ if (stdout.isTTY) stdout.write(sequence);
672
+ };
673
+
674
+ /** A bell and a notification, when the window is not the one in front: the turn is over, or it waits for an answer. */
675
+ const alert = (text) => {
676
+ if (alerts && !state.focused) tell(`\x1b]9;sumo — ${safeForTerminal(text).replace(/\s+/g, ' ')}\x07\x07`);
677
+ };
678
+
679
+ /** 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. */
680
+ const closeTurn = (began, before, ended) => {
681
+ const took = Date.now() - began;
682
+ state.spent = session.spent();
683
+ state.where = session.where();
684
+ const { calls, edited } = state.turn;
685
+ const files = [...edited];
686
+ const parts = [elapsed(took), calls > 0 ? `${calls} call${calls === 1 ? '' : 's'}` : '', files.length > 0 ? `edited ${files.slice(0, 3).join(', ')}${files.length > 3 ? ` +${files.length - 3} more` : ''}` : '', dollars(state.spent - before)];
687
+ if (calls > 0 || took >= notifyAfterMs) record({ kind: 'footer', text: parts.filter(Boolean).join(' · ') });
688
+ if (took >= notifyAfterMs) alert(`${state.where.name}: ${ended}`);
689
+ };
690
+
691
+ /** The way out. A turn in hand is stopped first and the screen closes when it has let go; nothing queued behind it is sent. */
692
+ const leave = () => {
693
+ state.gone = true;
694
+ state.queue = [];
695
+ if (state.working) session.interrupt();
696
+ else exit();
697
+ };
698
+
699
+ /** The user's answer to a call waiting on it; one answered already — by Esc, say — is left alone. */
700
+ const settle = (ask, answer) => {
701
+ if (!state.asks.includes(ask)) return;
702
+ state.asks = state.asks.filter((a) => a !== ask);
703
+ ask.resolve(answer);
704
+ redraw();
705
+ };
706
+
707
+ /** Said under the box for a moment, in place of the hints: why a key did nothing. */
708
+ const notify = (text) => {
709
+ clearTimeout(state.notice?.timer);
710
+ state.notice = {
711
+ text,
712
+ timer: setTimeout(() => {
713
+ state.notice = null;
714
+ redraw();
715
+ }, NOTICE_MS),
716
+ };
717
+ redraw();
718
+ };
719
+
720
+ /** A picture for the message being written: kept by its number, a marker for it where the cursor is. */
721
+ const attach = (image) => {
722
+ state.images.push(image);
723
+ state.ed = paste(state.ed, `[Image #${state.images.length}] `);
724
+ };
725
+
726
+ /** The pictures a line names, each once, in the order it names them; a marker deleted from the box took its picture with it. */
727
+ const picturesIn = (line) =>
728
+ [...new Set([...line.matchAll(/\[Image #(\d+)\]/g)].map((m) => Number(m[1])))]
729
+ .filter((n) => state.images[n - 1])
730
+ .map((n) => ({ label: `[Image #${n}]`, ...state.images[n - 1] }));
731
+
732
+ /** One thing the user sent, start to finish; whatever goes wrong inside is shown, never thrown at the terminal. */
733
+ async function turn(line, images) {
734
+ try {
735
+ // A session that starts over cannot take a job's report with it: the job is waited for, or stopped, first.
736
+ const { control: wanted, args: given } = line.startsWith('!') ? {} : session.expand(line);
737
+ if ((wanted === 'new' || (wanted === 'resume' && given)) && session.running().length > 0) {
738
+ record({ kind: 'user', text: line });
739
+ return record({ kind: 'error', text: `${session.running().map((id) => `j${id}`).join(', ')} still at work in the background — wait for the report, or /stop first` });
740
+ }
741
+ if (line.startsWith('!')) {
742
+ record({ kind: 'user', text: line });
743
+ state.working = pickMessage(messages);
744
+ redraw();
745
+ return record({ kind: 'shell', result: { content: await session.shell(line.slice(1).trim()), isError: false } });
746
+ }
747
+ const { text, said, guide, control, args, error } = session.expand(line);
748
+ if (error) return record({ kind: 'error', text: error });
749
+ if (control === 'quit') return leave();
750
+ if (control === 'new') {
751
+ session.end();
752
+ state.log = [];
753
+ // The old session's pictures go with it; their numbers stay taken, so a marker recalled from before names nothing.
754
+ state.images = state.images.map(() => null);
755
+ const block = session.start('new');
756
+ state.where = session.where();
757
+ state.spent = session.spent();
758
+ refresh(scrolledClear(state.rows));
759
+ return record(header(block));
760
+ }
761
+ if (control === 'resume') {
762
+ record({ kind: 'user', text: line });
763
+ if (!args) {
764
+ const saved = session.saved();
765
+ return record({ kind: 'note', text: saved.length > 0 ? saved.join('\n') : 'no saved sessions' });
766
+ }
767
+ // Refused — no such session, or one open elsewhere — nothing changes, and the refusal is shown below like any other error.
768
+ const said = session.resume(args);
769
+ state.log = [];
770
+ state.images = state.images.map(() => null);
771
+ state.where = session.where();
772
+ state.spent = session.spent();
773
+ refresh(scrolledClear(state.rows));
774
+ record(header(''));
775
+ // Where it stopped, drawn again: the last few turns, so what is picked up is in front of the user and not only the model.
776
+ for (const entry of replayOf(session.params.messages)) record(entry);
777
+ return record({ kind: 'note', text: said });
778
+ }
779
+ if (control === 'copy') {
780
+ record({ kind: 'user', text: line });
781
+ if (args && args !== 'code') return record({ kind: 'error', text: `/copy takes nothing, or "code" — not "${args}"` });
782
+ // The reply as the model wrote it, not as the screen drew it: no indent, no line broken to fit the window.
783
+ const replies = state.log.filter((entry) => entry.kind === 'reply' && !entry.own);
784
+ const blocks = replies.flatMap((entry) => [...entry.raw.matchAll(/^[ \t]*```[^\n]*\n([\s\S]*?)^[ \t]*```[ \t]*$/gm)].map((m) => m[1]));
785
+ const text = (args === 'code' ? blocks.at(-1) : replies.at(-1)?.raw)?.replace(/\n+$/, '');
786
+ if (!text) return record({ kind: 'error', text: args === 'code' ? 'no code block in the conversation yet' : 'no reply to copy yet' });
787
+ // Where no clipboard command takes it, the terminal is asked to (OSC 52).
788
+ const taken = await copy(text);
789
+ if (!taken) tell(`\x1b]52;c;${Buffer.from(text).toString('base64')}\x07`);
790
+ const lines = text.split('\n').length;
791
+ return record({ kind: 'note', text: `copied ${args === 'code' ? 'the last code block' : 'the last reply'} — ${lines} line${lines === 1 ? '' : 's'}${taken ? '' : ", through the terminal's clipboard"}` });
792
+ }
793
+ if (control === 'help') {
794
+ record({ kind: 'user', text: line });
795
+ return record({ kind: 'reply', raw: helpText(session.commands), own: true });
796
+ }
797
+ if (control === 'model' || control === 'memory' || control === 'mcp' || control === 'undo') {
798
+ record({ kind: 'user', text: line });
799
+ const text = control === 'model' ? session.route(args) : control === 'undo' ? session.undo() : control === 'mcp' ? (await session.mcp()).join('\n') : await session.memoryPage();
800
+ return record({ kind: 'note', text });
801
+ }
802
+ record({ kind: 'user', text: line });
803
+ await modelTurn(() => session.say(text, said, images, { guide }));
804
+ } catch (cause) {
805
+ closeReply();
806
+ record({ kind: 'error', text: `error: ${cause.message}` });
807
+ } finally {
808
+ endTurn();
809
+ }
810
+ }
811
+
812
+ /** The model at work, for a message or for a report: the working line, the reply as it comes, and the line the turn ends on. */
813
+ async function modelTurn(run) {
814
+ state.working = pickMessage(messages);
815
+ state.talking = true;
816
+ state.tokens = 0;
817
+ state.fresh = true;
818
+ state.heard = Date.now();
819
+ state.turn = { calls: 0, edited: new Set() };
820
+ state.reply = replyTo((item) => show([item]));
821
+ redraw();
822
+ const began = Date.now();
823
+ const before = session.spent();
824
+ let outcome;
825
+ try {
826
+ outcome = await run();
827
+ } catch (cause) {
828
+ closeReply();
829
+ record({ kind: 'error', text: `error: ${cause.message}` });
830
+ return closeTurn(began, before, 'stopped on an error');
831
+ }
832
+ closeReply();
833
+ // Nothing was waiting after all: no turn was run.
834
+ if (!outcome) return undefined;
835
+ if (outcome.stop === 'interrupted') record({ kind: 'note', text: 'Interrupted' });
836
+ if (outcome.stop === 'error') record({ kind: 'error', text: `error: ${outcome.error}` });
837
+ if (stopReason(outcome.stop)) record({ kind: 'note', text: stopReason(outcome.stop) });
838
+ return closeTurn(began, before, outcome.stop === 'error' ? 'stopped on an error' : outcome.stop === 'interrupted' ? 'interrupted' : 'done');
839
+ }
840
+
841
+ /** What every turn leaves behind it, however it ended. A job still at work in the background, and a question of its, are not the turn's to clear. */
842
+ function endTurn() {
843
+ const aside = session.running();
844
+ // A question the turn left standing has no call behind it any more.
845
+ for (const ask of state.asks.filter((a) => !aside.includes(a.job))) settle(ask, 'no');
846
+ state.running.clear();
847
+ state.live.clear();
848
+ for (const id of [...state.jobs.keys()]) if (!aside.includes(id)) state.jobs.delete(id);
849
+ dropEnded();
850
+ state.working = null;
851
+ state.talking = false;
852
+ state.thought = '';
853
+ redraw();
854
+ if (state.gone) exit();
855
+ }
856
+
857
+ /** A turn nobody typed: what the background jobs reported, read by the model as soon as it is free to. */
858
+ async function wakeTurn() {
859
+ try {
860
+ await modelTurn(() => session.wake());
861
+ } catch (cause) {
862
+ closeReply();
863
+ record({ kind: 'error', text: `error: ${cause.message}` });
864
+ } finally {
865
+ endTurn();
866
+ }
867
+ }
868
+
869
+ /** Once nothing is at work: what was typed meanwhile goes first, then what the background jobs reported. */
870
+ async function drain() {
871
+ while (!state.working && !state.gone) {
872
+ if (state.queue.length > 0) {
873
+ const next = state.queue.shift();
874
+ redraw();
875
+ await turn(next.line, next.images);
876
+ } else if (session.waiting() > 0) await wakeTurn();
877
+ else break;
878
+ }
879
+ }
880
+
881
+ /** `/stop`: a job at work in the background is stopped now, whatever else is going on — it is not a turn, and waits for none. */
882
+ function stopJob(line, given) {
883
+ record({ kind: 'user', text: line });
884
+ const ids = session.running();
885
+ if (ids.length === 0) return record({ kind: 'error', text: 'no job is at work in the background' });
886
+ const id = given ? Number(/^j?(\d+)$/.exec(given)?.[1]) : ids.length === 1 ? ids[0] : NaN;
887
+ if (!ids.includes(id)) return record({ kind: 'error', text: `which one — ${ids.map((j) => `/stop j${j}`).join(' or ')}` });
888
+ session.stop(id);
889
+ return record({ kind: 'note', text: `stopping j${id} — it can be picked up again: ask for it by its id` });
890
+ }
891
+
892
+ /** What was typed: now if nothing is running, after the turn in hand if something is. */
893
+ async function submit(line) {
894
+ keepHistory(line);
895
+ const asked = line.startsWith('/') ? session.expand(line) : {};
896
+ if (asked.control === 'stop') return stopJob(line, asked.args);
897
+ // For a job, not for the chat: `@j31 …` reaches that job wherever it runs, a bare `@…` the one running here.
898
+ // A job that cannot be told anything — closed by now, or never there — is said back, whichever way it was named.
899
+ // With a job's record open, that job is the one a bare `@…` means.
900
+ const named = /^@j?(\d+)\s+(\S[\s\S]*)$/.exec(line);
901
+ const said = named ? named[2].trim() : state.jobs.size > 0 && line.startsWith('@') ? line.slice(1).trim() : '';
902
+ if (said) {
903
+ // A job is told words only; a picture would be dropped without a word.
904
+ if (picturesIn(said).length > 0) return record({ kind: 'error', text: 'a job is told words only — send the picture to the chat, without the @' });
905
+ try {
906
+ const told = named ? session.tell(said, Number(named[1])) : session.tell(said, state.open);
907
+ if (told) return record({ kind: 'user', text: `@j${told} ${said}` });
908
+ } catch (cause) {
909
+ return record({ kind: 'error', text: cause.message });
910
+ }
911
+ }
912
+ const images = picturesIn(line);
913
+ if (state.working) {
914
+ // Words for the model at work are read with its next request, in this turn; a command, a picture, or anything typed
915
+ // while a `!` command runs waits for the turn to end. Either way it stands above the box until it is read or sent.
916
+ const steer = state.talking && images.length === 0 && !/^[/!]/.test(line);
917
+ if (steer) session.steer(line);
918
+ state.queue.push({ line, images, steer });
919
+ return redraw();
920
+ }
921
+ await turn(line, images);
922
+ await drain();
923
+ }
924
+
925
+ /**
926
+ * The files a mention could mean, from the project the tools run in. The list is git's, fetched when a file is first
927
+ * named and again once it has gone stale; until it has come, nothing is offered. At the start of the line `@` is the
928
+ * way to a job at work, so no file is offered there while one is.
929
+ */
930
+ const files = (query, from) => {
931
+ if (from === 0 && state.jobs.size > 0) return [];
932
+ const at = state.where.cwd;
933
+ if (state.files.cwd !== at || Date.now() - state.files.at > FILES_FRESH_MS) {
934
+ state.files = { cwd: at, at: Date.now(), list: state.files.cwd === at ? state.files.list : [] };
935
+ listFiles(at).then((list) => {
936
+ if (state.files.cwd !== at) return;
937
+ state.files.list = list;
938
+ redraw();
939
+ });
940
+ }
941
+ return matchFiles(state.files.list, query);
942
+ };
943
+
944
+ /**
945
+ * The terminal handed to a program of the user's — their editor, their pager — until it exits: the screen stops
946
+ * drawing and stops reading keys, the work behind it goes on, and everything is drawn again when the program is done.
947
+ */
948
+ const handOver = async (program, file, what) => {
949
+ if (state.away) return false;
950
+ state.away = true;
951
+ try {
952
+ tell(FOCUS_OFF);
953
+ await suspendTerminal(async () => {
954
+ // On a screen of its own: an editor or a pager that has one uses it anyway, and one that has none leaves nothing behind in the conversation.
955
+ tell(`${SCREEN_ASIDE}\x1b[2m${what} (${program.split(' ')[0].split('/').at(-1)}) has the terminal — the chat is back when it closes\x1b[22m\r\n`);
956
+ try {
957
+ await run(program, file);
958
+ } finally {
959
+ tell(SCREEN_BACK);
960
+ }
961
+ });
962
+ return true;
963
+ } catch (cause) {
964
+ notify(`${what} could not be opened: ${cause.message}`);
965
+ return false;
966
+ } finally {
967
+ tell(FOCUS_ON);
968
+ state.away = false;
969
+ redraw();
970
+ }
971
+ };
972
+
973
+ /** Ctrl-G: the message in the box, written in the user's editor; what is saved there is what the box holds after. */
974
+ const openEditor = async () => {
975
+ const file = join(paths().home, `message-${process.pid}.md`);
976
+ try {
977
+ mkdirSync(paths().home, { recursive: true, mode: 0o700 });
978
+ writeFileSync(file, state.ed.text, { mode: 0o600 });
979
+ if (!(await handOver(process.env.VISUAL || process.env.EDITOR || 'vi', file, 'the editor'))) return;
980
+ const text = readFileSync(file, 'utf8').replace(/\r\n?/g, '\n').replace(/\n+$/, '');
981
+ state.ed = { ...editor(state.ed.history), text, cursor: text.length };
982
+ } catch (cause) {
983
+ notify(cause.message);
984
+ } finally {
985
+ rmSync(file, { force: true });
986
+ redraw();
987
+ }
988
+ };
989
+
990
+ /**
991
+ * Ctrl-O: the whole conversation in the user's pager — every command, all its output, each file read or written —
992
+ * to scroll and to search. With a job's record open, it is all of that record. Nothing on the screen is wiped or drawn
993
+ * again for it: the pager has a screen of its own.
994
+ */
995
+ const openPager = async () => {
996
+ const file = join(paths().logs, `conversation-${process.pid}.txt`);
997
+ try {
998
+ mkdirSync(paths().logs, { recursive: true, mode: 0o700 });
999
+ const live = state.raw ? [{ kind: 'reply', raw: state.raw }] : [];
1000
+ // What a job wrote is shown, never obeyed: its record goes to the pager as it goes to the screen.
1001
+ const text = state.open === null ? transcript([...state.log, ...live], s, { width: state.columns, cwd: state.where.cwd }) : safeForTerminal(readFileSync(liveFile(state.open), 'utf8'));
1002
+ writeFileSync(file, text, { mode: 0o600 });
1003
+ // Opened at its end: what was asked about is nearly always the last thing that happened.
1004
+ await handOver(process.env.PAGER || 'less -R +G', file, 'the pager');
1005
+ } catch (cause) {
1006
+ notify(cause.message);
1007
+ } finally {
1008
+ rmSync(file, { force: true });
1009
+ }
1010
+ };
1011
+
1012
+ /** What is waiting — to be read at the next step, or sent after the turn — back in the box, ahead of what is typed there; the model reads none of it. */
1013
+ const takeBack = (entries) => {
1014
+ for (const entry of entries) if (entry.steer) session.unsteer(entry.line);
1015
+ state.queue = state.queue.filter((entry) => !entries.includes(entry));
1016
+ const text = [...entries.map((entry) => entry.line), state.ed.text].filter(Boolean).join('\n');
1017
+ state.ed = { ...editor(state.ed.history), text, cursor: text.length };
1018
+ };
1019
+
1020
+ useEffect(() => {
1021
+ const onText = (chunk) => {
1022
+ state.heard = Date.now();
1023
+ // The reply has begun: what was thought before it is no longer the news.
1024
+ state.thought = '';
1025
+ state.raw += chunk;
1026
+ state.reply?.write(chunk);
1027
+ redraw();
1028
+ };
1029
+ // What the model is thinking, so far: shown under the working line until it acts. A job's thought is its own: it is not drawn here.
1030
+ const onThinking = ({ text, job }) => {
1031
+ if (job) return;
1032
+ state.thought = text;
1033
+ state.heard = Date.now();
1034
+ redraw();
1035
+ };
1036
+ // A request being sent again, or a job's conversation summarized to make room: said where the work shows, with the job's id.
1037
+ const onRetry = (r) => record({ kind: 'note', text: `${r.job ? `j${r.job}: ` : ''}${retryLine(r)}` });
1038
+ const onCompact = (c) => record({ kind: 'note', text: `${c.job ? `j${c.job}: ` : ''}${compactLine(c)}` });
1039
+ // The session has passed what it may cost before it is said: said once, where the retries are.
1040
+ const onBudget = ({ text }) => record({ kind: 'note', text });
1041
+ const onTool = ({ call, job }) => {
1042
+ const at = state.jobs.get(job);
1043
+ if (at) at.calls++;
1044
+ else if (!job) {
1045
+ state.thought = '';
1046
+ closeReply();
1047
+ state.running.set(call.id, call);
1048
+ state.live.set(call.id, { since: Date.now(), out: '', cut: false });
1049
+ if (state.turn) state.turn.calls++;
1050
+ // A project named in this turn has moved the work: the paths drawn from here on are read from it.
1051
+ state.where = session.where();
1052
+ }
1053
+ redraw();
1054
+ };
1055
+ // What a running command prints, as it prints it: the end of it is kept, and drawn a few times a second at most.
1056
+ const onOutput = ({ call, chunk }) => {
1057
+ const live = state.live.get(call.id);
1058
+ if (!live) return;
1059
+ const out = live.out + chunk;
1060
+ live.cut ||= out.length > LIVE_KEPT_CHARS;
1061
+ live.out = out.slice(-LIVE_KEPT_CHARS);
1062
+ state.drawSoon ??= setTimeout(() => {
1063
+ state.drawSoon = null;
1064
+ redraw();
1065
+ }, LIVE_DRAW_MS);
1066
+ };
1067
+ // What was typed while the model worked, read by it now: it leaves the line above the box and joins the conversation.
1068
+ const onHeard = ({ said }) => {
1069
+ closeReply();
1070
+ for (const text of said) {
1071
+ const at = state.queue.findIndex((entry) => entry.steer && entry.line === text);
1072
+ if (at !== -1) state.queue.splice(at, 1);
1073
+ record({ kind: 'user', text });
1074
+ }
1075
+ };
1076
+ // What the model was handed without being asked: a way of working, or the check it stopped short of.
1077
+ const onGuide = ({ name }) => {
1078
+ closeReply();
1079
+ record({ kind: 'note', text: `guide: ${name}` });
1080
+ };
1081
+ // The pages a reply cites, under it. A title is a page's own words: nothing in it may drive the terminal.
1082
+ const onSources = ({ sources }) => {
1083
+ closeReply();
1084
+ record({ kind: 'note', text: `sources:\n${sources.map((page) => safeForTerminal(`${page.title} — ${page.url}`).replace(/\s+/g, ' ')).join('\n')}` });
1085
+ };
1086
+ const onCheck = ({ edited, checks }) => {
1087
+ closeReply();
1088
+ record({ kind: 'note', text: `held: ${edited.length} file${edited.length === 1 ? '' : 's'} edited, ${checks.length > 0 ? `${checks.join(' and ')} not run` : 'no check declared'}` });
1089
+ };
1090
+ // A job's work is not the chat's: it shows one line while it works, its report when it ends, and the rest where it is watched.
1091
+ const onResult = ({ call, result, job }) => {
1092
+ if (job) return;
1093
+ // Delegated jobs run side by side: one ending leaves the others' calls on the screen.
1094
+ state.running.delete(call.id);
1095
+ state.live.delete(call.id);
1096
+ state.heard = Date.now();
1097
+ if (state.turn && call.name === EDITOR_TOOL.name && call.input?.command !== 'view' && !result.isError) state.turn.edited.add(pathFrom(call.input?.path ?? '', state.where.cwd));
1098
+ record({ kind: 'tool', call, result });
1099
+ };
1100
+ const onJob = ({ job, call = null, tab = null }) => {
1101
+ state.jobs.set(job.id, { parent: call, calls: 0, since: Date.now(), agent: job.agent, title: job.title, route: routeOf(job) });
1102
+ const where = tab?.pane ? 'working in its Herdr tab' : tab?.error ? `no Herdr tab (${tab.error}) — sumo job watch ${job.id}` : `follow it: sumo job watch ${job.id}`;
1103
+ record({ kind: 'job', id: job.id, agent: job.agent, title: job.title, route: routeOf(job), where });
1104
+ };
1105
+ // A job in the background has reported: how it went is drawn where the conversation has got to, and the model reads the
1106
+ // report with its next request — or, when nothing is at work, in a turn started here for it. One the user stopped starts none.
1107
+ const onJobReport = ({ job, result }) => {
1108
+ record({ kind: 'tool', call: { id: `report-${job}`, name: DELEGATE_TOOL.name, input: { job } }, result });
1109
+ alert(`${state.where.name}: j${job} has reported`);
1110
+ if (!state.working) drain();
1111
+ };
1112
+ // The tab said to show the job stayed empty: why, and how to follow it all the same.
1113
+ const onTabFailed = ({ job, reason }) => record({ kind: 'error', text: `j${job}: ${reason} — follow it here: sumo job watch ${job}` });
1114
+ const onJobEnd = ({ job }) => {
1115
+ state.jobs.delete(job);
1116
+ dropEnded();
1117
+ redraw();
1118
+ };
1119
+ const onUsage = ({ totals }) => {
1120
+ state.tokens = totals.outputTokens;
1121
+ state.heard = Date.now();
1122
+ state.spent = session.spent();
1123
+ redraw();
1124
+ };
1125
+ // A call waiting on the user's word: shown under the work until a key answers it; Esc stops the turn, which declines it.
1126
+ const onApprove = (ask) => {
1127
+ state.asks.push(ask);
1128
+ ask.signal?.addEventListener('abort', () => settle(ask, 'no'), { once: true });
1129
+ alert(`${state.where.name}: ${ask.unsandboxed ? 'a command waits to run outside the sandbox' : `${ask.server} · ${ask.tool} waits for your answer`}`);
1130
+ redraw();
1131
+ };
1132
+ // A question of the model's: shown with its options, the first one picked, until a pick or a typed answer settles it.
1133
+ const onAsk = (ask) => {
1134
+ const standing = { ...ask, at: 0 };
1135
+ state.asks.push(standing);
1136
+ ask.signal?.addEventListener('abort', () => settle(standing, 'no'), { once: true });
1137
+ alert(`${state.where.name}: a question waits for your answer`);
1138
+ redraw();
1139
+ };
1140
+ // An MCP server that is not there is the user's to see; the model is simply not offered its tools.
1141
+ const onMcp = ({ servers, error }) => {
1142
+ if (error) record({ kind: 'error', text: `mcp: ${error}` });
1143
+ for (const server of servers.filter((s) => !s.ok)) record({ kind: 'error', text: `mcp ${server.name}: ${server.error} — sumo mcp shows every server` });
1144
+ };
1145
+ 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);
1146
+ return () => {
1147
+ events.off('text', onText).off('thinking', onThinking).off('retry', onRetry).off('compact', onCompact).off('budget', onBudget).off('tool', onTool).off('output', onOutput).off('heard', onHeard).off('guide', onGuide).off('sources', onSources).off('check', onCheck).off('result', onResult).off('usage', onUsage).off('job', onJob).off('tab-failed', onTabFailed).off('job-end', onJobEnd).off('job-report', onJobReport).off('approve', onApprove).off('ask', onAsk).off('mcp', onMcp);
1148
+ clearTimeout(state.leaving);
1149
+ clearTimeout(state.notice?.timer);
1150
+ clearTimeout(state.drawSoon);
1151
+ // The terminal as it was found: no more word of its focus, and its own title back.
1152
+ tell(`${FOCUS_OFF}${TITLE_BACK}`);
1153
+ };
1154
+ }, []);
1155
+
1156
+ // The window's title says whose chat it is and what it is doing, for a glance at the tab bar: at work, or waiting for an answer.
1157
+ useEffect(() => {
1158
+ const title = `${state.asks.length > 0 ? '? ' : state.working ? '✳ ' : ''}sumo · ${state.where.name}`;
1159
+ if (title === state.title) return;
1160
+ state.title = title;
1161
+ tell(`\x1b]2;${safeForTerminal(title)}\x07`);
1162
+ });
1163
+
1164
+ // The opening header was placed while the first frame was drawn; it is measured once that frame is down — and outside React, which an effect is not.
1165
+ useEffect(() => {
1166
+ const later = setTimeout(() => {
1167
+ measure();
1168
+ redraw();
1169
+ });
1170
+ return () => clearTimeout(later);
1171
+ }, []);
1172
+
1173
+ // A window dragged to a new size: once it has stopped moving, everything is drawn again to fit it.
1174
+ const sized = useRef(`${columns}x${rows}`);
1175
+ useEffect(() => {
1176
+ if (sized.current === `${columns}x${rows}`) return undefined;
1177
+ const settle = setTimeout(() => {
1178
+ sized.current = `${columns}x${rows}`;
1179
+ refresh();
1180
+ }, RESIZE_SETTLE_MS);
1181
+ return () => clearTimeout(settle);
1182
+ }, [columns, rows]);
1183
+
1184
+ useInput((input, key) => {
1185
+ // The terminal's answer to Ink's keyboard-protocol query, when it comes after Ink stopped waiting for it.
1186
+ if (/^\[\?\d+u$/.test(input)) return;
1187
+ // The terminal saying its window came to the front, or went behind: not something typed.
1188
+ if (input === '[I' || input === '[O') {
1189
+ state.focused = input === '[I';
1190
+ return;
1191
+ }
1192
+ for (const [one, oneKey] of keysOf(input, key)) {
1193
+ // A question of the model's: on an empty box the arrows move the pick and Enter takes it. Anything else is the box's,
1194
+ // and Enter there sends what was typed as the answer; Esc and Ctrl-C go on to stop the turn.
1195
+ const asked = state.asks[0]?.options ? state.asks[0] : null;
1196
+ if (asked && !state.ed.text && (oneKey.upArrow || oneKey.downArrow || (oneKey.return && !oneKey.shift && !oneKey.meta))) {
1197
+ if (oneKey.return) settle(asked, { label: asked.options[asked.at].label });
1198
+ else asked.at = Math.max(0, Math.min(asked.options.length - 1, asked.at + (oneKey.downArrow ? 1 : -1)));
1199
+ continue;
1200
+ }
1201
+ // A call standing takes the key: an answer, or Esc and Ctrl-C, which go on to stop the turn; nothing lands in the box.
1202
+ if (!asked && state.asks.length > 0 && !oneKey.escape && !(oneKey.ctrl && (one === 'c' || one === 'd'))) {
1203
+ // A run outside the sandbox is this one run or none: there is no always for it.
1204
+ const unsandboxed = state.asks[0].unsandboxed;
1205
+ const answer = (unsandboxed ? { y: 'once', n: 'no' } : { y: 'once', a: 'always', n: 'no' })[one];
1206
+ if (answer) settle(state.asks[0], answer);
1207
+ else notify(unsandboxed ? 'y runs it once outside the sandbox · n refuses it · esc stops the turn' : 'y allows it once · a always · n refuses it · esc stops the turn');
1208
+ continue;
1209
+ }
1210
+ // A question from a job in the background: Esc refuses that one call, and stops nothing.
1211
+ if (oneKey.escape && state.asks.length > 0 && session.running().includes(state.asks[0].job)) {
1212
+ settle(state.asks[0], 'no');
1213
+ continue;
1214
+ }
1215
+ // The rows under the box — the chat itself, then its jobs: Down past the box's last line steps onto them, and Up back off
1216
+ // them; Enter opens the job stepped on, or on the chat's row comes back to the chat. Esc steps off, and then closes the
1217
+ // record that is open — both before it stops a turn. Any other key is the box's.
1218
+ const listed = rowsUnderBox();
1219
+ if (state.pick !== null) {
1220
+ const at = listed.indexOf(state.pick);
1221
+ const to = oneKey.downArrow ? listed[Math.min(at + 1, listed.length - 1)] : oneKey.upArrow && at > 0 ? listed[at - 1] : null;
1222
+ if (oneKey.return) state.open = state.pick === MAIN ? null : state.pick;
1223
+ state.pick = to ?? null;
1224
+ if (oneKey.downArrow || oneKey.upArrow || oneKey.return || oneKey.escape) continue;
1225
+ } else if (oneKey.escape && state.open !== null && menuOf(state.ed, session.commands, files).length === 0) {
1226
+ state.open = null;
1227
+ continue;
1228
+ }
1229
+ if (oneKey.escape || (oneKey.ctrl && one === 'c')) {
1230
+ // What is nearest goes first: Ctrl-C clears what is typed, Esc closes the menu, and only then is the turn stopped.
1231
+ // A menu of files is shut without a word of the message lost; a command half typed is all there is to lose.
1232
+ const open = oneKey.escape ? menuOf(state.ed, session.commands, files) : [];
1233
+ if (oneKey.ctrl && state.ed.text) state.ed = editor(state.ed.history);
1234
+ else if (open.length > 0) state.ed = open[0].file ? { ...state.ed, shut: state.ed.text } : editor(state.ed.history);
1235
+ else if (state.working) {
1236
+ // Stopping the turn stops what was waiting on it too: it comes back to the box, to be sent again or not.
1237
+ takeBack([...state.queue]);
1238
+ session.interrupt();
1239
+ } else if (oneKey.escape) continue;
1240
+ else if (state.leaving) leave();
1241
+ else {
1242
+ state.leaving = setTimeout(() => {
1243
+ state.leaving = null;
1244
+ redraw();
1245
+ }, LEAVE_WINDOW_MS);
1246
+ }
1247
+ continue;
1248
+ }
1249
+ if (oneKey.ctrl && one === 'd' && !state.ed.text) {
1250
+ leave();
1251
+ continue;
1252
+ }
1253
+ if (oneKey.ctrl && one === 'o') {
1254
+ openPager();
1255
+ continue;
1256
+ }
1257
+ if (oneKey.ctrl && one === 'g') {
1258
+ openEditor();
1259
+ continue;
1260
+ }
1261
+ // Cmd-V pastes only text from a terminal; an image on the clipboard is fetched here.
1262
+ if (oneKey.ctrl && one === 'v') {
1263
+ clipboard()
1264
+ .then((image) => {
1265
+ if (!image) return notify('no image on the clipboard');
1266
+ attach(image);
1267
+ redraw();
1268
+ })
1269
+ .catch((cause) => notify(cause.message));
1270
+ continue;
1271
+ }
1272
+ // Up on an empty box takes back the last thing waiting, before the model reads it or the turn's end sends it.
1273
+ if (oneKey.upArrow && !state.ed.text && state.queue.length > 0) {
1274
+ takeBack([state.queue.at(-1)]);
1275
+ continue;
1276
+ }
1277
+ const pressed = press(state.ed, one, oneKey, session.commands, files);
1278
+ // Down that moved nothing — the last line of the text, nothing newer to recall — has left the box for the jobs under it.
1279
+ // 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.
1280
+ if (oneKey.downArrow && pressed.state === state.ed && listed.length > 0) state.pick = state.open === null ? listed[1] : MAIN;
1281
+ state.ed = pressed.state;
1282
+ if (pressed.submit !== undefined && asked) settle(asked, { text: pressed.submit });
1283
+ else if (pressed.submit !== undefined) submit(pressed.submit);
1284
+ }
1285
+ redraw();
1286
+ });
1287
+ // A file dropped on the terminal arrives pasted as its path: an image's path becomes the image.
1288
+ usePaste((text) => {
1289
+ let images;
1290
+ try {
1291
+ images = droppedImages(text);
1292
+ } catch (cause) {
1293
+ return notify(cause.message);
1294
+ }
1295
+ if (images) for (const image of images) attach(image);
1296
+ else state.ed = paste(state.ed, text);
1297
+ redraw();
1298
+ });
1299
+
1300
+ const menu = menuOf(state.ed, session.commands, files);
1301
+ const tail = state.reply?.tail ?? '';
1302
+ // The jobs the turn waits on: the ones whose call is still out. A job in the background holds nothing up.
1303
+ const atWork = [...state.jobs].filter(([, job]) => state.running.has(job.parent)).map(([id]) => `j${id}`);
1304
+ const reading = atWork.length === 0 ? 'next step' : `when ${atWork.join(', ')} report${atWork.length === 1 ? 's' : ''}`;
1305
+ // Ink adds a line under the frame; a frame that reached the last row would be drawn as a full screen.
1306
+ const room = state.unmeasured.length > 0 ? 0 : Math.max(0, rows - state.used - 1);
1307
+ return h(
1308
+ Box,
1309
+ { flexDirection: 'column', minHeight: room },
1310
+ h(Static, { key: state.epoch, items: state.items }, (item) => h(Item, { key: item.id, item, columns })),
1311
+ tail ? h(Reply, { text: tail, first: state.fresh }) : null,
1312
+ // What runs now, and under a delegate call the jobs it started. In one box of their own, so the lines coming and going
1313
+ // never move what follows — the working line keeps its clock.
1314
+ h(
1315
+ Box,
1316
+ { flexDirection: 'column' },
1317
+ ...[...state.running.values()].map((call) => h(Tool, { key: call.id, columns, view: toolView(call, null, { cwd: state.where.cwd }), running: true, live: state.live.get(call.id), jobs: [...state.jobs].filter(([, job]) => job.parent === call.id) })),
1318
+ // A job no call here started — none should be — still shows that it works.
1319
+ ),
1320
+ // The silence that is said is the model's: while a command, a job or a question is in hand, the wait is not on it.
1321
+ state.working ? h(Working, { messages, first: state.working, tokens: state.tokens, thought: state.thought, quietAfterMs, heard: state.talking && state.running.size === 0 && state.jobs.size === 0 && state.asks.length === 0 ? state.heard : 0 }) : null,
1322
+ state.asks.length > 0 ? (state.asks[0].options ? h(Question, { ask: state.asks[0] }) : h(Ask, { ask: state.asks[0], aside: session.running().includes(state.asks[0].job) })) : null,
1323
+ // The record of the job that is open, under everything the turn is doing: its end, as it grows.
1324
+ state.open !== null ? h(JobOpen, { id: state.open, job: state.jobs.get(state.open), rows }) : null,
1325
+ // The logo is the empty room's: once something has been said, the room is the conversation's.
1326
+ h(Room, { logo: state.log.some((entry) => entry.kind === 'user') ? [] : logo, rows, from: state.used }),
1327
+ h(
1328
+ Box,
1329
+ { flexDirection: 'column', marginTop: 1 },
1330
+ // A message for the model is read with its next request — which, while it waits on a delegated job, is when that job reports.
1331
+ ...state.queue.map(({ line, steer }, i) => h(Text, { key: i, dimColor: true, wrap: 'truncate' }, ` ${steer ? reading : 'queued'}: ${line.split('\n')[0]}${line.includes('\n') ? ' …' : ''}`)),
1332
+ h(Input, { state: state.ed, width: columns, rows }),
1333
+ // The jobs at work in the background, under the box, and the chat over them: they go on whether or not there is a turn.
1334
+ ...rowsUnderBox().map((id) => (id === MAIN ? h(MainAtWork, { key: MAIN, working: Boolean(state.working), picked: state.pick === MAIN, shown: state.open === null }) : h(JobAtWork, { key: `j${id}`, id, job: state.jobs.get(id), alone: true, picked: id === state.pick, open: id === state.open }))),
1335
+ menu.length > 0 ? h(Menu, { menu, pick: state.ed.pick }) : h(Status, { session, leaving: Boolean(state.leaving), notice: state.notice?.text, jobs: [...state.jobs.keys()], aside: session.running(), pick: state.pick, open: state.open, where: state.where, spent: state.spent, waiting: state.queue.length > 0, columns }),
1336
+ ),
1337
+ );
1338
+ }
1339
+
1340
+ /** Starts the session and draws it. The returned instance's `waitUntilExit()` settles when the user leaves. */
1341
+ export function runUi({ session, events, resume = null, stdin = process.stdin, stdout = process.stdout, messages = spinnerMessages(), cwd = process.cwd(), logo = logoLines(), clipboard = clipboardImage, copy = copyText, notify = true, notifyAfterMs = NOTIFY_AFTER_MS, quietAfterMs = QUIET_AFTER_MS, run = inTerminal, listFiles = gitFiles, debug = false }) {
1342
+ // Opened on a saved session (`sumo chat --resume`), the chat picks it up before the screen is drawn; a fresh one starts and is shown its block.
1343
+ const opening = resume === null ? null : session.resume(resume);
1344
+ const block = opening ? '' : session.start('startup');
1345
+ // Ink asks the terminal whether it speaks the kitty keyboard protocol before the screen turns raw mode on. In cooked
1346
+ // mode the terminal's answer is echoed and held back until a newline — and lands in the box as `[?0u`. Raw mode first.
1347
+ if (stdin.isTTY) stdin.setRawMode(true);
1348
+ // The chat starts at the top of a clear window, not under the shell line that started it: the room and the box are placed from its top.
1349
+ // What the window showed is scrolled up, not wiped: the terminal's scrollback from before the chat is still there to read.
1350
+ if (stdout.isTTY) stdout.write(scrolledClear(stdout.rows || 24));
1351
+ if (stdout.isTTY) stdout.write(`${TITLE_KEEP}${FOCUS_ON}`);
1352
+ // While Ink waits for that answer — a fifth of a second, on a terminal that gives none — it keeps what is typed and, when
1353
+ // it stops waiting, puts it back on the stream "so it isn't lost". But those keys were read as they came, and put back
1354
+ // they are read again: a letter typed just as the chat opens landed twice. For as long as Ink waits, nothing is put back.
1355
+ if (stdin.isTTY && typeof stdin.unshift === 'function') {
1356
+ const putBack = stdin.unshift;
1357
+ stdin.unshift = () => {};
1358
+ setTimeout(() => {
1359
+ stdin.unshift = putBack;
1360
+ }, KITTY_WAIT_MS).unref();
1361
+ }
1362
+ return render(h(App, { session, events, messages, cwd, block, opening, logo, clipboard, copy, notify, notifyAfterMs, quietAfterMs, run, listFiles }), { stdin, stdout, debug, exitOnCtrlC: false, kittyKeyboard: { mode: 'auto' } });
1363
+ }