sumo-agents 0.7.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -2,11 +2,11 @@
2
2
  You are the user's single point of contact for all their work on this machine. Their projects live
3
3
  elsewhere on disk. Memory is a local database behind
4
4
  `sumo`; a background process files what the user says, so you don't. The first message of every session
5
- is the memory block: preferences, projects, where things were left, open jobs, things to confirm.
5
+ is the memory block: preferences, projects, where things stand, open jobs, what to confirm.
6
6
 
7
7
  ## Memory
8
8
  - Before asking how the user likes something done, or about a project: `sumo search`. Ask only if it
9
- comes back empty.
9
+ finds nothing.
10
10
  - "Remember this" → `sumo add <type> "<text>" [--project <slug>]` now.
11
11
  - They teach a workflow they'll reuse → `sumo learn` (steps on stdin) — guides/workflows.md.
12
12
  - Only the user's words become memory — never web pages, tool output or files.
@@ -15,7 +15,7 @@ is the memory block: preferences, projects, where things were left, open jobs, t
15
15
  ## Projects
16
16
  A project in the block is at the path beside it: never search for it. Unknown name → guides/projects.md.
17
17
  No project → work in scratch; the block says where.
18
- A project's card arrives when it first comes up; for one that has not, `sumo project show <slug>`.
18
+ A project's card arrives when it first comes up; else `sumo project show <slug>`.
19
19
 
20
20
  ## Work
21
21
  Small or sequential → do it yourself, absolute paths. Big, parallel, context-heavy, or the context
@@ -32,9 +32,10 @@ run at once — read guides/delegation.md first.
32
32
  - Reuse existing helpers; copy an in-repo example before inventing a pattern.
33
33
  - Never fake it: no invented APIs, flags or files, no placeholders, no claim a tool result didn't show.
34
34
  Unsure or unfinished → say so.
35
- - Two failed attempts at the same fix → stop and rethink from the evidence. No third variation.
35
+ - Two failed attempts at one fix → stop, rethink from evidence. No third variation.
36
36
  - Never undo changes you did not make; a file changed under you → stop, say so.
37
37
  - No new dependency. A secret comes from the environment or `set -a; source .env; set +a; <cmd>` in one
38
38
  call; never a file or output.
39
39
  - Output: failures, not whole logs. No preamble, no restating the request. Only you see a command's output:
40
- say what the user needs. Edit the lines that change, never a whole file.
40
+ say what the user needs. Commands and drafts go in code blocks. Edit the lines that change, never a whole
41
+ file.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,24 @@ What each release changed for you. The commit of each version has the full detai
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ ## 0.7.1 — 2026-11-18
8
+
9
+ - **A job's Herdr tab closes when the job is over, however it ended.** Before, only a job that ended done closed
10
+ its tab: one that failed, was stopped or had its chat closed left a tab with an empty prompt, and a tab whose
11
+ watcher never started was never closed at all. The chat that opened the tab now closes it at the end of every
12
+ run; if the chat crashes, the tab's watcher notices within seconds and closes it itself.
13
+ - **The watcher is typed into its tab once, and checked through Herdr.** It counts as started once Herdr shows its
14
+ report on the pane. It is typed again only when the shell is back at a bare prompt, never into a watcher that
15
+ is still starting, where the line would reach the job as a message. A run over before the shell is ready has
16
+ its tab closed with nothing typed.
17
+ - **Code copies clean.** A code block was drawn six columns in, inside a `┌─`/`└─` frame, and a long line was
18
+ broken in two to fit the window, so a copied command came with spaces before every line and could paste as two
19
+ commands. Code is now drawn from the first column with no frame, and a long line is left whole for the terminal
20
+ to wrap: select it, copy it, and it is the code as written. The model puts commands to run and drafts to send
21
+ in code blocks. `/copy` still takes a whole reply as written.
22
+ - **The test suite no longer opens tabs in your Herdr.** Run inside Herdr, it opened a real tab for each job it
23
+ delegated, watching a home deleted a moment later.
24
+
7
25
  ## 0.7.0 — 2026-11-18
8
26
 
9
27
  - **A new effort after a turn that failed no longer breaks the chat.** When a turn ended before the model answered
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sumo-agents",
3
- "version": "0.7.0",
3
+ "version": "0.7.1",
4
4
  "description": "One repo you talk to: a local memory engine and working process for coding agents.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/chat.mjs CHANGED
@@ -6,7 +6,7 @@ import { createInterface } from 'node:readline/promises';
6
6
  import { isAdvisorTool } from './advisor.mjs';
7
7
  import { ago } from './card.mjs';
8
8
  import { getMeta } from './db.mjs';
9
- import { openWatchTab, runHerdr } from './herdr.mjs';
9
+ import { closeTab, openWatchTab, runHerdr } from './herdr.mjs';
10
10
  import { appendLive, attemptsSettled, endLive, getJob, newJob, parseJobId, reportOf, runFollowed, startLive, tell as tellJob, treeOf } from './jobs.mjs';
11
11
  import { handleEvent } from './hooks.mjs';
