@hmharness/cli 0.14.7 → 0.14.10

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/dist/tui.js CHANGED
@@ -13,7 +13,7 @@
13
13
  import { stdin, stdout } from 'node:process';
14
14
  import { basename } from 'node:path';
15
15
  import { createRequire } from 'node:module';
16
- import { loadConfig, homeDir, resolveProvider, listProviders, setChatRoute, setLocale, PROVIDER_PRESETS, addProviders, detectLocalProviders, latestSession, listSessions, loadTranscript } from '@hmharness/kernel';
16
+ import { loadConfig, homeDir, resolveProvider, listProviders, setChatRoute, setLocale, PROVIDER_PRESETS, addProviders, detectLocalProviders, latestSession, listSessions, loadTranscript, transcriptChars, compactMessages, adaptiveContextChars, getGoal, setGoal, clearGoal } from '@hmharness/kernel';
17
17
  import { listDrafts, listSkills, runBench, runEvolution } from '@hmharness/evolution';
18
18
  import { buildRegistry, runAgentTask, strings } from '@hmharness/agent';
19
19
  import { ensureWebDaemon, DEFAULT_WEB_PORT } from "./web-daemon.js";
@@ -106,6 +106,17 @@ export const COMMANDS = [
106
106
  { name: '/resume', key: 'cmdResume' },
107
107
  { name: '/status', key: 'cmdStatus' },
108
108
  { name: '/clear', key: 'cmdClear' },
109
+ { name: '/compact', key: 'cmdCompact' },
110
+ { name: '/diff', key: 'cmdDiff' },
111
+ { name: '/new', key: 'cmdNew' },
112
+ { name: '/fork', key: 'cmdFork' },
113
+ { name: '/copy', key: 'cmdCopy' },
114
+ { name: '/plan', key: 'cmdPlan' },
115
+ { name: '/goal', key: 'cmdGoal' },
116
+ { name: '/usage', key: 'cmdUsage' },
117
+ { name: '/statusline', key: 'cmdStatusline' },
118
+ { name: '/keymap', key: 'cmdKeymap' },
119
+ { name: '/review', key: 'cmdReview' },
109
120
  { name: '/web', key: 'cmdWeb' },
110
121
  { name: '/exit', key: 'cmdExit' },
111
122
  ];
@@ -123,6 +134,85 @@ export function nextLocale(current, arg) {
123
134
  return a;
124
135
  return current === 'en' ? 'zh' : 'en';
125
136
  }
