@hmharness/cli 0.14.7 → 0.14.9

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.
@@ -183,6 +273,26 @@ export class TuiRuntime {
183
273
  /** screen row of each visible palette item (SGR click hit-testing); the
184
274
  * render loop records row = frame.length (1-based) as it pushes rows */
185
275
  paletteClickRows = [];
276
+ /* ---------------- M2: runtime steering modals (codex parity) ---------------- */
277
+ /** Ctrl+R incremental history search: { query, matches (history indices), sel } */
278
+ histSearch = null;
279
+ /** Ctrl+T full-transcript overlay (also the pager base for B9): title + lines + viewport top */
280
+ overlay = null;
281
+ /** @-file palette (codex @ fuzzy reference): trailing @token query + ranked hits */
282
+ atPal = null;
283
+ /** double-Esc fork-edit arming (T13): timestamp of the first bare Esc */
284
+ escAt = 0;
285
+ forkArmed = false;
286
+ /** driver callbacks for the running-interaction trio (T9/T10) */
287
+ interruptFn = null;
288
+ injectFn = null;
289
+ forkEditFn = null;
290
+ /** M5 B12: Ctrl+G hands the draft to an external editor ($EDITOR/notepad) */
291
+ externalEditFn = null;
292
+ /** M5 B14: remappable key bindings (config.json tui.keymap) */
293
+ keymap = { ...KEYMAP_DEFAULTS };
294
+ /** last user-submitted line, for Esc-Esc edit-and-fork (T13) */
295
+ lastUserMsg = '';
186
296
  constructor() {
187
297
  // ?1l forces DECCKM OFF so arrow keys arrive as CSI (\x1b[A) even if a
188
298
  // previous program left the terminal in application cursor mode - in
@@ -316,6 +426,64 @@ export class TuiRuntime {
316
426
  const posLine = t.pickerPos(pos, vis.length, vis.length ? String(Math.round((pos / vis.length) * 100)) : '0');
317
427
  frame.push(' '.repeat(Math.max(0, W - posLine.length - 1)) + DIM(posLine));
318
428
  }
429
+ /** Ctrl+R history-search modal (B4): query line + matching entries,
430
+ * newest first; Enter adopts, Esc closes, ^P/^N or arrows move. */
431
+ renderHistSearch(frame, W, H) {
432
+ const hs = this.histSearch;
433
+ const t = this.t;
434
+ frame.push(truncateTo(BOLD(' ⌕ ' + t.histSearchTitle) + DIM(` ${hs.matches.length}`), W));
435
+ frame.push(DIM('─'.repeat(W)));
436
+ frame.push(truncateTo(' ' + (hs.query || DIM(t.histSearchNone)), W - 1));
437
+ frame.push(DIM('─'.repeat(W)));
438
+ const listH = Math.max(3, H - 5);
439
+ const vis = hs.matches;
440
+ for (let i = 0; i < listH && i < vis.length; i++) {
441
+ const sel = i === hs.sel;
442
+ const line = this.history[vis[i]] ?? '';
443
+ const plain = truncateTo((i + 1) + '. ' + line, W - 1);
444
+ frame.push(sel ? '\x1b[7m' + plain + ' '.repeat(Math.max(0, W - 1 - strWidth(plain))) + '\x1b[27m' : ' ' + plain);
445
+ }
446
+ if (vis.length === 0)
447
+ frame.push(DIM(' ' + t.histSearchNone));
448
+ frame.push(DIM('─'.repeat(W)));
449
+ frame.push(DIM(truncateTo(' ' + t.histSearchHint, W - 1)));
450
+ }
451
+ /** Ctrl+T full-transcript overlay (B5): title + scrollable lines; also the
452
+ * pager base for long outputs (B9). q/Esc closes, ↑↓/PgUp/PgDn/g/G scroll. */
453
+ renderOverlay(frame, W, H) {
454
+ const ov = this.overlay;
455
+ const t = this.t;
456
+ const listH = Math.max(5, H - 3);
457
+ frame.push(truncateTo(BOLD(' ' + ov.title) + DIM(` ${ov.lines.length}`), W));
458
+ frame.push(DIM('─'.repeat(W)));
459
+ if (ov.lines.length === 0)
460
+ frame.push(DIM(' (empty)'));
461
+ for (let i = 0; i < listH && ov.top + i < ov.lines.length; i++) {
462
+ frame.push(truncateTo(ov.lines[ov.top + i] || ' ', W - 1));
463
+ }
464
+ frame.push(DIM('─'.repeat(W)));
465
+ frame.push(DIM(truncateTo(' ' + t.overlayHint, W - 1)));
466
+ }
467
+ /** @-file palette (B2): ranked workspace hits for the trailing @token.
468
+ * Enter inserts the path; Esc closes; arrows move. */
469
+ renderAtPal(frame, W, H) {
470
+ const pal = this.atPal;
471
+ const t = this.t;
472
+ const title = BOLD(' @ ') + DIM('/' + pal.query + (pal.results.length ? ` · ${pal.results.length}` : ''));
473
+ frame.push(truncateTo(title, W));
474
+ frame.push(DIM('─'.repeat(W)));
475
+ const listH = Math.min(8, Math.max(3, H - 6));
476
+ if (pal.results.length === 0) {
477
+ frame.push(DIM(' ' + t.histSearchNone));
478
+ }
479
+ for (let i = 0; i < listH && i < pal.results.length; i++) {
480
+ const sel = i === pal.sel;
481
+ const plain = truncateTo(' ' + pal.results[i].rel, W - 1);
482
+ frame.push(sel ? '\x1b[7m' + plain + ' '.repeat(Math.max(0, W - 1 - strWidth(plain))) + '\x1b[27m' : plain);
483
+ }
484
+ frame.push(DIM('─'.repeat(W)));
485
+ frame.push(DIM(truncateTo(' ' + t.atPalHint, W - 1)));
486
+ }
319
487
  /** Run the highlighted palette row (shared by Enter and palette clicks);
320
488
  * with no palette open it just submits the typed input. */
321
489
  pickHighlighted() {
@@ -467,7 +635,15 @@ export class TuiRuntime {
467
635
  if (kind === 'say') {
468
636
  const wrapped = wrapTo(buf, width);
469
637
  lines.length = 0;
470
- wrapped.forEach((l) => lines.push(l));
638
+ // B10: completed lines get markdown color ONCE; the in-progress tail
639
+ // stays raw until it wraps — stable rows never reflow
640
+ const lastIdx = wrapped.length - 1;
641
+ for (let i = 0; i < lastIdx; i++)
642
+ lines.push(TuiRuntime.mdColor(wrapped[i]));
643
+ if (wrapped.length) {
644
+ const last = wrapped[lastIdx];
645
+ lines.push(buf.endsWith('\n') ? TuiRuntime.mdColor(last) : last);
646
+ }
471
647
  }
472
648
  else {
473
649
  // thinking stays FOLDED while streaming: one live line (what Claude
@@ -545,9 +721,303 @@ export class TuiRuntime {
545
721
  this.dirty = true;
546
722
  return line;
547
723
  }
724
+ setInput(text) {
725
+ this.input = text;
726
+ this.caret = text.length;
727
+ this.cmdIdx = 0;
728
+ this.dirty = true;
729
+ }
730
+ setLastUserText(s) {
731
+ this.lastUserMsg = s;
732
+ }
733
+ /** Last user-submitted line (Esc-Esc edit-and-fork source, T13). */
734
+ getLastUserText() {
735
+ return this.lastUserMsg;
736
+ }
548
737
  onSubmit(fn) {
549
738
  this.driver = fn;
550
739
  }
740
+ /* ---------------- M2 runtime steering API (driver wiring) ---------------- */
741
+ onInterrupt(fn) { this.interruptFn = fn; }
742
+ onInject(fn) { this.injectFn = fn; }
743
+ onForkEdit(fn) { this.forkEditFn = fn; }
744
+ onExternalEdit(fn) { this.externalEditFn = fn; }
745
+ /** M5 B14: apply remapped keys (config.json tui.keymap); unknown actions
746
+ * are ignored so a stale config degrades to defaults, never breaks keys */
747
+ setKeymap(map) {
748
+ this.keymap = { ...KEYMAP_DEFAULTS, ...map };
749
+ }
750
+ /** Close any open modal (Esc priority: panels close before anything else,
751
+ * T7/T9 order). Returns true when something was open. */
752
+ closeModal() {
753
+ if (this.histSearch) {
754
+ this.histSearch = null;
755
+ this.dirty = true;
756
+ return true;
757
+ }
758
+ if (this.overlay) {
759
+ this.overlay = null;
760
+ this.dirty = true;
761
+ return true;
762
+ }
763
+ if (this.atPal) {
764
+ this.atPal = null;
765
+ this.dirty = true;
766
+ return true;
767
+ }
768
+ return false;
769
+ }
770
+ /** Ctrl+R: incremental history search modal (B4). Enter adopts the match
771
+ * into the input; Esc closes; ^P/^N or arrows move. */
772
+ openHistSearch() {
773
+ if (!this.history.length)
774
+ return;
775
+ this.histSearch = { query: '', matches: histMatches(this.history, ''), sel: 0 };
776
+ this.dirty = true;
777
+ }
778
+ histKey(data) {
779
+ const hs = this.histSearch;
780
+ if (!hs)
781
+ return;
782
+ if (data === '\x1b') {
783
+ this.histSearch = null;
784
+ this.dirty = true;
785
+ return;
786
+ }
787
+ if (data === '\r') {
788
+ const line = this.history[hs.matches[hs.sel]];
789
+ if (line !== undefined) {
790
+ this.histSearch = null;
791
+ this.setInput(line);
792
+ }
793
+ return;
794
+ }
795
+ if (data === '\x1b[A' || data === '\x10') {
796
+ hs.sel = Math.max(0, hs.sel - 1);
797
+ this.dirty = true;
798
+ return;
799
+ }
800
+ if (data === '\x1b[B' || data === '\x0e') {
801
+ hs.sel = Math.min(hs.matches.length - 1, hs.sel + 1);
802
+ this.dirty = true;
803
+ return;
804
+ }
805
+ if (data === '\x7f' || data === '\b') {
806
+ hs.query = hs.query.slice(0, -1);
807
+ hs.matches = histMatches(this.history, hs.query);
808
+ hs.sel = 0;
809
+ this.dirty = true;
810
+ return;
811
+ }
812
+ if (data.length === 1 && data >= ' ') {
813
+ hs.query += data;
814
+ hs.matches = histMatches(this.history, hs.query);
815
+ hs.sel = 0;
816
+ this.dirty = true;
817
+ }
818
+ }
819
+ /** Ctrl+T: full-transcript overlay (B5), also the pager base for long
820
+ * outputs (B9). ↑↓/PgUp/PgDn/g/G scroll, Esc/q closes. */
821
+ overlaySource = () => [];
822
+ setOverlaySource(fn) { this.overlaySource = fn; }
823
+ openOverlay(title, lines) {
824
+ const H = Math.max(5, (stdout.rows || 30) - 2);
825
+ this.overlay = { title, lines, top: Math.max(0, lines.length - H) };
826
+ this.dirty = true;
827
+ }
828
+ /** Public pager/overlay entry (M4 /diff, B9 auto-pager). */
829
+ showOverlay(title, lines) {
830
+ this.openOverlay(title, lines);
831
+ }
832
+ /* ---------------- M4: tool-result cells (B8) ---------------- */
833
+ toolCells = [];
834
+ /** Tool call + result as a collapsible cell: one folded summary line by
835
+ * default (W1/T5 spirit); the `z` key (idle + empty input) expands the
836
+ * LAST cell to its full output. */
837
+ addToolCell(folded, full) {
838
+ const width = Math.max(20, (stdout.columns || 100) - 2);
839
+ const entry = { lines: wrapTo(folded, width).map((l) => DIM(l)) };
840
+ this.entries.push(entry);
841
+ this.toolCells.push({ entry, full, folded, expanded: false });
842
+ this.scrollFromBottom = 0;
843
+ this.dirty = true;
844
+ }
845
+ toggleLastCell() {
846
+ const cell = this.toolCells[this.toolCells.length - 1];
847
+ if (!cell)
848
+ return false;
849
+ const width = Math.max(20, (stdout.columns || 100) - 2);
850
+ cell.expanded = !cell.expanded;
851
+ cell.entry.lines = cell.expanded
852
+ ? [...wrapTo(cell.folded, width).map((l) => DIM(l)), ...wrapTo(cell.full, width)]
853
+ : wrapTo(cell.folded, width).map((l) => DIM(l));
854
+ this.dirty = true;
855
+ return true;
856
+ }
857
+ /* ---------------- M4: streaming markdown colorizer (B10) ---------------- */
858
+ /** Light zero-dep markdown line color for STREAMED text: headings cyan,
859
+ * list markers dim, fences dim, blockquotes dim; everything else plain.
860
+ * Applied per completed line so already-stable rows never reflow. */
861
+ static mdColor(line) {
862
+ const t = line.trim();
863
+ if (/^#{1,6}\s/.test(t))
864
+ return CYAN(BOLD(line));
865
+ if (/^```/.test(t))
866
+ return DIM(line);
867
+ if (/^>\s?/.test(t))
868
+ return DIM(line);
869
+ if (/^[-*+]\s/.test(t) || /^\d+[.)]\s/.test(t))
870
+ return DIM(line.replace(/^(\s*[-*+]\s|\s*\d+[.)]\s)/, '$1'));
871
+ return line;
872
+ }
873
+ overlayKey(data) {
874
+ const ov = this.overlay;
875
+ if (!ov)
876
+ return;
877
+ const H = Math.max(5, (stdout.rows || 30) - 2);
878
+ const maxTop = Math.max(0, ov.lines.length - H);
879
+ if (data === '\x1b' || data === '\x03' || data === 'q' || data === 'Q') {
880
+ this.overlay = null;
881
+ this.dirty = true;
882
+ return;
883
+ }
884
+ if (data === '\x1b[A' || data === '\x1b[5~' || data === 'k') {
885
+ ov.top = Math.max(0, ov.top - 1);
886
+ this.dirty = true;
887
+ return;
888
+ }
889
+ if (data === '\x1b[B' || data === '\x1b[6~' || data === 'j') {
890
+ ov.top = Math.min(maxTop, ov.top + 1);
891
+ this.dirty = true;
892
+ return;
893
+ }
894
+ if (data === '\x1b[H' || data === 'g') {
895
+ ov.top = 0;
896
+ this.dirty = true;
897
+ return;
898
+ }
899
+ if (data === '\x1b[F' || data === 'G') {
900
+ ov.top = maxTop;
901
+ this.dirty = true;
902
+ return;
903
+ }
904
+ }
905
+ /** @-file palette (B2): opens/refreshes from the input's trailing @token. */
906
+ refreshAtPal() {
907
+ const token = atToken(this.input);
908
+ if (token === null) {
909
+ if (this.atPal) {
910
+ this.atPal = null;
911
+ this.dirty = true;
912
+ }
913
+ return;
914
+ }
915
+ if (!this.atPal)
916
+ this.atPal = { query: token, results: [], sel: 0, token: 0, timer: null };
917
+ this.atPal.query = token;
918
+ if (this.atPal.timer)
919
+ clearTimeout(this.atPal.timer);
920
+ const tk = ++this.atPal.token;
921
+ this.atPal.timer = setTimeout(() => void this.runAtSearch(tk), 120);
922
+ }
923
+ async runAtSearch(tk) {
924
+ const pal = this.atPal;
925
+ if (!pal || pal.token !== tk)
926
+ return;
927
+ try {
928
+ const { fuzzyScore, SKIP_DIRS, MAX_SEARCH_DEPTH, MAX_SEARCH_ENTRIES, MAX_SEARCH_RESULTS } = await import('@hmharness/web');
929
+ const { readdir } = await import('node:fs/promises');
930
+ const { join: j } = await import('node:path');
931
+ const q = pal.query;
932
+ const root = process.cwd();
933
+ const hits = [];
934
+ let visited = 0;
935
+ const walk = async (dir, depth) => {
936
+ if (depth > MAX_SEARCH_DEPTH || visited >= MAX_SEARCH_ENTRIES)
937
+ return;
938
+ let entries;
939
+ try {
940
+ entries = await readdir(dir, { withFileTypes: true });
941
+ }
942
+ catch {
943
+ return;
944
+ }
945
+ for (const e of entries) {
946
+ if (visited >= MAX_SEARCH_ENTRIES)
947
+ return;
948
+ visited++;
949
+ if (e.isSymbolicLink())
950
+ continue;
951
+ const abs = j(dir, e.name);
952
+ if (e.isDirectory()) {
953
+ if (SKIP_DIRS.has(e.name))
954
+ continue;
955
+ await walk(abs, depth + 1);
956
+ continue;
957
+ }
958
+ if (!e.isFile())
959
+ continue;
960
+ const rel = abs.slice(root.length + 1).replace(/\\/g, '/');
961
+ const score = fuzzyScore(q, rel);
962
+ if (score >= 0)
963
+ hits.push({ rel, path: abs, score });
964
+ }
965
+ };
966
+ await walk(root, 0);
967
+ hits.sort((a, b) => b.score - a.score || a.rel.localeCompare(b.rel));
968
+ if (!this.atPal || this.atPal.token !== tk)
969
+ return;
970
+ this.atPal.results = hits.slice(0, MAX_SEARCH_RESULTS).map(({ rel, path }) => ({ rel, path }));
971
+ this.atPal.sel = 0;
972
+ this.dirty = true;
973
+ }
974
+ catch { /* search is best-effort; the palette just shows nothing */ }
975
+ }
976
+ atPalKey(data) {
977
+ const pal = this.atPal;
978
+ if (!pal)
979
+ return;
980
+ if (data === '\x1b') {
981
+ this.atPal = null;
982
+ this.dirty = true;
983
+ return;
984
+ }
985
+ if (data === '\r') {
986
+ const pick = pal.results[pal.sel];
987
+ if (pick) {
988
+ this.input = this.input.replace(/@[\w./\\-]*$/, '@' + pick.rel);
989
+ this.caret = this.input.length;
990
+ }
991
+ this.atPal = null;
992
+ this.dirty = true;
993
+ return;
994
+ }
995
+ if (data === '\x1b[A') {
996
+ pal.sel = Math.max(0, pal.sel - 1);
997
+ this.dirty = true;
998
+ return;
999
+ }
1000
+ if (data === '\x1b[B') {
1001
+ pal.sel = Math.min(pal.results.length - 1, pal.sel + 1);
1002
+ this.dirty = true;
1003
+ return;
1004
+ }
1005
+ // printable/backspace edits the input line itself; the palette re-filters
1006
+ if (data === '\x7f' || data === '\b') {
1007
+ if (this.caret > 0) {
1008
+ this.input = this.input.slice(0, this.caret - 1) + this.input.slice(this.caret);
1009
+ this.caret--;
1010
+ }
1011
+ this.refreshAtPal();
1012
+ return;
1013
+ }
1014
+ if (data.length === 1 && data >= ' ') {
1015
+ this.input = this.input.slice(0, this.caret) + data + this.input.slice(this.caret);
1016
+ this.caret += data.length;
1017
+ this.refreshAtPal();
1018
+ return;
1019
+ }
1020
+ }
551
1021
  /* ---------------- keyboard ---------------- */
552
1022
  clearScreen() {
553
1023
  this.entries = [];
@@ -576,6 +1046,20 @@ export class TuiRuntime {
576
1046
  this.pickerInput(key);
577
1047
  return;
578
1048
  }
1049
+ // M2 modals own the keys while open (history search, transcript overlay,
1050
+ // @-file palette) — each closes on its own Esc
1051
+ if (this.histSearch) {
1052
+ this.histKey(data);
1053
+ return;
1054
+ }
1055
+ if (this.overlay) {
1056
+ this.overlayKey(data);
1057
+ return;
1058
+ }
1059
+ if (this.atPal) {
1060
+ this.atPalKey(data);
1061
+ return;
1062
+ }
579
1063
  // wheel-only mouse routing: 64 = wheel-up, 65 = wheel-down. With
580
1064
  // button-event mode (1002) everything else - click, drag, release,
581
1065
  // motion - still belongs to the terminal's native selection.
@@ -635,14 +1119,79 @@ export class TuiRuntime {
635
1119
  this.dirty = true;
636
1120
  return;
637
1121
  }
1122
+ // Ctrl+Enter = inject into the RUNNING task (T10; terminals send it as
1123
+ // '\n' in raw mode; consistent with web W7 Ctrl+Enter). Idle it behaves
1124
+ // exactly like Enter (submit). Key is remappable (B14).
1125
+ if (data === this.keymap.inject) {
1126
+ if (this.busy && this.input.trim()) {
1127
+ const text = this.input;
1128
+ this.input = '';
1129
+ this.caret = 0;
1130
+ this.cmdIdx = 0;
1131
+ this.dirty = true;
1132
+ this.injectFn?.(text);
1133
+ }
1134
+ else {
1135
+ this.pickHighlighted();
1136
+ }
1137
+ return;
1138
+ }
1139
+ // Ctrl+G = external editor for the draft (B12); key remappable (B14)
1140
+ if (data === this.keymap.externalEdit && !this.busy) {
1141
+ this.externalEditFn?.(this.input);
1142
+ return;
1143
+ }
1144
+ // Ctrl+R = incremental history search (B4); key remappable (B14)
1145
+ if (data === this.keymap.historySearch) {
1146
+ this.openHistSearch();
1147
+ return;
1148
+ }
1149
+ // Ctrl+T = full-transcript overlay (B5): every transcript line PLUS the
1150
+ // full (folded-away) tool outputs, via the driver-registered source;
1151
+ // key remappable (B14)
1152
+ if (data === this.keymap.transcript) {
1153
+ const lines = [];
1154
+ for (const e of this.entries)
1155
+ lines.push(...e.lines.map(stripAnsi));
1156
+ const extra = this.overlaySource();
1157
+ this.openOverlay(this.t.tuiTranscript, [...lines, ...extra]);
1158
+ return;
1159
+ }
1160
+ // remapped interrupt key (B14): a non-Esc binding still stops the turn
1161
+ if (data === this.keymap.interrupt && this.keymap.interrupt !== '\x1b' && this.busy) {
1162
+ this.interruptFn?.();
1163
+ return;
1164
+ }
638
1165
  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.
1166
+ // Exact Esc only (arrow sequences arrive as '\x1b[A' and never match).
1167
+ // T9 order: an open modal closes FIRST; else running -> interrupt the
1168
+ // current task; else a non-empty draft is cleared (T7); else (idle +
1169
+ // empty) a second Esc within 800ms arms edit-and-fork (T13).
1170
+ if (this.closeModal())
1171
+ return;
1172
+ if (this.busy && this.keymap.interrupt === '\x1b') {
1173
+ this.interruptFn?.();
1174
+ return;
1175
+ }
641
1176
  if (this.input) {
642
1177
  this.input = '';
643
1178
  this.caret = 0;
644
1179
  this.cmdIdx = 0;
645
1180
  this.dirty = true;
1181
+ return;
1182
+ }
1183
+ const now = Date.now();
1184
+ if (forkArm(this.escAt, now, this.forkArmed)) {
1185
+ this.forkArmed = false;
1186
+ this.escAt = 0;
1187
+ if (this.lastUserMsg)
1188
+ this.forkEditFn?.();
1189
+ }
1190
+ else {
1191
+ this.forkArmed = true;
1192
+ this.escAt = now;
1193
+ this.status = this.t.forkArmed;
1194
+ this.dirty = true;
646
1195
  }
647
1196
  return;
648
1197
  }
@@ -778,6 +1327,12 @@ export class TuiRuntime {
778
1327
  this.dirty = true;
779
1328
  return;
780
1329
  }
1330
+ // M4 B8: `z` with an empty input expands/collapses the LAST tool cell
1331
+ // (folded summary <-> full output); with a draft it is just typing
1332
+ if (data === 'z' && !this.busy && !this.input) {
1333
+ if (this.toggleLastCell())
1334
+ return;
1335
+ }
781
1336
  if (data.startsWith('\x1b') || data < ' ')
782
1337
  return;
783
1338
  // printable text (CJK / IME preedit arrives as normal chunks)
@@ -785,6 +1340,8 @@ export class TuiRuntime {
785
1340
  this.caret += data.length;
786
1341
  this.cmdIdx = 0;
787
1342
  this.dirty = true;
1343
+ // '@' opens the file palette (B2); refreshAtPal() is a no-op otherwise
1344
+ this.refreshAtPal();
788
1345
  }
789
1346
  /* ---------------- rendering ---------------- */
790
1347
  render() {
@@ -799,6 +1356,21 @@ export class TuiRuntime {
799
1356
  this.flushFrame(frame, H);
800
1357
  return;
801
1358
  }
1359
+ if (this.histSearch) {
1360
+ this.renderHistSearch(frame, W, H);
1361
+ this.flushFrame(frame, H);
1362
+ return;
1363
+ }
1364
+ if (this.overlay) {
1365
+ this.renderOverlay(frame, W, H);
1366
+ this.flushFrame(frame, H);
1367
+ return;
1368
+ }
1369
+ if (this.atPal) {
1370
+ this.renderAtPal(frame, W, H);
1371
+ this.flushFrame(frame, H);
1372
+ return;
1373
+ }
802
1374
  // modal mouse reporting follows the palette (see syncMouseReporting);
803
1375
  // click rows are re-recorded every frame because screen positions move
804
1376
  this.syncMouseReporting();
@@ -1042,41 +1614,181 @@ export async function tui(yes, noWeb = false, opts = {}) {
1042
1614
  // Task queue: new submissions during a running task are queued (not
1043
1615
  // rejected, not run concurrently — sequential execution preserves history
1044
1616
  // 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.
1617
+ // M2 running-interaction trio (T9/T10, codex parity):
1618
+ // Enter (text) = queue for the NEXT turn
1619
+ // Ctrl+Enter = INJECT into the running turn (web W7-consistent)
1620
+ // Esc (running) = interrupt the current turn (was: empty Enter = stop —
1621
+ // reversed by 复案 2026-09-17, see DESIGNS.md)
1049
1622
  const taskQueue = [];
1050
1623
  let taskRunning = false;
1051
1624
  let currentAbort = null;
1625
+ /** live steering channel: Ctrl+Enter pushes here; runAgentTask drains it
1626
+ * into the running loop (InjectChannel shape) */
1627
+ let currentInject = null;
1628
+ /** full tool outputs retained for the Ctrl+T transcript overlay (B5) —
1629
+ * the transcript itself folds them to one line (W1/T5 spirit) */
1630
+ const fullToolLog = [];
1631
+ /** set by Esc-Esc edit-and-fork (T13): the next submission forks a new
1632
+ * session from the edited message (kernel forkFrom provenance) */
1633
+ let pendingFork = false;
1634
+ /** /fork (M4 B7): fork with the FULL history as resume (no edit point) */
1635
+ let forkAll = false;
1636
+ /** /plan (M4 B7): the next task gets a plan-first system directive */
1637
+ let planMode = false;
1638
+ /** /copy source: the last completed assistant text */
1639
+ let lastAiText = '';
1640
+ async function runShellBang(cmd) {
1641
+ // B3: `! command` runs the local shell through the SAME gate as the
1642
+ // agent's run_command tool — DENY_PATTERNS hard-refuse destructive
1643
+ // one-liners inside the tool; the TUI approval dialog stands in for the
1644
+ // loop's ask() (never a bypass; hard constraint #5).
1645
+ rt.addUser('!' + cmd);
1646
+ const tool = reg.get('run_command');
1647
+ if (!tool) {
1648
+ rt.addText('run_command tool missing', 'err');
1649
+ return;
1650
+ }
1651
+ const args = { command: cmd };
1652
+ // the tool's own gate decides (DENY_PATTERNS + shellgate live INSIDE
1653
+ // run_command.execute); the TUI dialog stands in for the loop's ask(),
1654
+ // except in YOLO/auto mode where approval is pre-granted
1655
+ if (tool.needsApproval?.(args, { cwd: process.cwd(), home }) && !autoApprove) {
1656
+ const ok = await rt.requestApproval('run_command', args);
1657
+ if (!ok) {
1658
+ rt.addText(DIM('denied'));
1659
+ return;
1660
+ }
1661
+ }
1662
+ const r = await tool.execute(args, { cwd: process.cwd(), home });
1663
+ const first = String(r.output).split('\n').find((l) => l.trim()) ?? '';
1664
+ rt.addText(` ${r.isError ? RED('✗') : GREEN('•')} ${DIM('⎿ ' + first.trim().slice(0, 120))}`, r.isError ? 'err' : 'dim');
1665
+ const rest = String(r.output).split('\n').slice(1).join('\n').trim();
1666
+ if (rest)
1667
+ rt.addText(rest.slice(0, 2000), 'dim');
1668
+ fullToolLog.push({ name: 'shell', output: String(r.output).slice(0, 4000) });
1669
+ }
1052
1670
  rt.onSubmit(() => {
1053
1671
  const line = rt.consumeInput().trim();
1054
1672
  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
- }
1673
+ // 复案 (T10): empty Enter no longer stops the running task. Stopping
1674
+ // is now an explicit Esc (T9). An empty Enter while running is a nudge.
1675
+ if (taskRunning)
1676
+ rt.addText(DIM('(empty — Esc stops · type + Enter queues · Ctrl+Enter injects)'));
1061
1677
  return;
1062
1678
  }
1063
1679
  if (line.startsWith('/')) {
1064
1680
  void handleLine(line);
1065
1681
  return;
1066
1682
  }
1683
+ if (shellBang(line) !== null) {
1684
+ void runShellBang(shellBang(line));
1685
+ return;
1686
+ }
1687
+ rt.setLastUserText(line);
1067
1688
  if (taskRunning) {
1068
1689
  taskQueue.push(line);
1069
1690
  rt.setQueued(taskQueue.length);
1070
1691
  rt.addText(`📋 queued: "${line.slice(0, 60)}${line.length > 60 ? '…' : ''}" (${taskQueue.length} waiting)`, 'dim');
1071
1692
  return;
1072
1693
  }
1073
- void executeTaskQueue(line);
1694
+ // Esc-Esc fork (T13): the new thread inherits everything BEFORE the last
1695
+ // user message (the edited line replaces it) and records the parent
1696
+ // session id in its rollout meta (kernel forkFrom). /fork (M4 B7): the
1697
+ // FULL history is the resume (no edit point).
1698
+ const forkFrom = pendingFork ? currentSessionId : undefined;
1699
+ const forkResume = pendingFork
1700
+ ? (forkAll ? history : history.slice(0, lastUserIdx(history)))
1701
+ : undefined;
1702
+ pendingFork = false;
1703
+ forkAll = false;
1704
+ void executeTaskQueue(line, forkFrom, forkResume);
1705
+ });
1706
+ rt.onInterrupt(() => {
1707
+ // T9: Esc while running interrupts the current turn. In-flight tool calls
1708
+ // finish first; queued tasks still run (clear with /queue clear).
1709
+ if (taskRunning && currentAbort) {
1710
+ currentAbort.abort();
1711
+ rt.addText('⏹ interrupting current task (in-flight tool calls finish first; queued tasks still run)', 'dim');
1712
+ }
1713
+ });
1714
+ rt.onInject((text) => {
1715
+ // T10: Ctrl+Enter injects into the RUNNING task (no-op when idle — the
1716
+ // key submits normally in that case)
1717
+ if (currentInject?.active) {
1718
+ currentInject.queue.push(text);
1719
+ rt.addText(`⤷ injected into running task: "${text.slice(0, 80)}"`, 'dim');
1720
+ }
1074
1721
  });
1075
- async function executeTaskQueue(firstTask) {
1722
+ rt.onForkEdit(() => {
1723
+ // T13: Esc Esc (idle + empty) loads the last user message for editing;
1724
+ // the next submit forks a new session from it
1725
+ const last = rt.getLastUserText();
1726
+ if (last) {
1727
+ pendingFork = true;
1728
+ rt.setInput(last);
1729
+ rt.addText(DIM('✂ edit and fork — Enter sends as a NEW session from this message'), 'dim');
1730
+ }
1731
+ });
1732
+ // B12: Ctrl+G hands the draft to an external editor ($EDITOR, notepad on
1733
+ // Windows); the edited text comes back into the input box
1734
+ rt.onExternalEdit(async (draft) => {
1735
+ try {
1736
+ const { mkdir, writeFile, readFile } = await import('node:fs/promises');
1737
+ const { join: j } = await import('node:path');
1738
+ const dir = j(home, 'tmp');
1739
+ await mkdir(dir, { recursive: true });
1740
+ const file = j(dir, `draft-${Date.now()}.txt`);
1741
+ await writeFile(file, draft, 'utf8');
1742
+ const { spawn } = await import('node:child_process');
1743
+ const editor = process.env.EDITOR || (process.platform === 'win32' ? 'notepad' : 'vi');
1744
+ await new Promise((resolve) => {
1745
+ const child = spawn(editor, process.platform === 'win32' ? [file] : [file], { windowsHide: false, stdio: 'inherit' });
1746
+ child.on('close', () => resolve());
1747
+ });
1748
+ const edited = await readFile(file, 'utf8');
1749
+ rt.setInput(edited);
1750
+ rt.addText(DIM(`✎ external editor (${editor}) → draft loaded (${edited.length} chars)`), 'dim');
1751
+ }
1752
+ catch (err) {
1753
+ rt.addText(String(err), 'err');
1754
+ }
1755
+ });
1756
+ // B14: remapped keys from config.json tui.keymap (applied at startup)
1757
+ {
1758
+ const km = cfg.tui?.keymap;
1759
+ if (km && typeof km === 'object')
1760
+ rt.setKeymap(km);
1761
+ }
1762
+ // B11: customizable idle statusline from config.json tui.statusline
1763
+ const applyStatusline = () => {
1764
+ const tpl = cfg.tui?.statusline ?? '';
1765
+ if (tpl) {
1766
+ rt.setStatus(renderStatusline(tpl, {
1767
+ model: chatModel,
1768
+ cwd: basename(process.cwd()),
1769
+ skills: skills.length,
1770
+ mode: autoApprove ? 'yolo' : cfg.approval === 'auto' ? 'auto' : 'ask',
1771
+ queue: taskQueue.length,
1772
+ version: HMH_VERSION,
1773
+ }));
1774
+ }
1775
+ };
1776
+ applyStatusline();
1777
+ // Ctrl+T overlay source: transcript + FULL (folded-away) tool outputs (B5)
1778
+ rt.setOverlaySource(() => {
1779
+ const out = [];
1780
+ for (const t of fullToolLog) {
1781
+ out.push('', `── ${t.name} ──`, t.output);
1782
+ }
1783
+ return out;
1784
+ });
1785
+ async function executeTaskQueue(firstTask, forkFrom, forkResume) {
1076
1786
  taskRunning = true;
1077
1787
  let task = firstTask;
1788
+ let first = true;
1078
1789
  while (task) {
1079
- await runSingleTask(task);
1790
+ await runSingleTask(task, first ? forkFrom : undefined, first ? forkResume : undefined);
1791
+ first = false;
1080
1792
  task = taskQueue.shift();
1081
1793
  rt.setQueued(taskQueue.length);
1082
1794
  if (task)
@@ -1084,10 +1796,17 @@ export async function tui(yes, noWeb = false, opts = {}) {
1084
1796
  }
1085
1797
  taskRunning = false;
1086
1798
  }
1087
- async function runSingleTask(line) {
1799
+ async function runSingleTask(line, forkFrom, forkResume) {
1088
1800
  rt.addUser(line);
1089
1801
  rt.setBusy(true, t.running);
1090
1802
  currentAbort = new AbortController();
1803
+ const injectCh = { queue: [], active: false };
1804
+ currentInject = injectCh;
1805
+ // /plan (M4 B7): a plan-first system directive rides ahead of the resume
1806
+ const planDirective = planMode
1807
+ ? [{ 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.' }]
1808
+ : [];
1809
+ const resumeBase = [...planDirective, ...(forkResume ?? history)];
1091
1810
  let appender = null;
1092
1811
  let kind = null;
1093
1812
  try {
@@ -1096,9 +1815,14 @@ export async function tui(yes, noWeb = false, opts = {}) {
1096
1815
  registry: reg,
1097
1816
  cfg,
1098
1817
  yes: autoApprove,
1099
- resumeMessages: history,
1100
- sessionId: currentSessionId,
1818
+ resumeMessages: resumeBase,
1819
+ sessionId: forkResume !== undefined ? undefined : currentSessionId,
1101
1820
  signal: currentAbort.signal,
1821
+ // M2 runtime steering: Ctrl+Enter pushes here; the runner drains it
1822
+ // between tool batches and the injected text lands as a user message
1823
+ inject: injectCh,
1824
+ // Esc-Esc fork (T13): the new rollout records the parent session id
1825
+ ...(forkFrom ? { forkFrom } : {}),
1102
1826
  approvalAsk: (name, args) => rt.requestApproval(name, args),
1103
1827
  events: {
1104
1828
  onLine: (l) => { if (kind === 'reasoning')
@@ -1132,17 +1856,37 @@ export async function tui(yes, noWeb = false, opts = {}) {
1132
1856
  onToolResult: (name, output, isError) => {
1133
1857
  const dot = isError ? RED('✗') : GREEN('•');
1134
1858
  const first = output.split('\n').find((l) => l.trim()) ?? '';
1135
- rt.addText(` ${dot} ${DIM('⎿ ' + first.trim().slice(0, 100))}`);
1859
+ // M4 B8: tool call + result = one collapsible cell (folded summary
1860
+ // by default; `z` with an empty input expands the last one)
1861
+ rt.addToolCell(` ${dot} ${CYAN(name)} ${DIM('⎿ ' + first.trim().slice(0, 100))}`, output);
1862
+ // M4 B9: outputs far beyond a screen auto-enter the pager overlay
1863
+ // (the user can always q/Esc back to the stream)
1864
+ if (output.split('\n').length > 2 * Math.max(20, (stdout.rows || 30))) {
1865
+ rt.showOverlay(`${name} output (${output.split('\n').length} lines)`, output.split('\n'));
1866
+ }
1867
+ // retain the FULL output for the Ctrl+T transcript overlay (B5);
1868
+ // the transcript itself keeps only the folded first line
1869
+ fullToolLog.push({ name, output: output.slice(0, 4000) });
1870
+ if (fullToolLog.length > 100)
1871
+ fullToolLog.splice(0, fullToolLog.length - 100);
1872
+ },
1873
+ onInjected: (message) => {
1874
+ rt.addText(`⤷ injected: "${message.slice(0, 80)}"`, 'dim');
1136
1875
  },
1137
1876
  },
1138
1877
  });
1139
1878
  rt.setBusy(false);
1140
1879
  currentSessionId = result.sessionId;
1880
+ currentInject = null;
1881
+ lastAiText = result.text || lastAiText;
1141
1882
  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)];
1883
+ // the plan directive rides in resumeBase but is NOT part of the thread:
1884
+ // history keeps only real messages (the next task re-applies it)
1885
+ history = [...(forkResume ?? history), { role: 'user', content: line }, ...result.messages.slice(resumeBase.length + 2)];
1143
1886
  }
1144
1887
  catch (err) {
1145
1888
  rt.setBusy(false);
1889
+ currentInject = null;
1146
1890
  rt.addText(String(err), 'err');
1147
1891
  }
1148
1892
  finally {
@@ -1166,9 +1910,7 @@ export async function tui(yes, noWeb = false, opts = {}) {
1166
1910
  const MAX_RENDER = 80;
1167
1911
  const msgs = tr.messages;
1168
1912
  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');
1913
+ rt.addText(t.cmdResuming(tr.id, msgs.length, skipped), 'dim');
1172
1914
  for (const m of (skipped > 0 ? msgs.slice(skipped) : msgs)) {
1173
1915
  const text = typeof m.content === 'string' ? m.content : '';
1174
1916
  if (m.role === 'user') {
@@ -1214,7 +1956,7 @@ export async function tui(yes, noWeb = false, opts = {}) {
1214
1956
  const queueList = taskQueue.length > 0
1215
1957
  ? taskQueue.map((task, i) => ' ' + (i + 1) + '. ' + task.slice(0, 70)).join('\n')
1216
1958
  : ' (empty)';
1217
- rt.addText('queue: ' + status + ' | ' + taskQueue.length + ' waiting\n' + queueList + '\n\nempty Enter = stop current · typed Enter = queue · /queue clear = drop all', 'dim');
1959
+ 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
1960
  return;
1219
1961
  }
1220
1962
  if (line === '?' || line === '/help') {
@@ -1229,6 +1971,210 @@ export async function tui(yes, noWeb = false, opts = {}) {
1229
1971
  currentSessionId = undefined;
1230
1972
  return;
1231
1973
  }
1974
+ if (line === '/new') {
1975
+ rt.clearScreen();
1976
+ history = [];
1977
+ currentSessionId = undefined;
1978
+ pendingFork = false;
1979
+ forkAll = false;
1980
+ rt.addText(DIM(t.cmdNewDone));
1981
+ return;
1982
+ }
1983
+ if (line === '/compact') {
1984
+ // M4 B7: compact the in-memory resume with the adaptive budget and
1985
+ // report the delta (honest: it affects the NEXT turn's context)
1986
+ const before = transcriptChars(history);
1987
+ const budget = adaptiveContextChars(cfg.provider);
1988
+ history = compactMessages(history, budget);
1989
+ const after = transcriptChars(history);
1990
+ rt.addText(`context: ${before.toLocaleString()} → ${after.toLocaleString()} chars (freed ${(before - after).toLocaleString()}; budget ${budget.toLocaleString()})`, 'dim');
1991
+ return;
1992
+ }
1993
+ if (line === '/diff') {
1994
+ // M4 B7: pager-view the worktree git diff (incl. untracked) via the
1995
+ // B5 overlay base
1996
+ rt.setBusy(true, '/diff');
1997
+ try {
1998
+ const { execFile } = await import('node:child_process');
1999
+ const { promisify } = await import('node:util');
2000
+ const run = promisify(execFile);
2001
+ const g = (a, mb) => run('git', a, { cwd: process.cwd(), windowsHide: true, maxBuffer: mb }).then((r) => String(r.stdout)).catch(() => '');
2002
+ const [st, df, un] = await Promise.all([
2003
+ g(['status', '--porcelain'], 4 * 1024 * 1024),
2004
+ g(['diff'], 8 * 1024 * 1024),
2005
+ g(['ls-files', '--others', '--exclude-standard'], 4 * 1024 * 1024),
2006
+ ]);
2007
+ const lines = [
2008
+ '── git status ──',
2009
+ ...(st.split('\n').filter(Boolean) || ['(clean)']),
2010
+ '',
2011
+ '── git diff ──',
2012
+ ...(df.split('\n') || ['(no tracked changes)']),
2013
+ '',
2014
+ '── untracked ──',
2015
+ ...(un.split('\n').filter(Boolean).slice(0, 60) || ['(none)']),
2016
+ ];
2017
+ rt.showOverlay(t.cmdDiff, lines);
2018
+ }
2019
+ catch (err) {
2020
+ rt.addText(String(err), 'err');
2021
+ }
2022
+ finally {
2023
+ rt.setBusy(false);
2024
+ }
2025
+ return;
2026
+ }
2027
+ if (line === '/fork') {
2028
+ // M4 B7: fork the CURRENT thread to a new session — the next task
2029
+ // resumes the FULL history and records forkFrom provenance
2030
+ if (!currentSessionId && history.length === 0) {
2031
+ rt.addText('nothing to fork yet', 'dim');
2032
+ return;
2033
+ }
2034
+ pendingFork = true;
2035
+ forkAll = true;
2036
+ rt.addText(DIM('✂ next task runs as a NEW session (forked' + (currentSessionId ? ' from ' + currentSessionId : '') + ' — full context inherited)'));
2037
+ return;
2038
+ }
2039
+ if (line === '/copy') {
2040
+ // M4 B7: last AI output -> clipboard (Windows clip / mac pbcopy /
2041
+ // linux xclip fallback chain; zero deps, stdin-fed)
2042
+ if (!lastAiText) {
2043
+ rt.addText('(no AI output yet to copy)', 'dim');
2044
+ return;
2045
+ }
2046
+ try {
2047
+ const { spawn } = await import('node:child_process');
2048
+ const bin = process.platform === 'win32' ? 'clip'
2049
+ : process.platform === 'darwin' ? 'pbcopy'
2050
+ : 'xclip';
2051
+ const args = bin === 'xclip' ? ['-selection', 'clipboard'] : [];
2052
+ const child = spawn(bin, args, { windowsHide: true, stdio: ['pipe', 'ignore', 'ignore'] });
2053
+ child.stdin.write(lastAiText);
2054
+ child.stdin.end();
2055
+ await new Promise((r) => child.on('close', r));
2056
+ rt.addText(GREEN('✓') + ' ' + t.cmdCopied, 'plain');
2057
+ }
2058
+ catch {
2059
+ rt.addText('(clipboard tool unavailable — output follows)\n' + lastAiText.slice(0, 2000), 'dim');
2060
+ }
2061
+ return;
2062
+ }
2063
+ if (line === '/plan' || line.startsWith('/plan ')) {
2064
+ // M4 B7: plan mode toggle (the directive is injected per-task, so the
2065
+ // agent always presents a plan and waits for confirmation first)
2066
+ planMode = !planMode;
2067
+ rt.addText(planMode ? GREEN('🔥') + ' ' + t.cmdPlanOn : t.cmdPlanOff, 'plain');
2068
+ return;
2069
+ }
2070
+ if (line === '/goal' || line.startsWith('/goal ')) {
2071
+ // M4 B7: session goal (shared storage with web A6 — kernel/goal.ts)
2072
+ const arg = line.slice(6).trim();
2073
+ const key = currentSessionId ?? 'web';
2074
+ try {
2075
+ if (!arg) {
2076
+ const g = await getGoal(home, key);
2077
+ rt.addText(g ? `goal: ${g}` : '(no goal set — /goal <text> to set)', 'dim');
2078
+ }
2079
+ else if (arg === 'clear') {
2080
+ await clearGoal(home, key);
2081
+ rt.addText(t.cmdGoalCleared, 'dim');
2082
+ }
2083
+ else {
2084
+ await setGoal(home, key, arg);
2085
+ rt.addText(GREEN('✓') + ` goal set (session ${key.slice(0, 8)}…)`, 'plain');
2086
+ }
2087
+ }
2088
+ catch (err) {
2089
+ rt.addText(String(err), 'err');
2090
+ }
2091
+ return;
2092
+ }
2093
+ if (line === '/usage') {
2094
+ // M4 B7: session context occupancy (the resume the model will see)
2095
+ const chars = transcriptChars(history);
2096
+ const budget = adaptiveContextChars(cfg.provider);
2097
+ rt.addText(`context: ${chars.toLocaleString()} chars (~${Math.ceil(chars / 4).toLocaleString()} tok) of ${budget.toLocaleString()} budget (${Math.round((chars / budget) * 100)}%)`, 'dim');
2098
+ return;
2099
+ }
2100
+ if (line === '/statusline' || line.startsWith('/statusline ')) {
2101
+ // M5 B11: customize the idle statusline ({model} {cwd} {skills} {mode}
2102
+ // {queue} {version}); persisted under config.json tui.statusline
2103
+ const arg = line.slice(12).trim();
2104
+ const cur = cfg.tui?.statusline ?? '';
2105
+ if (!arg) {
2106
+ rt.addText(cur ? `statusline: "${cur}"` : '(no custom statusline — /statusline "{model} · {cwd}" to set; placeholders: model cwd skills mode queue version)', 'dim');
2107
+ return;
2108
+ }
2109
+ try {
2110
+ const { patchConfig } = await import('@hmharness/kernel');
2111
+ const merged = { ...(cfg.tui ?? {}), statusline: arg };
2112
+ const fresh = await patchConfig({ tui: merged });
2113
+ cfg = fresh;
2114
+ applyStatusline();
2115
+ rt.addText(GREEN('✓') + ` statusline: "${arg}"`, 'plain');
2116
+ }
2117
+ catch (err) {
2118
+ rt.addText(String(err), 'err');
2119
+ }
2120
+ return;
2121
+ }
2122
+ if (line === '/keymap' || line.startsWith('/keymap ')) {
2123
+ // M5 B14: show / remap the M2/M4 action keys (config.json tui.keymap)
2124
+ const arg = line.slice(8).trim();
2125
+ if (!arg) {
2126
+ const km = cfg.tui?.keymap ?? {};
2127
+ const rows = Object.entries(KEYMAP_DEFAULTS).map(([a, d]) => {
2128
+ const v = km[a] ?? d;
2129
+ const pretty = v === '\x1b' ? 'esc' : v === '\x0a' ? 'ctrl+enter' : v === '\x12' ? 'ctrl+r' : v === '\x14' ? 'ctrl+t' : v === '\x07' ? 'ctrl+g' : JSON.stringify(v);
2130
+ return ` ${a.padEnd(14)} ${pretty}`;
2131
+ });
2132
+ rt.addText('keymap (defaults in parens):\n' + rows.join('\n') + '\n\n/keymap <action>=<key> — e.g. /keymap inject=ctrl+j', 'dim');
2133
+ return;
2134
+ }
2135
+ const eq = arg.indexOf('=');
2136
+ if (eq <= 0) {
2137
+ rt.addText('usage: /keymap <action>=<key> (actions: ' + Object.keys(KEYMAP_DEFAULTS).join(' ') + ')', 'err');
2138
+ return;
2139
+ }
2140
+ const action = arg.slice(0, eq).trim();
2141
+ const spec = arg.slice(eq + 1).trim();
2142
+ if (!(action in KEYMAP_DEFAULTS)) {
2143
+ rt.addText(`unknown action "${action}" (actions: ${Object.keys(KEYMAP_DEFAULTS).join(' ')})`, 'err');
2144
+ return;
2145
+ }
2146
+ const byte = parseKeySpec(spec);
2147
+ if (byte === null) {
2148
+ 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');
2149
+ return;
2150
+ }
2151
+ try {
2152
+ const { patchConfig } = await import('@hmharness/kernel');
2153
+ const prev = cfg.tui?.keymap ?? {};
2154
+ const merged = { ...(cfg.tui ?? {}), keymap: { ...prev, [action]: byte } };
2155
+ const fresh = await patchConfig({ tui: merged });
2156
+ cfg = fresh;
2157
+ rt.setKeymap({ ...prev, [action]: byte });
2158
+ rt.addText(GREEN('✓') + ` ${action} → ${spec}`, 'plain');
2159
+ }
2160
+ catch (err) {
2161
+ rt.addText(String(err), 'err');
2162
+ }
2163
+ return;
2164
+ }
2165
+ if (line === '/review') {
2166
+ // M4 B7: one-click "review the current worktree" task template
2167
+ 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.';
2168
+ if (taskRunning) {
2169
+ taskQueue.push(reviewTask);
2170
+ rt.setQueued(taskQueue.length);
2171
+ rt.addText(`📋 queued: "review the worktree" (${taskQueue.length} waiting)`, 'dim');
2172
+ }
2173
+ else {
2174
+ void executeTaskQueue(reviewTask);
2175
+ }
2176
+ return;
2177
+ }
1232
2178
  if (line === '/status') {
1233
2179
  rt.setStatus(t.tuiStatus(cfg.locale ?? 'zh', skills.length, chatModel));
1234
2180
  return;
@@ -1266,7 +2212,7 @@ export async function tui(yes, noWeb = false, opts = {}) {
1266
2212
  // the screen with a running task's streaming output.
1267
2213
  if (!arg) {
1268
2214
  if (taskRunning) {
1269
- rt.addText('task running - stop it first (empty Enter), then /resume', 'dim');
2215
+ rt.addText('task running - Esc to stop, then /resume', 'dim');
1270
2216
  return;
1271
2217
  }
1272
2218
  const pick = await rt.openResumePicker();
@@ -1415,7 +2361,7 @@ export async function tui(yes, noWeb = false, opts = {}) {
1415
2361
  provider: cfg.provider,
1416
2362
  runCase: async (c) => {
1417
2363
  if (c.tools)
1418
- return '(skipped in tui; run hmh evolve)';
2364
+ return t.cmdEvolveHint;
1419
2365
  const r = await chat(cfg.provider, [{ role: 'user', content: c.prompt }]);
1420
2366
  return r.message.content ?? '';
1421
2367
  },