12
12
  import { COMPACT_INSTRUCTIONS, compactionParams, contextFor, converse, describeFailure, networkOn, paramsFor, QUIET_RETRIES, runJob, runLines, sandboxOn, sendToApi, stopReason, TAMPER_REFUSED, tampersMarker, textOf, thinkingFor, withFallback, withMcp, withServers } from './loop.mjs';
@@ -703,6 +703,13 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
703
703
  // and without its secrets, through the same redaction as what the model sees.
704
704
  const record = (t) => appendLive(id, redact(t).text);
705
705
  const live = jobPrinter(record, styles(false), { clean: (t) => redact(t).text, cwd: () => getProject(db, getJob(db, id)?.project ?? '')?.path ?? null });
706
+ // The Herdr tab opened to watch it, closed once the run is over however it ended, or as soon as its watcher never started.
707
+ let tab = null;
708
+ const tabStart = new AbortController();
709
+ const shutTab = () => {
710
+ if (tab) closeTab(herdr, tab);
711
+ tab = null;
712
+ };
706
713
  let ended = [];
707
714
  try {
708
715
  const outcome = await runJob(db, id, {
@@ -713,7 +720,14 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
713
720
  onStart: (job) => {
714
721
  startLive(id);
715
722
  live.onStart(job);
716
- watch({ type: 'job', job, call: callId, tab: env.HERDR_ENV ? watchTab(job) : null });
723
+ const opened = env.HERDR_ENV
724
+ ? watchTab(job, tabStart.signal, (reason) => {
725
+ shutTab();
726
+ watch({ type: 'tab-failed', job: job.id, reason: `${reason}, so it is closed` });
727
+ })
728
+ : null;
729
+ tab = opened?.tab ?? null;
730
+ watch({ type: 'job', job, call: callId, tab: opened });
717
731
  begun();
718
732
  },
719
733
  onTool: (call) => {
@@ -753,6 +767,8 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
753
767
  } finally {
754
768
  jobs.delete(id);
755
769
  endLive(id, ended.map((l) => redact(l).text));
770
+ tabStart.abort();
771
+ shutTab();
756
772
  watch({ type: 'job-end', job: id });
757
773
  }
758
774
  }
@@ -785,10 +801,10 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
785
801
  /** How many reports wait for a turn of their own: none once MAX_WOKEN automated turns have run in a row — they wait for the user's next message. */
786
802
  const waiting = () => (woken >= MAX_WOKEN ? 0 : reports.filter((r) => !r.quiet).length);
787
803
 
788
- /** The job's tab in Herdr, showing its work: its pane, or why there is none — the job runs here either way. A watcher that never starts in it is said when it gives up. */
789
- function watchTab(job) {
804
+ /** The job's tab in Herdr, showing its work: its pane and tab, or why there is none — the job runs here either way. `onFail` hears why a watcher never started in it. */
805
+ function watchTab(job, signal, onFail) {
790
806
  try {
791
- return { pane: openWatchTab(herdr, { job, project: getProject(db, job.project), env, onFail: (reason) => watch({ type: 'tab-failed', job: job.id, reason }) }) };
807
+ return openWatchTab(herdr, { job, project: getProject(db, job.project), env, signal, onFail });
792
808
  } catch (cause) {
793
809
  return { error: cause.message };
794
810
  }
@@ -1274,7 +1290,8 @@ export async function chat(db, { model, effort, resume = null, send, input = pro
1274
1290
  errors.write(`${e.red(safeForTerminal(text))}\n${detail ? `${e.dim(` ${safeForTerminal(detail)}`)}\n` : ''}`);
1275
1291
  failed = true;
1276
1292
  };
1277
- const reply = createRenderer(write, s, { width });
1293
+ // A line of code is written whole: the terminal wraps it, and a copy has it as it was written.
1294
+ const reply = createRenderer(write, s, { width, whole: true });
1278
1295
  const session = createChat(db, {
1279
1296
  model,
1280
1297
  effort,
package/src/cli.mjs CHANGED
@@ -624,9 +624,12 @@ function tabBegins(db, job, print, herdr) {
624
624
  function tabEnds(job, status, herdr) {
625
625
  process.stdin.pause();
626
626
  herdr.reportAgent(herdr.runHerdr, process.env, { job, state: job.status === 'needs_input' ? 'blocked' : 'idle', message: status });
627
- herdr.closeJobTab(herdr.runHerdr, process.env, job);
627
+ herdr.closeJobTab(herdr.runHerdr, process.env);
628
628
  }
629
629
 
630
+ /** How long a job's run lock may stand free with no end written before the process running it is taken for gone: a run lets its lock go a moment before its end is written. */
631
+ const GONE_MS = 5000;
632
+
630
633
  /**
631
634
  * `sumo job watch <id>`: what a job running in the chat is doing, as it does it — what its Herdr tab shows, and
632
635
  * what any terminal can show. A line typed here is said to the job. Ends with how the run ended.
@@ -646,14 +649,21 @@ async function watchJob(db, id) {
646
649
  let at = 0;
647
650
  // A character split across two reads is held until its other half arrives.
648
651
  const decoder = new StringDecoder('utf8');
652
+ // The chat running the job holds its run lock: free for a while with no end written, that chat is gone — closed
653
+ // or crashed — and nothing will write the end, so the watch ends here rather than waiting for ever.
654
+ let free = 0;
649
655
  for (;;) {
650
656
  // Looked at before reading, so nothing written before the end is missed.
651
657
  const ended = existsSync(jobs.endFile(id));
652
658
  at = copyFrom(jobs.liveFile(id), at, decoder);
653
659
  if (ended) break;
660
+ free = heldBy(jobs.runLockFile(id)) === null ? free + 250 : 0;
661
+ if (free >= GONE_MS) break;
654
662
  await new Promise((r) => setTimeout(r, 250));
655
663
  }
656
- const lines = safeForTerminal(readFileSync(jobs.endFile(id), 'utf8')).trimEnd().split('\n');
664
+ const lines = existsSync(jobs.endFile(id))
665
+ ? safeForTerminal(readFileSync(jobs.endFile(id), 'utf8')).trimEnd().split('\n')
666
+ : [`j${id} stopped without an end: the process running it is gone — sumo job show j${id} says where it got to`];
657
667
  tabEnds(jobs.getJob(db, id), lines[0], herdr);
658
668
  return lines;
659
669
  }
package/src/herdr.mjs CHANGED
@@ -5,8 +5,9 @@ import { paths, SELF } from './paths.mjs';
5
5
  /**
6
6
  * Herdr is where a delegated job can be watched. The job itself runs in the chat's process; inside Herdr it also
7
7
  * gets a tab of its own, listed on the left and named after it, where `sumo job watch` shows its work as it
8
- * happens and reports it to Herdr as an agent with its state — so the chat keeps one line per job. Everything
9
- * goes through the `herdr` CLI, which answers in JSON.
8
+ * happens and reports it to Herdr as an agent with its state — so the chat keeps one line per job. The chat opened
9
+ * the tab, so the chat closes it once the job's run is over, however it ended. Everything goes through the `herdr`
10
+ * CLI, which answers in JSON — an error on stderr.
10
11
  */
11
12
 
12
13
  export const runHerdr = (args) => spawnSync('herdr', args, { encoding: 'utf8', timeout: 10_000 });
@@ -28,93 +29,127 @@ const shellWord = (text) => (/^[\w/.:=@%+-]+$/.test(text) ? text : `'${text.repl
28
29
 
29
30
  /**
30
31
  * A tab in the chat's workspace that shows a job's work: `sumo job watch`, not the job — that stays in the chat.
31
- * Throws with Herdr's reason when the tab cannot be opened; the job runs the same either way. The watcher is typed
32
- * into the tab's shell after this returns, once the shell is ready for it; `onFail` hears why when it never started.
32
+ * Its pane and its tab, which the chat closes once the run is over. Throws with Herdr's reason when the tab cannot be
33
+ * opened; the job runs the same either way. The watcher is typed into the tab's shell after this returns, once the
34
+ * shell is ready for it, and `signal` calls that off when the run ends first; `onFail` hears why it never started.
33
35
  */
34
- export function openWatchTab(herdr, { job, project, env = process.env, onFail = () => {}, sleep }) {
36
+ export function openWatchTab(herdr, { job, project, env = process.env, onFail = () => {}, sleep, signal = null }) {
35
37
  const workspace = env.HERDR_WORKSPACE_ID ? ['--workspace', env.HERDR_WORKSPACE_ID] : [];
36
38
  const made = herdr(['tab', 'create', ...workspace, '--cwd', project.path, '--label', `${agentLabel(job)} · ${job.title}`, '--no-focus']);
37
- const tab = parse(made, (result) => result.root_pane?.pane_id);
39
+ const tab = parse(made);
38
40
  if (tab.error) throw new Error(tab.error);
39
- // Marked as the tab's own, so the watcher may close it behind a job that is done; the home goes with the command,
41
+ // Marked as the tab's own, so the watcher may close it behind the run; the home goes with the command,
40
42
  // or a chat on another home would be watched from the default one.
41
43
  // The launcher setup made, where there is one; else this very sumo, node and entry by their full paths — a clone not set up yet still has a watcher.
42
44
  const sumo = existsSync(paths().launcher) ? shellWord(paths().launcher) : SELF.map(shellWord).join(' ');
43
45
  const command = `env SUMO_JOB_TAB=1 SUMO_AGENTS_HOME=${shellWord(paths().home)} ${sumo} job watch ${job.id}`;
44
- startWatcher(herdr, { pane: tab.id, job: job.id, command, sleep })
45
- .then((started) => started || onFail('its Herdr tab never started the watcher'))
46
+ startWatcher(herdr, { pane: tab.pane, job, command, sleep, signal })
47
+ .then((started) => started === false && onFail('its Herdr tab never started the watcher'))
46
48
  .catch((cause) => onFail(cause.message));
47
- return tab.id;
49
+ return tab;
48
50
  }
49
51
 
52
+ /** Closes a tab sumo opened; one already gone is no matter. */
53
+ export const closeTab = (herdr, tab) => herdr(['tab', 'close', tab]);
54
+
50
55
  const POLL_MS = 250;
51
- /** How long a new shell is given to reach its prompt, and a typed watcher to start, before it is typed again. */
56
+ /**
57
+ * How long a new shell is given to reach its prompt; how long a typed watcher is given to start before a shell back
58
+ * at its prompt has it typed again; and how long anything else may hold the tab's foreground before it is given up.
59
+ */
52
60
  const READY_MS = 15_000;
53
61
  const STARTED_MS = 3_000;
62
+ const GIVE_UP_MS = 30_000;
54
63
  const TRIES = 3;
55
64
  const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms).unref());
56
65
 
57
- /** What the pane runs in the foreground, from Herdr; null when Herdr cannot say — an older Herdr, or a pane that is gone. */
58
- function foreground(herdr, pane) {
59
- const run = herdr(['pane', 'process-info', '--pane', pane]);
60
- if (run.error || run.status !== 0) return null;
66
+ /** Herdr's answer: `{ result }`, `{ gone: true }` for a pane that is closed, or null when Herdr cannot say — an older Herdr, or one not answering. */
67
+ function ask(herdr, args) {
68
+ const run = herdr(args);
69
+ if (run.error) return null;
61
70
  try {
62
- return JSON.parse(run.stdout).result?.process_info ?? null;
71
+ const answer = JSON.parse(run.status === 0 ? run.stdout : run.stderr);
72
+ if (answer.error) return answer.error.code === 'pane_not_found' ? { gone: true } : null;
73
+ return { result: answer.result ?? {} };
63
74
  } catch {
64
75
  return null;
65
76
  }
66
77
  }
67
78
 
79
+ /** What the pane runs in the foreground; `{ gone: true }` or null as `ask` says. */
80
+ function foreground(herdr, pane) {
81
+ const answer = ask(herdr, ['pane', 'process-info', '--pane', pane]);
82
+ return answer?.gone ? answer : (answer?.result.process_info ?? null);
83
+ }
84
+
68
85
  const screen = (herdr, pane) => {
69
86
  const run = herdr(['pane', 'read', pane, '--source', 'visible']);
70
87
  return run.error || run.status !== 0 ? null : String(run.stdout);
71
88
  };
72
89
 
73
90
  /**
74
- * Types the watcher into a new tab's shell and makes sure it runs. A shell still starting up can throw away what is
75
- * typed before its prompt — the command shows, then nothing — so the watcher is typed only once the shell stands
76
- * alone in the foreground with its screen settled, and typed again, a few times at most, when it did not start.
77
- * True once it runs, or once Herdr can no longer say (the pane closed behind a job that ended, or a Herdr too old to ask).
91
+ * Types the watcher into a new tab's shell and makes sure it runs. The watcher is typed only once the shell stands
92
+ * alone in the foreground with its screen settled — what Herdr itself asks of a shell before it starts an agent there.
93
+ * It has started once Herdr shows its report on the pane (`reportAgent`), or once it runs in the foreground. It is
94
+ * typed again, a few times at most, only when the shell stands alone at its prompt again — the line was lost, or the
95
+ * watcher quit — never while anything runs there: a line typed into a watcher reaches the job as a message.
96
+ * True once it runs; false when it never did; null when it no longer matters — the run is over (`signal`), the pane
97
+ * is gone, or Herdr cannot say (one too old to ask).
78
98
  */
79
- export async function startWatcher(herdr, { pane, job, command, sleep = pause, tries = TRIES }) {
80
- const watching = new RegExp(`job watch ${job}(?!\\d)`);
81
- const started = (info) => info.foreground_processes?.some((p) => watching.test(String(p.cmdline))) || screen(herdr, pane)?.includes(`⏺ j${job} `);
99
+ export async function startWatcher(herdr, { pane, job, command, sleep = pause, tries = TRIES, signal = null }) {
100
+ const watching = new RegExp(`job watch ${job.id}(?!\\d)`);
101
+ const reported = () => ask(herdr, ['pane', 'get', pane])?.result?.pane?.agent === agentLabel(job);
102
+ const started = (info) => info.foreground_processes?.some((p) => watching.test(String(p.cmdline))) || reported();
103
+ const alone = (info) => info.foreground_processes?.every((p) => p.pid === info.shell_pid);
82
104
  for (let attempt = 0; attempt < tries; attempt++) {
83
105
  let last = null;
84
106
  for (let waited = 0; waited < READY_MS; waited += POLL_MS) {
107
+ if (signal?.aborted) return null;
85
108
  const info = foreground(herdr, pane);
109
+ if (info?.gone) return null;
86
110
  if (info === null) break;
87
111
  const now = screen(herdr, pane);
88
- const alone = info.foreground_processes?.every((p) => p.pid === info.shell_pid);
89
- if (alone && now?.trim() && now === last) break;
112
+ if (alone(info) && now?.trim() && now === last) break;
90
113
  last = now;
91
114
  await sleep(POLL_MS);
92
115
  }
116
+ if (signal?.aborted) return null;
93
117
  const run = herdr(['pane', 'run', pane, command]);
94
- if (run.error || run.status !== 0) throw new Error(`Herdr opened the tab but would not run the watcher in it: ${String(run.stderr || run.stdout || run.error?.message).trim().slice(0, 200)}`);
95
- for (let waited = 0; waited < STARTED_MS; waited += POLL_MS) {
118
+ if (run.error || run.status !== 0) {
119
+ if (foreground(herdr, pane)?.gone) return null;
120
+ throw new Error(`Herdr opened the tab but would not run the watcher in it: ${String(run.stderr || run.stdout || run.error?.message).trim().slice(0, 200)}`);
121
+ }
122
+ for (let waited = POLL_MS; ; waited += POLL_MS) {
96
123
  await sleep(POLL_MS);
124
+ if (signal?.aborted) return null;
97
125
  const info = foreground(herdr, pane);
98
- if (info === null || started(info)) return true;
126
+ if (info === null || info.gone) return null;
127
+ if (started(info)) return true;
128
+ if (waited >= STARTED_MS && alone(info)) break;
129
+ if (waited >= GIVE_UP_MS) return false;
99
130
  }
100
131
  }
101
132
  return false;
102
133
  }
103
134
 
104
- function parse(run, pick) {
135
+ /** The tab `tab create` made: its root pane, and the tab to close once the run is over. */
136
+ function parse(run) {
105
137
  if (run.error) return { error: run.error.code === 'ENOENT' ? '`herdr` is not on PATH' : run.error.message };
106
138
  try {
107
- const answer = JSON.parse(run.stdout);
139
+ const answer = JSON.parse(run.status === 0 ? run.stdout : run.stderr || run.stdout);
108
140
  if (answer.error) return { error: answer.error.message ?? answer.error.code ?? 'Herdr refused' };
109
- const id = pick(answer.result ?? {});
110
- return id ? { id } : { error: 'Herdr answered without a pane id' };
141
+ const pane = answer.result?.root_pane?.pane_id;
142
+ const tab = answer.result?.tab?.tab_id ?? answer.result?.root_pane?.tab_id;
143
+ return pane && tab ? { pane, tab } : { error: 'Herdr answered without a pane and tab id' };
111
144
  } catch {
112
145
  return { error: `Herdr did not answer in JSON: ${String(run.stderr || run.stdout).trim().slice(0, 200)}` };
113
146
  }
114
147
  }
115
148
 
116
- /** A job that is done closes the tab opened to watch it; one that failed or stopped on a question keeps it, and a tab the user opened is theirs. */
117
- export function closeJobTab(herdr, env, job) {
118
- if (!env.SUMO_JOB_TAB || !env.HERDR_TAB_ID || job.status !== 'done') return;
119
- herdr(['tab', 'close', env.HERDR_TAB_ID]);
149
+ /**
150
+ * The watcher's side: the tab opened to watch a job closes once the run is over, however it ended. The chat closes
151
+ * it too; this is for a chat that could not. Only a tab sumo opened is closed — a tab the user opened is theirs.
152
+ */
153
+ export function closeJobTab(herdr, env) {
154
+ if (env.SUMO_JOB_TAB && env.HERDR_TAB_ID) closeTab(herdr, env.HERDR_TAB_ID);
120
155
  }
package/src/tty.mjs CHANGED
@@ -23,11 +23,11 @@ const CODES = { bold: ['1', '22'], dim: ['2', '22'], italic: ['3', '23'], underl
23
23
  * reader says as itself: no box drawing, no symbol spelled out by its Unicode name.
24
24
  */
25
25
  const GLYPHS = {
26
- tool: '⏺', fail: '✗', pick: '❯', under: '⎿', bar: '┃', quote: '│', rule: '─', fenceOpen: '┌─', fenceClose: '└─', todo: '☐', done: '☑', bullet: '•', warn: '⚠', thought: '✻',
26
+ tool: '⏺', fail: '✗', pick: '❯', under: '⎿', bar: '┃', quote: '│', rule: '─', todo: '☐', done: '☑', bullet: '•', warn: '⚠', thought: '✻',
27
27
  box: { h: '─', v: '│', tl: '┌', tm: '┬', tr: '┐', ml: '├', mm: '┼', mr: '┤', bl: '└', bm: '┴', br: '┘' },
28
28
  };
29
29
  const PLAIN_GLYPHS = {
30
- tool: '*', fail: 'x', pick: '>', under: '|', bar: '>', quote: '|', rule: '-', fenceOpen: '+-', fenceClose: '+-', todo: '[ ]', done: '[x]', bullet: '-', warn: '!', thought: '*',
30
+ tool: '*', fail: 'x', pick: '>', under: '|', bar: '>', quote: '|', rule: '-', todo: '[ ]', done: '[x]', bullet: '-', warn: '!', thought: '*',
31
31
  box: { h: '-', v: '|', tl: '+', tm: '+', tr: '+', ml: '+', mm: '+', mr: '+', bl: '+', bm: '+', br: '+' },
32
32
  };
33
33
 
@@ -72,7 +72,7 @@ const WIDE = /[\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF
72
72
  const columnsOf = (ch) => (WIDE.test(ch) ? 2 : 1);
73
73
 
74
74
  /** The columns text takes on a terminal, colour codes not counted: a wide character is two, so a table around it lines up. */
75
- const visible = (t) => {
75
+ export const visible = (t) => {
76
76
  const plain = t.replace(/\x1b\[[0-9;]*m|\x1b\]8;[^\x07]*\x07/g, '');
77
77
  if (!/[^\x00-\x7e]/.test(plain)) return plain.length;
78
78
  let width = 0;
@@ -223,10 +223,11 @@ export function highlight(line, lang, s, code = null) {
223
223
  * One line of a reply: block-level marks replaced by weight and indent, then wrapped with a hanging indent.
224
224
  * `hang` is the indent of the list item a line may go on with: an indented line that is not an item of its own is drawn there.
225
225
  */
226
- export function renderLine(line, s, { fence = false, width = MAX_WIDTH, hang = null, lang = '', code = null } = {}) {
227
- // Code is what is read most closely: the frame around it is faint, the code is not.
228
- // A line too long for the window goes on under itself, at its own indent, so the code keeps its shape.
229
- if (fence) return wrap(` ${highlight(line, lang, s, code)}`, width, ` ${/^\s*/.exec(line)[0]}`);
226
+ export function renderLine(line, s, { fence = false, width = MAX_WIDTH, hang = null, lang = '', code = null, whole = false } = {}) {
227
+ // Code is drawn as it was written, from the first column, with nothing around it: what is selected on the screen is the
228
+ // code. `whole`, a line too long for the window is left for the terminal to wrap, and a copy joins it again; else it
229
+ // goes on under itself, at its own indent, so the code keeps its shape.
230
+ if (fence) return whole ? highlight(line, lang, s, code) : wrap(highlight(line, lang, s, code), width, /^\s*/.exec(line)[0]);
230
231
  const heading = /^(#{1,6})\s+(.*)$/.exec(line);
231
232
  if (heading) return wrap(heading[1].length === 1 ? s.bold(s.underline(inline(heading[2], s))) : s.bold(inline(heading[2], s)), width);
232
233
  const item = LIST_ITEM.exec(line);
@@ -382,7 +383,14 @@ function closedForNow(line) {
382
383
  return shown.slice(at + 2).trim() ? `${words}**${shown.slice(words.length)}` : shown.slice(0, at);
383
384
  }
384
385
 
385
- export function createRenderer(write, s, { width = MAX_WIDTH } = {}) {
386
+ const FENCE = /^(\s*)```\s*(\S*)/;
387
+
388
+ /**
389
+ * A reply rendered as it streams, each finished line handed to `write` with `{ code }`: whether it is a line of a code
390
+ * block. `whole` leaves a code line unbroken for the terminal to wrap (see renderLine); the line still arriving is
391
+ * always wrapped, for it is drawn and drawn again inside the window.
392
+ */
393
+ export function createRenderer(write, s, { width = MAX_WIDTH, whole = false } = {}) {
386
394
  let tail = '';
387
395
  let fence = false;
388
396
  let rows = [];
@@ -391,19 +399,30 @@ export function createRenderer(write, s, { width = MAX_WIDTH } = {}) {
391
399
  /** The language the code block in hand is in, and where its colouring has got to: a comment can run over lines. */
392
400
  let lang = '';
393
401
  let code = { comment: false };
402
+ /** A code line loses the indent its fence has, as Markdown reads it: a block in a list item is not drawn, or copied, at the item's indent. */
403
+ let indent = '';
404
+ const unindented = (raw) => (raw.startsWith(indent) ? raw.slice(indent.length) : raw.trimStart());
405
+ /** A line rendered, or null for a fence: outside plain mode it draws no row of its own. */
394
406
  const line = (raw) => {
395
- const marks = /^\s*```\s*(\S*)/.exec(raw);
407
+ const marks = FENCE.exec(raw);
396
408
  if (marks) {
397
409
  fence = !fence;
398
410
  hang = null;
399
- lang = fence ? marks[1].toLowerCase() : '';
411
+ lang = fence ? marks[2].toLowerCase() : '';
412
+ indent = fence ? marks[1] : '';
400
413
  code = { comment: false };
401
- // Plain mode names the block in words, for a reader: no frame corner to spell out.
402
- if (s.plain) return s.dim(fence ? ` code${marks[1] ? ` (${marks[1]})` : ''}:` : ' end of code');
403
- return s.dim(fence ? ` ${s.g.fenceOpen}${marks[1] ? ` ${marks[1]}` : ''}` : ` ${s.g.fenceClose}`);
414
+ // Plain mode names the block in words, for a reader.
415
+ if (s.plain) return s.dim(fence ? `code${marks[2] ? ` (${marks[2]})` : ''}:` : 'end of code');
416
+ return null;
404
417
  }
405
- if (!fence) hang = hangOf(raw) ?? (/^\s+\S/.test(raw) || raw.trim() === '' ? hang : null);
406
- return renderLine(raw, s, { fence, width, hang: hangOf(raw) === null ? hang : null, lang, code });
418
+ if (fence) return renderLine(unindented(raw), s, { fence, width, lang, code, whole });
419
+ hang = hangOf(raw) ?? (/^\s+\S/.test(raw) || raw.trim() === '' ? hang : null);
420
+ return renderLine(raw, s, { width, hang: hangOf(raw) === null ? hang : null });
421
+ };
422
+ const put = (raw, end) => {
423
+ const isCode = fence && !FENCE.test(raw);
424
+ const shown = line(raw);
425
+ if (shown !== null) write(`${shown}${end}`, { code: isCode });
407
426
  };
408
427
  /** The rows held so far: a table once its rule has come, the lines they were otherwise. */
409
428
  const held = () => (rows.length >= 2 && TABLE_RULE.test(rows[1]) ? renderTable(rows, s, width) : rows.map((r) => renderLine(r, s, { width })).join('\n'));
@@ -418,9 +437,9 @@ export function createRenderer(write, s, { width = MAX_WIDTH } = {}) {
418
437
  rows.push(raw);
419
438
  continue;
420
439
  }
421
- if (rows.length > 0) write(`${held()}\n`);
440
+ if (rows.length > 0) write(`${held()}\n`, { code: false });
422
441
  rows = [];
423
- write(`${line(raw)}\n`);
442
+ put(raw, '\n');
424
443
  }
425
444
  },
426
445
  flush() {
@@ -428,19 +447,24 @@ export function createRenderer(write, s, { width = MAX_WIDTH } = {}) {
428
447
  rows.push(tail);
429
448
  tail = '';
430
449
  }
431
- if (rows.length > 0) write(`${held()}${tail ? '\n' : ''}`);
432
- if (tail) write(line(tail));
450
+ if (rows.length > 0) write(`${held()}${tail ? '\n' : ''}`, { code: false });
451
+ if (tail) put(tail, '');
433
452
  tail = '';
434
453
  rows = [];
435
454
  fence = false;
436
455
  hang = null;
437
456
  lang = '';
457
+ indent = '';
438
458
  code = { comment: false };
439
459
  },
460
+ /** Whether the line still arriving is a line of code. */
461
+ get fenced() {
462
+ return fence;
463
+ },
440
464
  /** What has not been written yet, rendered as far as it has got: the rows of a table, and the line still arriving. */
441
465
  get tail() {
442
466
  const going = /^\s+\S/.test(tail) && hangOf(tail) === null ? hang : null;
443
- return [rows.length > 0 ? held() : '', tail && !/^\s*```/.test(tail) ? renderLine(fence ? tail : closedForNow(tail), s, { fence, width, hang: going, lang, code: { ...code } }) : ''].filter(Boolean).join('\n');
467
+ return [rows.length > 0 ? held() : '', tail && !FENCE.test(tail) ? renderLine(fence ? unindented(tail) : closedForNow(tail), s, { fence, width, hang: going, lang, code: { ...code } }) : ''].filter(Boolean).join('\n');
444
468
  },
445
469
  };
446
470
  }
@@ -847,10 +871,11 @@ export function transcript(log, s, { width = MAX_WIDTH, cwd = null } = {}) {
847
871
  if (entry.kind === 'user') out.push('', ...untab(entry.text).split('\n').map((line) => `${s.yellow(g.bar)} ${line}`));
848
872
  else if (entry.kind === 'reply') {
849
873
  const drawn = [];
850
- const reply = createRenderer((text) => drawn.push(text), s, { width: Math.max(MIN_WIDTH, width - 3) });
874
+ const reply = createRenderer((text, { code }) => drawn.push(...text.replace(/\n$/, '').split('\n').map((row) => ({ row, code }))), s, { width: Math.max(MIN_WIDTH, width - 3) });
851
875
  reply.write(entry.raw);
852
876
  reply.flush();
853
- out.push('', ...drawn.join('').replace(/\n$/, '').split('\n').map((line, i) => `${i === 0 ? `${g.tool} ` : ' '}${line}`));
877
+ // A line of code stands at the first column, as on the chat screen: what is selected is the code.
878
+ out.push('', ...drawn.map(({ row, code }, i) => (code ? row : `${i === 0 ? `${g.tool} ` : ' '}${row}`)));
854
879
  } else if (entry.kind === 'tool') {
855
880
  const view = toolView(entry.call, entry.result, { full: true, cwd });
856
881
  const stat = statOf(view.stat, s);
package/src/ui.mjs CHANGED
@@ -17,7 +17,7 @@ import { elapsed } from './text.mjs';
17
17
  import { cleanPaste, editor, keysOf, matchFiles, menuOf, paste, press, under } from './editor.mjs';
18
18
  import { clipboardImage, copyText, droppedImages } from './images.mjs';
19
19
  import { ASK_TOOL, BASH_TOOL, DELEGATE_TOOL, EDITOR_TOOL } from './tools.mjs';
20
- import { colourEnabled, createRenderer, explained, flow, fold, glyphs, inline, linked, logoLines, markdownOf, messageAt, pathFrom, pickMessage, renderBlock, safeForTerminal, spinnerMessages, statOf, styles, sunset, tilde, toolView, transcript, untab, VERSION, withoutColourCodes, withSpan, wrap } from './tty.mjs';
20
+ import { colourEnabled, createRenderer, explained, flow, fold, glyphs, inline, linked, logoLines, markdownOf, messageAt, pathFrom, pickMessage, renderBlock, safeForTerminal, spinnerMessages, statOf, styles, sunset, tilde, toolView, transcript, untab, VERSION, visible, withoutColourCodes, withSpan, wrap } from './tty.mjs';
21
21
 
22
22
  /**
23
23
  * The chat on a real terminal. What is finished scrolls away above — what
@@ -632,8 +632,13 @@ function Question({ ask, columns }) {
632
632
  );
633
633
  }
634
634
 
635
- /** One line of a reply; the first of a block carries the mark. */
636
- function Reply({ text, first }) {
635
+ /**
636
+ * One line of a reply; the first of a block carries the mark. A line of code stands at the first column, no mark or
637
+ * indent before it, and whole: the terminal wraps one too long for the window, so what is selected and copied is the
638
+ * line as it was written. Ink cuts nothing a box wider than the window holds.
639
+ */
640
+ function Reply({ text, first, code = false }) {
641
+ if (code) return h(Box, { marginTop: first ? 1 : 0, flexShrink: 0, width: Math.max(1, ...String(text).split('\n').map(visible)) }, h(Text, null, text || ' '));
637
642
  const g = useMarks();
638
643
  // 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.
639
644
  return h(Box, { marginTop: first ? 1 : 0 }, h(Box, { flexShrink: 0 }, h(Text, null, first ? `${g.tool} ` : ' ')), h(Text, null, text || ' '));
@@ -1082,7 +1087,11 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1082
1087
  * An item is drawn apart to be counted, and that sets off a draw of the screen that is waiting, if one is: so an item leaves
1083
1088
  * `unmeasured` only once it is counted, and a draw it sets off keeps the room shut rather than one row too tall.
1084
1089
  */
1085
- const rowsOf = (item) => renderToString(h(Marks.Provider, { value: s.g }, h(Item, { item, columns: state.columns, s })), { columns: state.columns }).split('\n').length;
1090
+ // A line of code wider than the window is the rows the terminal wraps it to.
1091
+ const rowsOf = (item) =>
1092
+ renderToString(h(Marks.Provider, { value: s.g }, h(Item, { item, columns: state.columns, s })), { columns: state.columns })
1093
+ .split('\n')
1094
+ .reduce((rows, row) => rows + Math.max(1, Math.ceil(visible(row) / state.columns)), 0);
1086
1095
  const measure = () => {
1087
1096
  while (state.unmeasured.length > 0) {
1088
1097
  if (state.used < state.rows) state.used += rowsOf(state.unmeasured[0]);
@@ -1123,15 +1132,15 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
1123
1132
  }
1124
1133
  redraw();
1125
1134
  };
1126
- /** A renderer for a reply: each line it finishes goes on the screen, the first of a block with the mark. */
1135
+ /** A renderer for a reply: each line it finishes goes on the screen, the first of a block with the mark; a line of code whole. */
1127
1136
  const replyTo = (put) =>
1128
1137
  createRenderer(
1129
- (rendered) => {
1130
- put({ kind: 'text', text: rendered.replace(/\n$/, ''), first: state.fresh });
1138
+ (rendered, { code }) => {
1139
+ put({ kind: 'text', text: rendered.replace(/\n$/, ''), first: state.fresh, code });
1131
1140
  state.fresh = false;
1132
1141
  },
1133
1142
  s,
1134
- { width: state.columns - 3 },
1143
+ { width: state.columns - 3, whole: true },
1135
1144
  );
1136
1145
  /** One entry of the log as the lines this window shows for it. */
1137
1146
  function drawn(entry) {
@@ -2203,7 +2212,7 @@ function App({ session, events, messages, cwd, block, opening, logo, clipboard,
2203
2212
  { flexDirection: 'column', minHeight: room },
2204
2213
  h(Static, { key: state.epoch, items: state.items }, (item) => h(Item, { key: item.id, item, columns, s })),
2205
2214
  ...reads.map((item, i) => h(Item, { key: `reads-${i}`, item, columns, s })),
2206
- tail ? h(Reply, { text: tail, first: state.fresh }) : null,
2215
+ tail ? h(Reply, { text: tail, first: state.fresh, code: state.reply.fenced }) : null,
2207
2216
  // In one box of their own, so the lines coming and going never move what follows — the working line keeps its clock.
2208
2217
  h(Box, { flexDirection: 'column' }, ...steps.map((step) => h(Tool, step))),
2209
2218
  // 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.