137
+ /* ---------------- M2 runtime-steering helpers (pure, testable) ---------------- */
138
+ /** The trailing `@<query>` token of a task line, or null. Drives the @-file
139
+ * palette (codex/dsh @ reference): typing '@' opens it, the following
140
+ * path-ish chars extend the query, Enter inserts the picked path. */
141
+ export function atToken(input) {
142
+ if (input.startsWith('/'))
143
+ return null; // slash commands never @-reference
144
+ const m = /@([\w./\\-]*)$/.exec(input);
145
+ return m ? m[1] : null;
146
+ }
147
+ /** Substring history search (Ctrl+R): indices of entries containing the
148
+ * query (case-insensitive), NEWEST first, capped at 50. Empty query lists
149
+ * the most recent 50. */
150
+ export function histMatches(history, query) {
151
+ const q = query.trim().toLowerCase();
152
+ const out = [];
153
+ for (let i = history.length - 1; i >= 0 && out.length < 50; i--) {
154
+ if (!q || history[i].toLowerCase().includes(q))
155
+ out.push(i);
156
+ }
157
+ return out;
158
+ }
159
+ /** `!` line prefix → the shell command to run (B3), or null. Empty `!` is
160
+ * not a command. */
161
+ export function shellBang(line) {
162
+ if (!line.startsWith('!'))
163
+ return null;
164
+ const cmd = line.slice(1).trim();
165
+ return cmd || null;
166
+ }
167
+ /** Double-Esc fork-edit arming (B6): a bare Esc when idle+empty returns true
168
+ * only if the previous Esc was within `windowMs` and the arm is set. Pure
169
+ * timing decision; the runtime keeps escAt/armed state. */
170
+ export function forkArm(prevAt, now, armed, windowMs = 800) {
171
+ return armed && now - prevAt < windowMs;
172
+ }
173
+ /** Index of the LAST user-role message — the fork point (T13): a fork keeps
174
+ * everything BEFORE it as the new thread's resume and replaces it with the
175
+ * edited message. -1 when there is none. */
176
+ export function lastUserIdx(messages) {
177
+ for (let i = messages.length - 1; i >= 0; i--) {
178
+ if (messages[i].role === 'user')
179
+ return i;
180
+ }
181
+ return -1;
182
+ }
183
+ /* ---------------- M5: statusline template + keymap (pure, testable) ---------------- */
184
+ /** /statusline (B11): render a configurable bottom-line template. Supported
185
+ * placeholders: {model} {cwd} {skills} {mode} {queue} {version} — unknown
186
+ * tokens stay literal so a typo is visible, never silently dropped. */
187
+ export function renderStatusline(template, ctx) {
188
+ const map = {
189
+ model: ctx.model, cwd: ctx.cwd, skills: String(ctx.skills),
190
+ mode: ctx.mode, queue: String(ctx.queue), version: ctx.version,
191
+ };
192
+ return String(template).replace(/\{(\w+)\}/g, (m, k) => (k in map ? map[k] : m));
193
+ }
194
+ /** /keymap (B14): parse a human key spec into the raw-mode byte string the
195
+ * TUI dispatches on. Returns null for unknown specs. */
196
+ export function parseKeySpec(spec) {
197
+ const s = String(spec ?? '').trim().toLowerCase();
198
+ const named = {
199
+ 'ctrl+j': '\x0a', 'ctrl-enter': '\x0a', 'ctrl+r': '\x12', 'ctrl+t': '\x14',
200
+ 'ctrl+g': '\x07', 'ctrl+p': '\x10', 'ctrl+n': '\x0e', esc: '\x1b', enter: '\r', tab: '\t',
201
+ };
202
+ if (named[s])
203
+ return named[s];
204
+ if (/^[a-z0-9]$/.test(s))
205
+ return s;
206
+ return null;
207
+ }
208
+ /** The remappable M2/M4 actions and their defaults (B14). */
209
+ export const KEYMAP_DEFAULTS = {
210
+ interrupt: '\x1b', // T9: stop the running turn
211
+ inject: '\x0a', // T10: Ctrl+Enter inject
212
+ historySearch: '\x12', // T14: Ctrl+R
213
+ transcript: '\x14', // T15: Ctrl+T
214
+ externalEdit: '\x07', // B12: Ctrl+G
215
+ };
126
216
  /**
127
217
  * SGR mouse wheel decoding: '\x1b[<64;COL;ROWM' is wheel-up (-1), 65 is
128
218
  * wheel-down (+1), anything else (clicks, drags, plain keys) is 0.
@@ -138,6 +228,21 @@ export function parseWheel(data) {
138
228
  return 1;
139
229
  return 0;
140
230
  }
231
+ /**
232
+ * SGR reports can split across stdin chunks (fast wheel bursts fragment in
233
+ * some terminals). If the buffer ends inside a report - a trailing
234
+ * '\x1b[<...' with no terminating M/m yet - slice it off as `pending` for
235
+ * the next chunk and hand back only the complete part.
236
+ */
237
+ export function splitMouseReport(data) {
238
+ const cut = data.lastIndexOf('\x1b[<');
239
+ if (cut === -1)
240
+ return { data, pending: '' };
241
+ const tail = data.slice(cut);
242
+ return /^\x1b\[<\d+(;\d+)*[Mm]$/.test(tail)
243
+ ? { data, pending: '' }
244
+ : { data: data.slice(0, cut), pending: tail };
245
+ }
141
246
  export class TuiRuntime {
142
247
  entries = [];
143
248
  dirty = true;
@@ -171,23 +276,49 @@ export class TuiRuntime {
171
276
  modeTag = '';
172
277
  /** rows for the `/model ` picker (configured providers first, set by driver) */
173
278
  modelChoices = [];
174
- /** Wheel/click handling: NO mouse reporting by default - select/copy
175
- * always works and terminals translate the wheel to arrow keys on the
176
- * alternate screen. Reporting turns on ONLY while a palette is open
177
- * (modal: clicks choose rows, the wheel drives the selection) and turns
178
- * off the moment it closes. (A permanent /mouse toggle existed for
179
- * terminals without alt-screen wheel mapping; removed - it cost native
180
- * selection full-time to fix a case this Windows/HarmonyOS-first tool
181
- * does not target.) */
182
- mouseReported = false;
279
+ /** Wheel/click handling: SGR mouse reporting is ALWAYS on (enabled with
280
+ * ?1000h+?1006h at startup). Cross-terminal wheel support has to come
281
+ * from explicit reports: only some terminals translate the wheel to
282
+ * arrow keys on the alternate screen, so the wheel would silently do
283
+ * nothing on the others (conhost, several Linux terminals, the
284
+ * KaihongOS terminal). The wheel drives the transcript (or the open
285
+ * palette's selection); clicks only pick rows while a palette is open.
286
+ * Native select/copy stays available via Shift+click, the standard
287
+ * bypass in mainstream terminals. */
288
+ mouseReported = true;
289
+ /** tail of an SGR mouse report split across stdin chunks (fast wheel
290
+ * bursts); prepended to the next chunk so parseWheel sees the sequence */
291
+ mousePending = '';
183
292
  /** screen row of each visible palette item (SGR click hit-testing); the
184
293
  * render loop records row = frame.length (1-based) as it pushes rows */
185
294
  paletteClickRows = [];
295
+ /* ---------------- M2: runtime steering modals (codex parity) ---------------- */
296
+ /** Ctrl+R incremental history search: { query, matches (history indices), sel } */
297
+ histSearch = null;
298
+ /** Ctrl+T full-transcript overlay (also the pager base for B9): title + lines + viewport top */
299
+ overlay = null;
300
+ /** @-file palette (codex @ fuzzy reference): trailing @token query + ranked hits */
301
+ atPal = null;
302
+ /** double-Esc fork-edit arming (T13): timestamp of the first bare Esc */
303
+ escAt = 0;
304
+ forkArmed = false;
305
+ /** driver callbacks for the running-interaction trio (T9/T10) */
306
+ interruptFn = null;
307
+ injectFn = null;
308
+ forkEditFn = null;
309
+ /** M5 B12: Ctrl+G hands the draft to an external editor ($EDITOR/notepad) */
310
+ externalEditFn = null;
311
+ /** M5 B14: remappable key bindings (config.json tui.keymap) */
312
+ keymap = { ...KEYMAP_DEFAULTS };
313
+ /** last user-submitted line, for Esc-Esc edit-and-fork (T13) */
314
+ lastUserMsg = '';
186
315
  constructor() {
187
316
  // ?1l forces DECCKM OFF so arrow keys arrive as CSI (\x1b[A) even if a
188
317
  // previous program left the terminal in application cursor mode - in
189
- // that mode arrows arrive as SS3 (\x1bOA) and would be silently dropped
190
- stdout.write('\x1b[?1049h\x1b[?25l\x1b[2J\x1b[?1l');
318
+ // that mode arrows arrive as SS3 (\x1bOA) and would be silently dropped.
319
+ // SGR mouse reporting on from the first frame: the wheel must scroll on
320
+ // every terminal, not only the ones that map wheel->arrows themselves.
321
+ stdout.write('\x1b[?1049h\x1b[?25l\x1b[2J\x1b[?1l\x1b[?1000h\x1b[?1006h');
191
322
  stdin.setRawMode?.(true);
192
323
  stdin.resume();
193
324
  stdin.setEncoding('utf8');
@@ -316,6 +447,64 @@ export class TuiRuntime {
316
447
  const posLine = t.pickerPos(pos, vis.length, vis.length ? String(Math.round((pos / vis.length) * 100)) : '0');
317
448
  frame.push(' '.repeat(Math.max(0, W - posLine.length - 1)) + DIM(posLine));
318
449
  }
450
+ /** Ctrl+R history-search modal (B4): query line + matching entries,
451
+ * newest first; Enter adopts, Esc closes, ^P/^N or arrows move. */
452
+ renderHistSearch(frame, W, H) {
453
+ const hs = this.histSearch;
454
+ const t = this.t;
455
+ frame.push(truncateTo(BOLD(' ⌕ ' + t.histSearchTitle) + DIM(` ${hs.matches.length}`), W));
456
+ frame.push(DIM('─'.repeat(W)));
457
+ frame.push(truncateTo(' ' + (hs.query || DIM(t.histSearchNone)), W - 1));
458
+ frame.push(DIM('─'.repeat(W)));
459
+ const listH = Math.max(3, H - 5);
460
+ const vis = hs.matches;
461
+ for (let i = 0; i < listH && i < vis.length; i++) {
462
+ const sel = i === hs.sel;
463
+ const line = this.history[vis[i]] ?? '';
464
+ const plain = truncateTo((i + 1) + '. ' + line, W - 1);
465
+ frame.push(sel ? '\x1b[7m' + plain + ' '.repeat(Math.max(0, W - 1 - strWidth(plain))) + '\x1b[27m' : ' ' + plain);
466
+ }
467
+ if (vis.length === 0)
468
+ frame.push(DIM(' ' + t.histSearchNone));
469
+ frame.push(DIM('─'.repeat(W)));
470
+ frame.push(DIM(truncateTo(' ' + t.histSearchHint, W - 1)));
471
+ }
472
+ /** Ctrl+T full-transcript overlay (B5): title + scrollable lines; also the
473
+ * pager base for long outputs (B9). q/Esc closes, ↑↓/PgUp/PgDn/g/G scroll. */
474
+ renderOverlay(frame, W, H) {
475
+ const ov = this.overlay;
476
+ const t = this.t;
477
+ const listH = Math.max(5, H - 3);
478
+ frame.push(truncateTo(BOLD(' ' + ov.title) + DIM(` ${ov.lines.length}`), W));
479
+ frame.push(DIM('─'.repeat(W)));
480
+ if (ov.lines.length === 0)
481
+ frame.push(DIM(' (empty)'));
482
+ for (let i = 0; i < listH && ov.top + i < ov.lines.length; i++) {
483
+ frame.push(truncateTo(ov.lines[ov.top + i] || ' ', W - 1));
484
+ }
485
+ frame.push(DIM('─'.repeat(W)));
486
+ frame.push(DIM(truncateTo(' ' + t.overlayHint, W - 1)));
487
+ }
488
+ /** @-file palette (B2): ranked workspace hits for the trailing @token.
489
+ * Enter inserts the path; Esc closes; arrows move. */
490
+ renderAtPal(frame, W, H) {
491
+ const pal = this.atPal;
492
+ const t = this.t;
493
+ const title = BOLD(' @ ') + DIM('/' + pal.query + (pal.results.length ? ` · ${pal.results.length}` : ''));
494
+ frame.push(truncateTo(title, W));
495
+ frame.push(DIM('─'.repeat(W)));
496
+ const listH = Math.min(8, Math.max(3, H - 6));
497
+ if (pal.results.length === 0) {
498
+ frame.push(DIM(' ' + t.histSearchNone));
499
+ }
500
+ for (let i = 0; i < listH && i < pal.results.length; i++) {
501
+ const sel = i === pal.sel;
502
+ const plain = truncateTo(' ' + pal.results[i].rel, W - 1);
503
+ frame.push(sel ? '\x1b[7m' + plain + ' '.repeat(Math.max(0, W - 1 - strWidth(plain))) + '\x1b[27m' : plain);
504
+ }
505
+ frame.push(DIM('─'.repeat(W)));
506
+ frame.push(DIM(truncateTo(' ' + t.atPalHint, W - 1)));
507
+ }
319
508
  /** Run the highlighted palette row (shared by Enter and palette clicks);
320
509
  * with no palette open it just submits the typed input. */
321
510
  pickHighlighted() {
@@ -377,16 +566,6 @@ export class TuiRuntime {
377
566
  this.modeTag = tag;
378
567
  this.dirty = true;
379
568
  }
380
- /** Reporting is on ONLY while a palette is open. The palette is a modal:
381
- * while it shows, clicks choose its rows and the wheel drives its
382
- * selection; drag-select resumes the moment it closes. */
383
- syncMouseReporting() {
384
- const want = this.panelItems(this.input).length > 0;
385
- if (want === this.mouseReported)
386
- return;
387
- this.mouseReported = want;
388
- stdout.write(want ? '\x1b[?1000h\x1b[?1006h' : '\x1b[?1000l\x1b[?1006l');
389
- }
390
569
  /** The palette data source: `/model ` opens the model picker, otherwise
391
570
  * slash commands. (/resume submits straight through to the driver, which
392
571
  * opens the Codex-style full-frame picker - resume-picker.ts.) Rows are
@@ -467,7 +646,15 @@ export class TuiRuntime {
467
646
  if (kind === 'say') {
468
647
  const wrapped = wrapTo(buf, width);
469
648
  lines.length = 0;
470
- wrapped.forEach((l) => lines.push(l));
649
+ // B10: completed lines get markdown color ONCE; the in-progress tail
650
+ // stays raw until it wraps — stable rows never reflow
651
+ const lastIdx = wrapped.length - 1;
652
+ for (let i = 0; i < lastIdx; i++)
653
+ lines.push(TuiRuntime.mdColor(wrapped[i]));
654
+ if (wrapped.length) {
655
+ const last = wrapped[lastIdx];
656
+ lines.push(buf.endsWith('\n') ? TuiRuntime.mdColor(last) : last);
657
+ }
471
658
  }
472
659
  else {
473
660
  // thinking stays FOLDED while streaming: one live line (what Claude
@@ -545,9 +732,303 @@ export class TuiRuntime {
545
732
  this.dirty = true;
546
733
  return line;
547
734
  }
735
+ setInput(text) {
736
+ this.input = text;
737
+ this.caret = text.length;
738
+ this.cmdIdx = 0;
739
+ this.dirty = true;
740
+ }
741
+ setLastUserText(s) {
742
+ this.lastUserMsg = s;
743
+ }
744
+ /** Last user-submitted line (Esc-Esc edit-and-fork source, T13). */
745
+ getLastUserText() {
746
+ return this.lastUserMsg;
747
+ }
548
748
  onSubmit(fn) {
549
749
  this.driver = fn;
550
750
  }
751
+ /* ---------------- M2 runtime steering API (driver wiring) ---------------- */
752
+ onInterrupt(fn) { this.interruptFn = fn; }
753
+ onInject(fn) { this.injectFn = fn; }
754
+ onForkEdit(fn) { this.forkEditFn = fn; }
755
+ onExternalEdit(fn) { this.externalEditFn = fn; }
756
+ /** M5 B14: apply remapped keys (config.json tui.keymap); unknown actions
757
+ * are ignored so a stale config degrades to defaults, never breaks keys */
758
+ setKeymap(map) {
759
+ this.keymap = { ...KEYMAP_DEFAULTS, ...map };
760
+ }
761
+ /** Close any open modal (Esc priority: panels close before anything else,
762
+ * T7/T9 order). Returns true when something was open. */
763
+ closeModal() {
764
+ if (this.histSearch) {
765
+ this.histSearch = null;
766
+ this.dirty = true;
767
+ return true;
768
+ }
769
+ if (this.overlay) {
770
+ this.overlay = null;
771
+ this.dirty = true;
772
+ return true;
773
+ }
774
+ if (this.atPal) {
775
+ this.atPal = null;
776
+ this.dirty = true;
777
+ return true;
778
+ }
779
+ return false;
780
+ }
781
+ /** Ctrl+R: incremental history search modal (B4). Enter adopts the match
782
+ * into the input; Esc closes; ^P/^N or arrows move. */
783
+ openHistSearch() {
784
+ if (!this.history.length)
785
+ return;
786
+ this.histSearch = { query: '', matches: histMatches(this.history, ''), sel: 0 };
787
+ this.dirty = true;
788
+ }
789
+ histKey(data) {
790
+ const hs = this.histSearch;
791
+ if (!hs)
792
+ return;
793
+ if (data === '\x1b') {
794
+ this.histSearch = null;
795
+ this.dirty = true;
796
+ return;
797
+ }
798
+ if (data === '\r') {
799
+ const line = this.history[hs.matches[hs.sel]];
800
+ if (line !== undefined) {
801
+ this.histSearch = null;
802
+ this.setInput(line);
803
+ }
804
+ return;
805
+ }
806
+ if (data === '\x1b[A' || data === '\x10') {
807
+ hs.sel = Math.max(0, hs.sel - 1);
808
+ this.dirty = true;
809
+ return;
810
+ }
811
+ if (data === '\x1b[B' || data === '\x0e') {
812
+ hs.sel = Math.min(hs.matches.length - 1, hs.sel + 1);
813
+ this.dirty = true;
814
+ return;
815
+ }
816
+ if (data === '\x7f' || data === '\b') {
817
+ hs.query = hs.query.slice(0, -1);
818
+ hs.matches = histMatches(this.history, hs.query);
819
+ hs.sel = 0;
820
+ this.dirty = true;
821
+ return;
822
+ }
823
+ if (data.length === 1 && data >= ' ') {
824
+ hs.query += data;
825
+ hs.matches = histMatches(this.history, hs.query);
826
+ hs.sel = 0;
827
+ this.dirty = true;
828
+ }
829
+ }
830
+ /** Ctrl+T: full-transcript overlay (B5), also the pager base for long
831
+ * outputs (B9). ↑↓/PgUp/PgDn/g/G scroll, Esc/q closes. */
832
+ overlaySource = () => [];
833
+ setOverlaySource(fn) { this.overlaySource = fn; }
834
+ openOverlay(title, lines) {
835
+ const H = Math.max(5, (stdout.rows || 30) - 2);
836
+ this.overlay = { title, lines, top: Math.max(0, lines.length - H) };
837
+ this.dirty = true;
838
+ }
839
+ /** Public pager/overlay entry (M4 /diff, B9 auto-pager). */
840
+ showOverlay(title, lines) {
841
+ this.openOverlay(title, lines);
842
+ }
843
+ /* ---------------- M4: tool-result cells (B8) ---------------- */
844
+ toolCells = [];
845
+ /** Tool call + result as a collapsible cell: one folded summary line by
846
+ * default (W1/T5 spirit); the `z` key (idle + empty input) expands the
847
+ * LAST cell to its full output. */
848
+ addToolCell(folded, full) {
849
+ const width = Math.max(20, (stdout.columns || 100) - 2);
850
+ const entry = { lines: wrapTo(folded, width).map((l) => DIM(l)) };
851
+ this.entries.push(entry);
852
+ this.toolCells.push({ entry, full, folded, expanded: false });
853
+ this.scrollFromBottom = 0;
854
+ this.dirty = true;
855
+ }
856
+ toggleLastCell() {
857
+ const cell = this.toolCells[this.toolCells.length - 1];
858
+ if (!cell)
859
+ return false;
860
+ const width = Math.max(20, (stdout.columns || 100) - 2);
861
+ cell.expanded = !cell.expanded;
862
+ cell.entry.lines = cell.expanded
863
+ ? [...wrapTo(cell.folded, width).map((l) => DIM(l)), ...wrapTo(cell.full, width)]
864
+ : wrapTo(cell.folded, width).map((l) => DIM(l));
865
+ this.dirty = true;
866
+ return true;
867
+ }
868
+ /* ---------------- M4: streaming markdown colorizer (B10) ---------------- */
869
+ /** Light zero-dep markdown line color for STREAMED text: headings cyan,
870
+ * list markers dim, fences dim, blockquotes dim; everything else plain.
871
+ * Applied per completed line so already-stable rows never reflow. */
872
+ static mdColor(line) {
873
+ const t = line.trim();
874
+ if (/^#{1,6}\s/.test(t))
875
+ return CYAN(BOLD(line));
876
+ if (/^```/.test(t))
877
+ return DIM(line);
878
+ if (/^>\s?/.test(t))
879
+ return DIM(line);
880
+ if (/^[-*+]\s/.test(t) || /^\d+[.)]\s/.test(t))
881
+ return DIM(line.replace(/^(\s*[-*+]\s|\s*\d+[.)]\s)/, '$1'));
882
+ return line;
883
+ }
884
+ overlayKey(data) {
885
+ const ov = this.overlay;
886
+ if (!ov)
887
+ return;
888
+ const H = Math.max(5, (stdout.rows || 30) - 2);
889
+ const maxTop = Math.max(0, ov.lines.length - H);
890
+ if (data === '\x1b' || data === '\x03' || data === 'q' || data === 'Q') {
891
+ this.overlay = null;
892
+ this.dirty = true;
893
+ return;
894
+ }
895
+ if (data === '\x1b[A' || data === '\x1b[5~' || data === 'k') {
896
+ ov.top = Math.max(0, ov.top - 1);
897
+ this.dirty = true;
898
+ return;
899
+ }
900
+ if (data === '\x1b[B' || data === '\x1b[6~' || data === 'j') {
901
+ ov.top = Math.min(maxTop, ov.top + 1);
902
+ this.dirty = true;
903
+ return;
904
+ }
905
+ if (data === '\x1b[H' || data === 'g') {
906
+ ov.top = 0;
907
+ this.dirty = true;
908
+ return;
909
+ }
910
+ if (data === '\x1b[F' || data === 'G') {
911
+ ov.top = maxTop;
912
+ this.dirty = true;
913
+ return;
914
+ }
915
+ }
916
+ /** @-file palette (B2): opens/refreshes from the input's trailing @token. */
917
+ refreshAtPal() {
918
+ const token = atToken(this.input);
919
+ if (token === null) {
920
+ if (this.atPal) {
921
+ this.atPal = null;
922
+ this.dirty = true;
923
+ }
924
+ return;
925
+ }
926
+ if (!this.atPal)
927
+ this.atPal = { query: token, results: [], sel: 0, token: 0, timer: null };
928
+ this.atPal.query = token;
929
+ if (this.atPal.timer)
930
+ clearTimeout(this.atPal.timer);
931
+ const tk = ++this.atPal.token;
932
+ this.atPal.timer = setTimeout(() => void this.runAtSearch(tk), 120);
933
+ }
934
+ async runAtSearch(tk) {
935
+ const pal = this.atPal;
936
+ if (!pal || pal.token !== tk)
937
+ return;
938
+ try {
939
+ const { fuzzyScore, SKIP_DIRS, MAX_SEARCH_DEPTH, MAX_SEARCH_ENTRIES, MAX_SEARCH_RESULTS } = await import('@hmharness/web');
940
+ const { readdir } = await import('node:fs/promises');
941
+ const { join: j } = await import('node:path');
942
+ const q = pal.query;
943
+ const root = process.cwd();
944
+ const hits = [];
945
+ let visited = 0;
946
+ const walk = async (dir, depth) => {
947
+ if (depth > MAX_SEARCH_DEPTH || visited >= MAX_SEARCH_ENTRIES)
948
+ return;
949
+ let entries;
950
+ try {
951
+ entries = await readdir(dir, { withFileTypes: true });
952
+ }
953
+ catch {
954
+ return;
955
+ }
956
+ for (const e of entries) {
957
+ if (visited >= MAX_SEARCH_ENTRIES)
958
+ return;
959
+ visited++;
960
+ if (e.isSymbolicLink())
961
+ continue;
962
+ const abs = j(dir, e.name);
963
+ if (e.isDirectory()) {
964
+ if (SKIP_DIRS.has(e.name))
965
+ continue;
966
+ await walk(abs, depth + 1);
967
+ continue;
968
+ }
969
+ if (!e.isFile())
970
+ continue;
971
+ const rel = abs.slice(root.length + 1).replace(/\\/g, '/');
972
+ const score = fuzzyScore(q, rel);
973
+ if (score >= 0)
974
+ hits.push({ rel, path: abs, score });
975
+ }
976
+ };
977
+ await walk(root, 0);
978
+ hits.sort((a, b) => b.score - a.score || a.rel.localeCompare(b.rel));
979
+ if (!this.atPal || this.atPal.token !== tk)
980
+ return;
981
+ this.atPal.results = hits.slice(0, MAX_SEARCH_RESULTS).map(({ rel, path }) => ({ rel, path }));
982
+ this.atPal.sel = 0;
983
+ this.dirty = true;
984
+ }
985
+ catch { /* search is best-effort; the palette just shows nothing */ }
986
+ }
987
+ atPalKey(data) {
988
+ const pal = this.atPal;
989
+ if (!pal)
990
+ return;
991
+ if (data === '\x1b') {
992
+ this.atPal = null;
993
+ this.dirty = true;
994
+ return;
995
+ }
996
+ if (data === '\r') {
997
+ const pick = pal.results[pal.sel];
998
+ if (pick) {
999
+ this.input = this.input.replace(/@[\w./\\-]*$/, '@' + pick.rel);
1000
+ this.caret = this.input.length;
1001
+ }
1002
+ this.atPal = null;
1003
+ this.dirty = true;
1004
+ return;
1005
+ }
1006
+ if (data === '\x1b[A') {
1007
+ pal.sel = Math.max(0, pal.sel - 1);
1008
+ this.dirty = true;
1009
+ return;
1010
+ }
1011
+ if (data === '\x1b[B') {
1012
+ pal.sel = Math.min(pal.results.length - 1, pal.sel + 1);
1013
+ this.dirty = true;
1014
+ return;
1015
+ }
1016
+ // printable/backspace edits the input line itself; the palette re-filters
1017
+ if (data === '\x7f' || data === '\b') {
1018
+ if (this.caret > 0) {
1019
+ this.input = this.input.slice(0, this.caret - 1) + this.input.slice(this.caret);
1020
+ this.caret--;
1021
+ }
1022
+ this.refreshAtPal();
1023
+ return;
1024
+ }
1025
+ if (data.length === 1 && data >= ' ') {
1026
+ this.input = this.input.slice(0, this.caret) + data + this.input.slice(this.caret);
1027
+ this.caret += data.length;
1028
+ this.refreshAtPal();
1029
+ return;
1030
+ }
1031
+ }
551
1032
  /* ---------------- keyboard ---------------- */
552
1033
  clearScreen() {
553
1034
  this.entries = [];
@@ -562,6 +1043,18 @@ export class TuiRuntime {
562
1043
  return n;
563
1044
  }
564
1045
  onKey(data) {
1046
+ // reassemble an SGR mouse report that arrived split across stdin chunks
1047
+ // (fast wheel bursts fragment in some terminals) before anything parses
1048
+ if (this.mousePending) {
1049
+ data = this.mousePending + data;
1050
+ this.mousePending = '';
1051
+ }
1052
+ const split = splitMouseReport(data);
1053
+ if (split.pending)
1054
+ this.mousePending = split.pending;
1055
+ if (!split.data)
1056
+ return;
1057
+ data = split.data;
565
1058
  // SS3 application-mode arrows (\x1bOA…H): terminals left in DECCKM by a
566
1059
  // previous program send these; normalize to the CSI forms this UI
567
1060
  // matches so navigation never silently dies
@@ -576,9 +1069,24 @@ export class TuiRuntime {
576
1069
  this.pickerInput(key);
577
1070
  return;
578
1071
  }
579
- // wheel-only mouse routing: 64 = wheel-up, 65 = wheel-down. With
580
- // button-event mode (1002) everything else - click, drag, release,
581
- // motion - still belongs to the terminal's native selection.
1072
+ // M2 modals own the keys while open (history search, transcript overlay,
1073
+ // @-file palette) — each closes on its own Esc
1074
+ if (this.histSearch) {
1075
+ this.histKey(data);
1076
+ return;
1077
+ }
1078
+ if (this.overlay) {
1079
+ this.overlayKey(data);
1080
+ return;
1081
+ }
1082
+ if (this.atPal) {
1083
+ this.atPalKey(data);
1084
+ return;
1085
+ }
1086
+ // wheel-only mouse routing: 64 = wheel-up, 65 = wheel-down. Reporting
1087
+ // is always on, so every other report - click, drag, release - is just
1088
+ // swallowed below; the terminal's Shift+click native selection bypasses
1089
+ // the app entirely and keeps working.
582
1090
  const wheel = parseWheel(data);
583
1091
  if (wheel !== 0) {
584
1092
  // an open palette takes the wheel: it moves the selection (the list
@@ -635,14 +1143,79 @@ export class TuiRuntime {
635
1143
  this.dirty = true;
636
1144
  return;
637
1145
  }
1146
+ // Ctrl+Enter = inject into the RUNNING task (T10; terminals send it as
1147
+ // '\n' in raw mode; consistent with web W7 Ctrl+Enter). Idle it behaves
1148
+ // exactly like Enter (submit). Key is remappable (B14).
1149
+ if (data === this.keymap.inject) {
1150
+ if (this.busy && this.input.trim()) {
1151
+ const text = this.input;
1152
+ this.input = '';
1153
+ this.caret = 0;
1154
+ this.cmdIdx = 0;
1155
+ this.dirty = true;
1156
+ this.injectFn?.(text);
1157
+ }
1158
+ else {
1159
+ this.pickHighlighted();
1160
+ }
1161
+ return;
1162
+ }
1163
+ // Ctrl+G = external editor for the draft (B12); key remappable (B14)
1164
+ if (data === this.keymap.externalEdit && !this.busy) {
1165
+ this.externalEditFn?.(this.input);
1166
+ return;
1167
+ }
1168
+ // Ctrl+R = incremental history search (B4); key remappable (B14)
1169
+ if (data === this.keymap.historySearch) {
1170
+ this.openHistSearch();
1171
+ return;
1172
+ }
1173
+ // Ctrl+T = full-transcript overlay (B5): every transcript line PLUS the
1174
+ // full (folded-away) tool outputs, via the driver-registered source;
1175
+ // key remappable (B14)
1176
+ if (data === this.keymap.transcript) {
1177
+ const lines = [];
1178
+ for (const e of this.entries)
1179
+ lines.push(...e.lines.map(stripAnsi));
1180
+ const extra = this.overlaySource();
1181
+ this.openOverlay(this.t.tuiTranscript, [...lines, ...extra]);
1182
+ return;
1183
+ }
1184
+ // remapped interrupt key (B14): a non-Esc binding still stops the turn
1185
+ if (data === this.keymap.interrupt && this.keymap.interrupt !== '\x1b' && this.busy) {
1186
+ this.interruptFn?.();
1187
+ return;
1188
+ }
638
1189
  if (data === '\x1b') {
639
- // Esc closes an open palette / discards the draft. Exact-match only:
640
- // arrow sequences arrive as one chunk ('\x1b[A') and never match.
1190
+ // Exact Esc only (arrow sequences arrive as '\x1b[A' and never match).
1191
+ // T9 order: an open modal closes FIRST; else running -> interrupt the
1192
+ // current task; else a non-empty draft is cleared (T7); else (idle +
1193
+ // empty) a second Esc within 800ms arms edit-and-fork (T13).
1194
+ if (this.closeModal())
1195
+ return;
1196
+ if (this.busy && this.keymap.interrupt === '\x1b') {
1197
+ this.interruptFn?.();
1198
+ return;
1199
+ }
641
1200
  if (this.input) {
642
1201
  this.input = '';
643
1202
  this.caret = 0;
644
1203
  this.cmdIdx = 0;
645
1204
  this.dirty = true;
1205
+ return;
1206
+ }
1207
+ const now = Date.now();
1208
+ if (forkArm(this.escAt, now, this.forkArmed)) {
1209
+ this.forkArmed = false;
1210
+ this.escAt = 0;
1211
+ if (this.lastUserMsg)
1212
+ this.forkEditFn?.();
1213
+ }
1214
+ else {
1215
+ this.forkArmed = true;
1216
+ this.escAt = now;
1217
+ this.status = this.t.forkArmed;
1218
+ this.dirty = true;
646
1219
  }
647
1220
  return;
648
1221
  }
@@ -778,6 +1351,12 @@ export class TuiRuntime {
778
1351
  this.dirty = true;
779
1352
  return;
780
1353
  }
1354
+ // M4 B8: `z` with an empty input expands/collapses the LAST tool cell
1355
+ // (folded summary <-> full output); with a draft it is just typing
1356
+ if (data === 'z' && !this.busy && !this.input) {
1357
+ if (this.toggleLastCell())
1358
+ return;
1359
+ }
781
1360
  if (data.startsWith('\x1b') || data < ' ')
782
1361
  return;
783
1362
  // printable text (CJK / IME preedit arrives as normal chunks)
@@ -785,6 +1364,8 @@ export class TuiRuntime {
785
1364
  this.caret += data.length;
786
1365
  this.cmdIdx = 0;
787
1366
  this.dirty = true;
1367
+ // '@' opens the file palette (B2); refreshAtPal() is a no-op otherwise
1368
+ this.refreshAtPal();
788
1369
  }
789
1370
  /* ---------------- rendering ---------------- */
790
1371
  render() {
@@ -799,9 +1380,23 @@ export class TuiRuntime {
799
1380
  this.flushFrame(frame, H);
800
1381
  return;
801
1382
  }
802
- // modal mouse reporting follows the palette (see syncMouseReporting);
1383
+ if (this.histSearch) {
1384
+ this.renderHistSearch(frame, W, H);
1385
+ this.flushFrame(frame, H);
1386
+ return;
1387
+ }
1388
+ if (this.overlay) {
1389
+ this.renderOverlay(frame, W, H);
1390
+ this.flushFrame(frame, H);
1391
+ return;
1392
+ }
1393
+ if (this.atPal) {
1394
+ this.renderAtPal(frame, W, H);
1395
+ this.flushFrame(frame, H);
1396
+ return;
1397
+ }
803
1398
  // click rows are re-recorded every frame because screen positions move
804
- this.syncMouseReporting();
1399
+ // (mouse reporting is always on - see the mouseReported field note)
805
1400
  this.paletteClickRows.length = 0;
806
1401
  const spin = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'[this.spinnerFrame] ?? ' ';
807
1402
  // Header = pure identity strip: logo · model · cwd · skills (+ mode tag
@@ -1042,41 +1637,181 @@ export async function tui(yes, noWeb = false, opts = {}) {
1042
1637
  // Task queue: new submissions during a running task are queued (not
1043
1638
  // rejected, not run concurrently — sequential execution preserves history
1044
1639
  // integrity). Slash commands still run immediately (they're quick).
1045
- // Codex-style interaction: ONE key does both jobs — Enter sends when there
1046
- // is text and STOPS the running task when the line is empty (the TUI
1047
- // equivalent of the send button that becomes a stop button). No `!` prefix,
1048
- // no /queue skip: the queue is visible in the busy hints line.
1640
+ // M2 running-interaction trio (T9/T10, codex parity):
1641
+ // Enter (text) = queue for the NEXT turn
1642
+ // Ctrl+Enter = INJECT into the running turn (web W7-consistent)
1643
+ // Esc (running) = interrupt the current turn (was: empty Enter = stop —
1644
+ // reversed by 复案 2026-09-17, see DESIGNS.md)
1049
1645
  const taskQueue = [];
1050
1646
  let taskRunning = false;
1051
1647
  let currentAbort = null;
1648
+ /** live steering channel: Ctrl+Enter pushes here; runAgentTask drains it
1649
+ * into the running loop (InjectChannel shape) */
1650
+ let currentInject = null;
1651
+ /** full tool outputs retained for the Ctrl+T transcript overlay (B5) —
1652
+ * the transcript itself folds them to one line (W1/T5 spirit) */
1653
+ const fullToolLog = [];
1654
+ /** set by Esc-Esc edit-and-fork (T13): the next submission forks a new
1655
+ * session from the edited message (kernel forkFrom provenance) */
1656
+ let pendingFork = false;
1657
+ /** /fork (M4 B7): fork with the FULL history as resume (no edit point) */
1658
+ let forkAll = false;
1659
+ /** /plan (M4 B7): the next task gets a plan-first system directive */
1660
+ let planMode = false;
1661
+ /** /copy source: the last completed assistant text */
1662
+ let lastAiText = '';
1663
+ async function runShellBang(cmd) {
1664
+ // B3: `! command` runs the local shell through the SAME gate as the
1665
+ // agent's run_command tool — DENY_PATTERNS hard-refuse destructive
1666
+ // one-liners inside the tool; the TUI approval dialog stands in for the
1667
+ // loop's ask() (never a bypass; hard constraint #5).
1668
+ rt.addUser('!' + cmd);
1669
+ const tool = reg.get('run_command');
1670
+ if (!tool) {
1671
+ rt.addText('run_command tool missing', 'err');
1672
+ return;
1673
+ }
1674
+ const args = { command: cmd };
1675
+ // the tool's own gate decides (DENY_PATTERNS + shellgate live INSIDE
1676
+ // run_command.execute); the TUI dialog stands in for the loop's ask(),
1677
+ // except in YOLO/auto mode where approval is pre-granted
1678
+ if (tool.needsApproval?.(args, { cwd: process.cwd(), home }) && !autoApprove) {
1679
+ const ok = await rt.requestApproval('run_command', args);
1680
+ if (!ok) {
1681
+ rt.addText(DIM('denied'));
1682
+ return;
1683
+ }
1684
+ }
1685
+ const r = await tool.execute(args, { cwd: process.cwd(), home });
1686
+ const first = String(r.output).split('\n').find((l) => l.trim()) ?? '';
1687
+ rt.addText(` ${r.isError ? RED('✗') : GREEN('•')} ${DIM('⎿ ' + first.trim().slice(0, 120))}`, r.isError ? 'err' : 'dim');
1688
+ const rest = String(r.output).split('\n').slice(1).join('\n').trim();
1689
+ if (rest)
1690
+ rt.addText(rest.slice(0, 2000), 'dim');
1691
+ fullToolLog.push({ name: 'shell', output: String(r.output).slice(0, 4000) });
1692
+ }
1052
1693
  rt.onSubmit(() => {
1053
1694
  const line = rt.consumeInput().trim();
1054
1695
  if (!line) {
1055
- // empty Enter while running = stop (interrupts the current task;
1056
- // queued tasks still run — clear them first with /queue clear if not)
1057
- if (taskRunning) {
1058
- currentAbort?.abort();
1059
- rt.addText('⏹ interrupting current task (in-flight tool calls finish first; queued tasks still run)', 'dim');
1060
- }
1696
+ // 复案 (T10): empty Enter no longer stops the running task. Stopping
1697
+ // is now an explicit Esc (T9). An empty Enter while running is a nudge.
1698
+ if (taskRunning)
1699
+ rt.addText(DIM('(empty — Esc stops · type + Enter queues · Ctrl+Enter injects)'));
1061
1700
  return;
1062
1701
  }
1063
1702
  if (line.startsWith('/')) {
1064
1703
  void handleLine(line);
1065
1704
  return;
1066
1705
  }
1706
+ if (shellBang(line) !== null) {
1707
+ void runShellBang(shellBang(line));
1708
+ return;
1709
+ }
1710
+ rt.setLastUserText(line);
1067
1711
  if (taskRunning) {
1068
1712
  taskQueue.push(line);
1069
1713
  rt.setQueued(taskQueue.length);
1070
1714
  rt.addText(`📋 queued: "${line.slice(0, 60)}${line.length > 60 ? '…' : ''}" (${taskQueue.length} waiting)`, 'dim');
1071
1715
  return;
1072
1716
  }
1073
- void executeTaskQueue(line);
1717
+ // Esc-Esc fork (T13): the new thread inherits everything BEFORE the last
1718
+ // user message (the edited line replaces it) and records the parent
1719
+ // session id in its rollout meta (kernel forkFrom). /fork (M4 B7): the
1720
+ // FULL history is the resume (no edit point).
1721
+ const forkFrom = pendingFork ? currentSessionId : undefined;
1722
+ const forkResume = pendingFork
1723
+ ? (forkAll ? history : history.slice(0, lastUserIdx(history)))
1724
+ : undefined;
1725
+ pendingFork = false;
1726
+ forkAll = false;
1727
+ void executeTaskQueue(line, forkFrom, forkResume);
1728
+ });
1729
+ rt.onInterrupt(() => {
1730
+ // T9: Esc while running interrupts the current turn. In-flight tool calls
1731
+ // finish first; queued tasks still run (clear with /queue clear).
1732
+ if (taskRunning && currentAbort) {
1733
+ currentAbort.abort();
1734
+ rt.addText('⏹ interrupting current task (in-flight tool calls finish first; queued tasks still run)', 'dim');
1735
+ }
1074
1736
  });
1075
- async function executeTaskQueue(firstTask) {
1737
+ rt.onInject((text) => {
1738
+ // T10: Ctrl+Enter injects into the RUNNING task (no-op when idle — the
1739
+ // key submits normally in that case)
1740
+ if (currentInject?.active) {
1741
+ currentInject.queue.push(text);
1742
+ rt.addText(`⤷ injected into running task: "${text.slice(0, 80)}"`, 'dim');
1743
+ }
1744
+ });
1745
+ rt.onForkEdit(() => {
1746
+ // T13: Esc Esc (idle + empty) loads the last user message for editing;
1747
+ // the next submit forks a new session from it
1748
+ const last = rt.getLastUserText();
1749
+ if (last) {
1750
+ pendingFork = true;
1751
+ rt.setInput(last);
1752
+ rt.addText(DIM('✂ edit and fork — Enter sends as a NEW session from this message'), 'dim');
1753
+ }
1754
+ });
1755
+ // B12: Ctrl+G hands the draft to an external editor ($EDITOR, notepad on
1756
+ // Windows); the edited text comes back into the input box
1757
+ rt.onExternalEdit(async (draft) => {
1758
+ try {
1759
+ const { mkdir, writeFile, readFile } = await import('node:fs/promises');
1760
+ const { join: j } = await import('node:path');
1761
+ const dir = j(home, 'tmp');
1762
+ await mkdir(dir, { recursive: true });
1763
+ const file = j(dir, `draft-${Date.now()}.txt`);
1764
+ await writeFile(file, draft, 'utf8');
1765
+ const { spawn } = await import('node:child_process');
1766
+ const editor = process.env.EDITOR || (process.platform === 'win32' ? 'notepad' : 'vi');
1767
+ await new Promise((resolve) => {
1768
+ const child = spawn(editor, process.platform === 'win32' ? [file] : [file], { windowsHide: false, stdio: 'inherit' });
1769
+ child.on('close', () => resolve());
1770
+ });
1771
+ const edited = await readFile(file, 'utf8');
1772
+ rt.setInput(edited);
1773
+ rt.addText(DIM(`✎ external editor (${editor}) → draft loaded (${edited.length} chars)`), 'dim');
1774
+ }
1775
+ catch (err) {
1776
+ rt.addText(String(err), 'err');
1777
+ }
1778
+ });
1779
+ // B14: remapped keys from config.json tui.keymap (applied at startup)
1780
+ {
1781
+ const km = cfg.tui?.keymap;
1782
+ if (km && typeof km === 'object')
1783
+ rt.setKeymap(km);
1784
+ }
1785
+ // B11: customizable idle statusline from config.json tui.statusline
1786
+ const applyStatusline = () => {
1787
+ const tpl = cfg.tui?.statusline ?? '';
1788
+ if (tpl) {
1789
+ rt.setStatus(renderStatusline(tpl, {
1790
+ model: chatModel,
1791
+ cwd: basename(process.cwd()),
1792
+ skills: skills.length,
1793
+ mode: autoApprove ? 'yolo' : cfg.approval === 'auto' ? 'auto' : 'ask',
1794
+ queue: taskQueue.length,
1795
+ version: HMH_VERSION,
1796
+ }));
1797
+ }
1798
+ };
1799
+ applyStatusline();
1800
+ // Ctrl+T overlay source: transcript + FULL (folded-away) tool outputs (B5)
1801
+ rt.setOverlaySource(() => {
1802
+ const out = [];
1803
+ for (const t of fullToolLog) {
1804
+ out.push('', `── ${t.name} ──`, t.output);
1805
+ }
1806
+ return out;
1807
+ });
1808
+ async function executeTaskQueue(firstTask, forkFrom, forkResume) {
1076
1809
  taskRunning = true;
1077
1810
  let task = firstTask;
1811
+ let first = true;
1078
1812
  while (task) {
1079
- await runSingleTask(task);
1813
+ await runSingleTask(task, first ? forkFrom : undefined, first ? forkResume : undefined);
1814
+ first = false;
1080
1815
  task = taskQueue.shift();
1081
1816
  rt.setQueued(taskQueue.length);
1082
1817
  if (task)
@@ -1084,10 +1819,17 @@ export async function tui(yes, noWeb = false, opts = {}) {
1084
1819
  }
1085
1820
  taskRunning = false;
1086
1821
  }
1087
- async function runSingleTask(line) {
1822
+ async function runSingleTask(line, forkFrom, forkResume) {
1088
1823
  rt.addUser(line);
1089
1824
  rt.setBusy(true, t.running);
1090
1825
  currentAbort = new AbortController();
1826
+ const injectCh = { queue: [], active: false };
1827
+ currentInject = injectCh;
1828
+ // /plan (M4 B7): a plan-first system directive rides ahead of the resume
1829
+ const planDirective = planMode
1830
+ ? [{ role: 'system', content: '[plan mode] Before ANY tool use, present a concrete plan (2-5 numbered steps). Then STOP and wait for the user to confirm before executing. Only execute after explicit confirmation.' }]
1831
+ : [];
1832
+ const resumeBase = [...planDirective, ...(forkResume ?? history)];
1091
1833
  let appender = null;
1092
1834
  let kind = null;
1093
1835
  try {
@@ -1096,9 +1838,14 @@ export async function tui(yes, noWeb = false, opts = {}) {
1096
1838
  registry: reg,
1097
1839
  cfg,
1098
1840
  yes: autoApprove,
1099
- resumeMessages: history,
1100
- sessionId: currentSessionId,
1841
+ resumeMessages: resumeBase,
1842
+ sessionId: forkResume !== undefined ? undefined : currentSessionId,
1101
1843
  signal: currentAbort.signal,
1844
+ // M2 runtime steering: Ctrl+Enter pushes here; the runner drains it
1845
+ // between tool batches and the injected text lands as a user message
1846
+ inject: injectCh,
1847
+ // Esc-Esc fork (T13): the new rollout records the parent session id
1848
+ ...(forkFrom ? { forkFrom } : {}),
1102
1849
  approvalAsk: (name, args) => rt.requestApproval(name, args),
1103
1850
  events: {
1104
1851
  onLine: (l) => { if (kind === 'reasoning')
@@ -1132,17 +1879,37 @@ export async function tui(yes, noWeb = false, opts = {}) {
1132
1879
  onToolResult: (name, output, isError) => {
1133
1880
  const dot = isError ? RED('✗') : GREEN('•');
1134
1881
  const first = output.split('\n').find((l) => l.trim()) ?? '';
1135
- rt.addText(` ${dot} ${DIM('⎿ ' + first.trim().slice(0, 100))}`);
1882
+ // M4 B8: tool call + result = one collapsible cell (folded summary
1883
+ // by default; `z` with an empty input expands the last one)
1884
+ rt.addToolCell(` ${dot} ${CYAN(name)} ${DIM('⎿ ' + first.trim().slice(0, 100))}`, output);
1885
+ // M4 B9: outputs far beyond a screen auto-enter the pager overlay
1886
+ // (the user can always q/Esc back to the stream)
1887
+ if (output.split('\n').length > 2 * Math.max(20, (stdout.rows || 30))) {
1888
+ rt.showOverlay(`${name} output (${output.split('\n').length} lines)`, output.split('\n'));
1889
+ }
1890
+ // retain the FULL output for the Ctrl+T transcript overlay (B5);
1891
+ // the transcript itself keeps only the folded first line
1892
+ fullToolLog.push({ name, output: output.slice(0, 4000) });
1893
+ if (fullToolLog.length > 100)
1894
+ fullToolLog.splice(0, fullToolLog.length - 100);
1895
+ },
1896
+ onInjected: (message) => {
1897
+ rt.addText(`⤷ injected: "${message.slice(0, 80)}"`, 'dim');
1136
1898
  },
1137
1899
  },
1138
1900
  });
1139
1901
  rt.setBusy(false);
1140
1902
  currentSessionId = result.sessionId;
1903
+ currentInject = null;
1904
+ lastAiText = result.text || lastAiText;
1141
1905
  rt.setStatus(`↑${result.usage.promptTokens} ↓${result.usage.completionTokens} tok · ${result.turns} turns · ${result.toolUses} tools`);
1142
- history = [...history, { role: 'user', content: line }, ...result.messages.slice(history.length + 2)];
1906
+ // the plan directive rides in resumeBase but is NOT part of the thread:
1907
+ // history keeps only real messages (the next task re-applies it)
1908
+ history = [...(forkResume ?? history), { role: 'user', content: line }, ...result.messages.slice(resumeBase.length + 2)];
1143
1909
  }
1144
1910
  catch (err) {
1145
1911
  rt.setBusy(false);
1912
+ currentInject = null;
1146
1913
  rt.addText(String(err), 'err');
1147
1914
  }
1148
1915
  finally {
@@ -1166,9 +1933,7 @@ export async function tui(yes, noWeb = false, opts = {}) {
1166
1933
  const MAX_RENDER = 80;
1167
1934
  const msgs = tr.messages;
1168
1935
  const skipped = Math.max(0, msgs.length - MAX_RENDER);
1169
- rt.addText('--- resumed ' + tr.id + ' · ' + msgs.length + ' messages'
1170
- + (skipped > 0 ? ' (' + skipped + ' earlier kept in context, not shown)' : '')
1171
- + ' ---', 'dim');
1936
+ rt.addText(t.cmdResuming(tr.id, msgs.length, skipped), 'dim');
1172
1937
  for (const m of (skipped > 0 ? msgs.slice(skipped) : msgs)) {
1173
1938
  const text = typeof m.content === 'string' ? m.content : '';
1174
1939
  if (m.role === 'user') {
@@ -1214,7 +1979,7 @@ export async function tui(yes, noWeb = false, opts = {}) {
1214
1979
  const queueList = taskQueue.length > 0
1215
1980
  ? taskQueue.map((task, i) => ' ' + (i + 1) + '. ' + task.slice(0, 70)).join('\n')
1216
1981
  : ' (empty)';
1217
- rt.addText('queue: ' + status + ' | ' + taskQueue.length + ' waiting\n' + queueList + '\n\nempty Enter = stop current · typed Enter = queue · /queue clear = drop all', 'dim');
1982
+ rt.addText('queue: ' + status + ' | ' + taskQueue.length + ' waiting\n' + queueList + '\n\nEsc = stop current · type+Enter = queue · Ctrl+Enter = inject · /queue clear = drop all', 'dim');
1218
1983
  return;
1219
1984
  }
1220
1985
  if (line === '?' || line === '/help') {
@@ -1229,6 +1994,210 @@ export async function tui(yes, noWeb = false, opts = {}) {
1229
1994
  currentSessionId = undefined;
1230
1995
  return;
1231
1996
  }
1997
+ if (line === '/new') {
1998
+ rt.clearScreen();
1999
+ history = [];
2000
+ currentSessionId = undefined;
2001
+ pendingFork = false;
2002
+ forkAll = false;
2003
+ rt.addText(DIM(t.cmdNewDone));
2004
+ return;
2005
+ }
2006
+ if (line === '/compact') {
2007
+ // M4 B7: compact the in-memory resume with the adaptive budget and
2008
+ // report the delta (honest: it affects the NEXT turn's context)
2009
+ const before = transcriptChars(history);
2010
+ const budget = adaptiveContextChars(cfg.provider);
2011
+ history = compactMessages(history, budget);
2012
+ const after = transcriptChars(history);
2013
+ rt.addText(`context: ${before.toLocaleString()} → ${after.toLocaleString()} chars (freed ${(before - after).toLocaleString()}; budget ${budget.toLocaleString()})`, 'dim');
2014
+ return;
2015
+ }
2016
+ if (line === '/diff') {
2017
+ // M4 B7: pager-view the worktree git diff (incl. untracked) via the
2018
+ // B5 overlay base
2019
+ rt.setBusy(true, '/diff');
2020
+ try {
2021
+ const { execFile } = await import('node:child_process');
2022
+ const { promisify } = await import('node:util');
2023
+ const run = promisify(execFile);
2024
+ const g = (a, mb) => run('git', a, { cwd: process.cwd(), windowsHide: true, maxBuffer: mb }).then((r) => String(r.stdout)).catch(() => '');
2025
+ const [st, df, un] = await Promise.all([
2026
+ g(['status', '--porcelain'], 4 * 1024 * 1024),
2027
+ g(['diff'], 8 * 1024 * 1024),
2028
+ g(['ls-files', '--others', '--exclude-standard'], 4 * 1024 * 1024),
2029
+ ]);
2030
+ const lines = [
2031
+ '── git status ──',
2032
+ ...(st.split('\n').filter(Boolean) || ['(clean)']),
2033
+ '',
2034
+ '── git diff ──',
2035
+ ...(df.split('\n') || ['(no tracked changes)']),
2036
+ '',
2037
+ '── untracked ──',
2038
+ ...(un.split('\n').filter(Boolean).slice(0, 60) || ['(none)']),
2039
+ ];
2040
+ rt.showOverlay(t.cmdDiff, lines);
2041
+ }
2042
+ catch (err) {
2043
+ rt.addText(String(err), 'err');
2044
+ }
2045
+ finally {
2046
+ rt.setBusy(false);
2047
+ }
2048
+ return;
2049
+ }
2050
+ if (line === '/fork') {
2051
+ // M4 B7: fork the CURRENT thread to a new session — the next task
2052
+ // resumes the FULL history and records forkFrom provenance
2053
+ if (!currentSessionId && history.length === 0) {
2054
+ rt.addText('nothing to fork yet', 'dim');
2055
+ return;
2056
+ }
2057
+ pendingFork = true;
2058
+ forkAll = true;
2059
+ rt.addText(DIM('✂ next task runs as a NEW session (forked' + (currentSessionId ? ' from ' + currentSessionId : '') + ' — full context inherited)'));
2060
+ return;
2061
+ }
2062
+ if (line === '/copy') {
2063
+ // M4 B7: last AI output -> clipboard (Windows clip / mac pbcopy /
2064
+ // linux xclip fallback chain; zero deps, stdin-fed)
2065
+ if (!lastAiText) {
2066
+ rt.addText('(no AI output yet to copy)', 'dim');
2067
+ return;
2068
+ }
2069
+ try {
2070
+ const { spawn } = await import('node:child_process');
2071
+ const bin = process.platform === 'win32' ? 'clip'
2072
+ : process.platform === 'darwin' ? 'pbcopy'
2073
+ : 'xclip';
2074
+ const args = bin === 'xclip' ? ['-selection', 'clipboard'] : [];
2075
+ const child = spawn(bin, args, { windowsHide: true, stdio: ['pipe', 'ignore', 'ignore'] });
2076
+ child.stdin.write(lastAiText);
2077
+ child.stdin.end();
2078
+ await new Promise((r) => child.on('close', r));
2079
+ rt.addText(GREEN('✓') + ' ' + t.cmdCopied, 'plain');
2080
+ }
2081
+ catch {
2082
+ rt.addText('(clipboard tool unavailable — output follows)\n' + lastAiText.slice(0, 2000), 'dim');
2083
+ }
2084
+ return;
2085
+ }
2086
+ if (line === '/plan' || line.startsWith('/plan ')) {
2087
+ // M4 B7: plan mode toggle (the directive is injected per-task, so the
2088
+ // agent always presents a plan and waits for confirmation first)
2089
+ planMode = !planMode;
2090
+ rt.addText(planMode ? GREEN('🔥') + ' ' + t.cmdPlanOn : t.cmdPlanOff, 'plain');
2091
+ return;
2092
+ }
2093
+ if (line === '/goal' || line.startsWith('/goal ')) {
2094
+ // M4 B7: session goal (shared storage with web A6 — kernel/goal.ts)
2095
+ const arg = line.slice(6).trim();
2096
+ const key = currentSessionId ?? 'web';
2097
+ try {
2098
+ if (!arg) {
2099
+ const g = await getGoal(home, key);
2100
+ rt.addText(g ? `goal: ${g}` : '(no goal set — /goal <text> to set)', 'dim');
2101
+ }
2102
+ else if (arg === 'clear') {
2103
+ await clearGoal(home, key);
2104
+ rt.addText(t.cmdGoalCleared, 'dim');
2105
+ }
2106
+ else {
2107
+ await setGoal(home, key, arg);
2108
+ rt.addText(GREEN('✓') + ` goal set (session ${key.slice(0, 8)}…)`, 'plain');
2109
+ }
2110
+ }
2111
+ catch (err) {
2112
+ rt.addText(String(err), 'err');
2113
+ }
2114
+ return;
2115
+ }
2116
+ if (line === '/usage') {
2117
+ // M4 B7: session context occupancy (the resume the model will see)
2118
+ const chars = transcriptChars(history);
2119
+ const budget = adaptiveContextChars(cfg.provider);
2120
+ rt.addText(`context: ${chars.toLocaleString()} chars (~${Math.ceil(chars / 4).toLocaleString()} tok) of ${budget.toLocaleString()} budget (${Math.round((chars / budget) * 100)}%)`, 'dim');
2121
+ return;
2122
+ }
2123
+ if (line === '/statusline' || line.startsWith('/statusline ')) {
2124
+ // M5 B11: customize the idle statusline ({model} {cwd} {skills} {mode}
2125
+ // {queue} {version}); persisted under config.json tui.statusline
2126
+ const arg = line.slice(12).trim();
2127
+ const cur = cfg.tui?.statusline ?? '';
2128
+ if (!arg) {
2129
+ rt.addText(cur ? `statusline: "${cur}"` : '(no custom statusline — /statusline "{model} · {cwd}" to set; placeholders: model cwd skills mode queue version)', 'dim');
2130
+ return;
2131
+ }
2132
+ try {
2133
+ const { patchConfig } = await import('@hmharness/kernel');
2134
+ const merged = { ...(cfg.tui ?? {}), statusline: arg };
2135
+ const fresh = await patchConfig({ tui: merged });
2136
+ cfg = fresh;
2137
+ applyStatusline();
2138
+ rt.addText(GREEN('✓') + ` statusline: "${arg}"`, 'plain');
2139
+ }
2140
+ catch (err) {
2141
+ rt.addText(String(err), 'err');
2142
+ }
2143
+ return;
2144
+ }
2145
+ if (line === '/keymap' || line.startsWith('/keymap ')) {
2146
+ // M5 B14: show / remap the M2/M4 action keys (config.json tui.keymap)
2147
+ const arg = line.slice(8).trim();
2148
+ if (!arg) {
2149
+ const km = cfg.tui?.keymap ?? {};
2150
+ const rows = Object.entries(KEYMAP_DEFAULTS).map(([a, d]) => {
2151
+ const v = km[a] ?? d;
2152
+ const pretty = v === '\x1b' ? 'esc' : v === '\x0a' ? 'ctrl+enter' : v === '\x12' ? 'ctrl+r' : v === '\x14' ? 'ctrl+t' : v === '\x07' ? 'ctrl+g' : JSON.stringify(v);
2153
+ return ` ${a.padEnd(14)} ${pretty}`;
2154
+ });
2155
+ rt.addText('keymap (defaults in parens):\n' + rows.join('\n') + '\n\n/keymap <action>=<key> — e.g. /keymap inject=ctrl+j', 'dim');
2156
+ return;
2157
+ }
2158
+ const eq = arg.indexOf('=');
2159
+ if (eq <= 0) {
2160
+ rt.addText('usage: /keymap <action>=<key> (actions: ' + Object.keys(KEYMAP_DEFAULTS).join(' ') + ')', 'err');
2161
+ return;
2162
+ }
2163
+ const action = arg.slice(0, eq).trim();
2164
+ const spec = arg.slice(eq + 1).trim();
2165
+ if (!(action in KEYMAP_DEFAULTS)) {
2166
+ rt.addText(`unknown action "${action}" (actions: ${Object.keys(KEYMAP_DEFAULTS).join(' ')})`, 'err');
2167
+ return;
2168
+ }
2169
+ const byte = parseKeySpec(spec);
2170
+ if (byte === null) {
2171
+ rt.addText(`unknown key "${spec}" (try: esc, ctrl+r, ctrl+t, ctrl+j, ctrl+g, ctrl+p, ctrl+n, tab, enter, or a single char)`, 'err');
2172
+ return;
2173
+ }
2174
+ try {
2175
+ const { patchConfig } = await import('@hmharness/kernel');
2176
+ const prev = cfg.tui?.keymap ?? {};
2177
+ const merged = { ...(cfg.tui ?? {}), keymap: { ...prev, [action]: byte } };
2178
+ const fresh = await patchConfig({ tui: merged });
2179
+ cfg = fresh;
2180
+ rt.setKeymap({ ...prev, [action]: byte });
2181
+ rt.addText(GREEN('✓') + ` ${action} → ${spec}`, 'plain');
2182
+ }
2183
+ catch (err) {
2184
+ rt.addText(String(err), 'err');
2185
+ }
2186
+ return;
2187
+ }
2188
+ if (line === '/review') {
2189
+ // M4 B7: one-click "review the current worktree" task template
2190
+ const reviewTask = 'Review the current worktree: run git status and inspect the diffs, then identify bugs, risks, regressions, and missing tests. Report findings ordered by severity with file:line references. Do NOT modify any files.';
2191
+ if (taskRunning) {
2192
+ taskQueue.push(reviewTask);
2193
+ rt.setQueued(taskQueue.length);
2194
+ rt.addText(`📋 queued: "review the worktree" (${taskQueue.length} waiting)`, 'dim');
2195
+ }
2196
+ else {
2197
+ void executeTaskQueue(reviewTask);
2198
+ }
2199
+ return;
2200
+ }
1232
2201
  if (line === '/status') {
1233
2202
  rt.setStatus(t.tuiStatus(cfg.locale ?? 'zh', skills.length, chatModel));
1234
2203
  return;
@@ -1266,7 +2235,7 @@ export async function tui(yes, noWeb = false, opts = {}) {
1266
2235
  // the screen with a running task's streaming output.
1267
2236
  if (!arg) {
1268
2237
  if (taskRunning) {
1269
- rt.addText('task running - stop it first (empty Enter), then /resume', 'dim');
2238
+ rt.addText('task running - Esc to stop, then /resume', 'dim');
1270
2239
  return;
1271
2240
  }
1272
2241
  const pick = await rt.openResumePicker();
@@ -1415,7 +2384,7 @@ export async function tui(yes, noWeb = false, opts = {}) {
1415
2384
  provider: cfg.provider,
1416
2385
  runCase: async (c) => {
1417
2386
  if (c.tools)
1418
- return '(skipped in tui; run hmh evolve)';
2387
+ return t.cmdEvolveHint;
1419
2388
  const r = await chat(cfg.provider, [{ role: 'user', content: c.prompt }]);
1420
2389
  return r.message.content ?? '';
1421
2390
  },