@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/main.js CHANGED
@@ -63,8 +63,12 @@ async function runTask(task, taskOpts = {}) {
63
63
  registry: reg,
64
64
  cfg,
65
65
  yes: taskOpts.yes,
66
- resumeMessages: taskOpts.resumeMessages,
66
+ resumeMessages: [
67
+ ...(taskOpts.plan ? [{ 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.' }] : []),
68
+ ...(taskOpts.resumeMessages ?? []),
69
+ ],
67
70
  sessionId: taskOpts.sessionId,
71
+ ...(taskOpts.forkFrom ? { forkFrom: taskOpts.forkFrom } : {}),
68
72
  events: {
69
73
  onLine: (l) => stdout.write(DIM(` ${l}\n`)),
70
74
  onDelta: (kind, chunk) => {
@@ -122,6 +126,11 @@ async function repl(yes, initialHistory, initialSessionId) {
122
126
  // one rollout per conversation: the first task creates it, later lines and
123
127
  // `hmh resume` sessions append to it (codex thread semantics)
124
128
  let currentSessionId = initialSessionId;
129
+ // M4 B7: /fork queues a fork of the next task; /plan injects a
130
+ // plan-first directive (kernel forkFrom + system directive ride in runTask)
131
+ let pendingFork = false;
132
+ let forkAll = false;
133
+ let planMode = false;
125
134
  try {
126
135
  while (true) {
127
136
  let line;
@@ -225,6 +234,70 @@ async function repl(yes, initialHistory, initialSessionId) {
225
234
  stdout.write(DIM(t.cmdClearDone) + '\n');
226
235
  continue;
227
236
  }
237
+ if (line === '/new') {
238
+ // M4 B7: new-session alias of /clear (codex /new)
239
+ history = [];
240
+ currentSessionId = undefined;
241
+ stdout.write(DIM(t.cmdNewDone) + '\n');
242
+ continue;
243
+ }
244
+ if (line === '/compact') {
245
+ // M4 B7: compact the in-memory resume; report the delta
246
+ const { transcriptChars, compactMessages, adaptiveContextChars } = await import('@hmharness/kernel');
247
+ const before = transcriptChars(history);
248
+ const budget = adaptiveContextChars(cfg.provider);
249
+ history = compactMessages(history, budget);
250
+ const after = transcriptChars(history);
251
+ stdout.write(`context: ${before.toLocaleString()} → ${after.toLocaleString()} chars (freed ${(before - after).toLocaleString()}; budget ${budget.toLocaleString()})\n`);
252
+ continue;
253
+ }
254
+ if (line === '/usage') {
255
+ const { transcriptChars, adaptiveContextChars } = await import('@hmharness/kernel');
256
+ const chars = transcriptChars(history);
257
+ const budget = adaptiveContextChars(cfg.provider);
258
+ stdout.write(`context: ${chars.toLocaleString()} chars (~${Math.ceil(chars / 4).toLocaleString()} tok) of ${budget.toLocaleString()} budget (${Math.round((chars / budget) * 100)}%)\n`);
259
+ continue;
260
+ }
261
+ if (line === '/goal' || line.startsWith('/goal ')) {
262
+ const { getGoal, setGoal, clearGoal } = await import('@hmharness/kernel');
263
+ const arg = line.slice(6).trim();
264
+ const key = currentSessionId ?? 'web';
265
+ if (!arg) {
266
+ const g = await getGoal(home, key);
267
+ stdout.write((g ? `goal: ${g}` : '(no goal set — /goal <text> to set)') + '\n');
268
+ }
269
+ else if (arg === 'clear') {
270
+ await clearGoal(home, key);
271
+ stdout.write(DIM(t.cmdGoalCleared) + '\n');
272
+ }
273
+ else {
274
+ await setGoal(home, key, arg);
275
+ stdout.write(GREEN('✓') + ` goal set (session ${key.slice(0, 8)}…)\n`);
276
+ }
277
+ continue;
278
+ }
279
+ if (line === '/fork') {
280
+ // M4 B7: the NEXT task forks a new session inheriting full context
281
+ // (kernel forkFrom provenance rides in runTask)
282
+ if (!currentSessionId && history.length === 0) {
283
+ stdout.write('nothing to fork yet\n');
284
+ continue;
285
+ }
286
+ pendingFork = true;
287
+ forkAll = true;
288
+ stdout.write(DIM('✂ next task runs as a NEW session (forked' + (currentSessionId ? ' from ' + currentSessionId : '') + ')\n'));
289
+ continue;
290
+ }
291
+ if (line === '/plan') {
292
+ planMode = !planMode;
293
+ stdout.write((planMode ? GREEN('🔥') + ' ' + t.cmdPlanOn : t.cmdPlanOff) + '\n');
294
+ continue;
295
+ }
296
+ if (line === '/review') {
297
+ // M4 B7: submit the review-worktree task template
298
+ line = '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.';
299
+ // fall through to the task runner below
300
+ }
228
301
  if (line === '/status') {
229
302
  header();
230
303
  continue;
@@ -258,18 +331,36 @@ async function repl(yes, initialHistory, initialSessionId) {
258
331
  stdout.write(t.tuiEvolveDone(report.proposals.length, report.insightCount, report.noteCount) + '\n');
259
332
  continue;
260
333
  }
261
- stdout.write(YELLOW(t.unknownCommand(line) + '\n'));
262
- continue;
334
+ if (line === '/review') {
335
+ // M4 B7: submit the review-worktree task template — falls through
336
+ // to the task runner below; the else-branch fires only for lines
337
+ // no command consumed
338
+ line = '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.';
339
+ }
340
+ else {
341
+ stdout.write(YELLOW(t.unknownCommand(line) + '\n'));
342
+ continue;
343
+ }
263
344
  }
264
345
  try {
265
- const r = await runTask(line, { yes: autoApprove, sharedRl: rl, registry: reg, clients, resumeMessages: history, sessionId: currentSessionId });
346
+ const r = await runTask(line, {
347
+ yes: autoApprove, sharedRl: rl, registry: reg, clients,
348
+ resumeMessages: history,
349
+ sessionId: pendingFork && !forkAll ? undefined : currentSessionId,
350
+ forkFrom: pendingFork ? currentSessionId : undefined,
351
+ plan: planMode,
352
+ });
266
353
  // working transcript = [system, ...resumeMessages, user, ...new turns];
267
354
  // only the NEW turns (past the replayed prefix) extend history.
268
- history = [...history, { role: 'user', content: line }, ...r.messages.slice(history.length + 2)];
355
+ pendingFork = false;
356
+ forkAll = false;
357
+ history = [...history, { role: 'user', content: line }, ...r.messages.slice((planMode ? 1 : 0) + history.length + 2)];
269
358
  // one rollout per REPL conversation (codex thread semantics)
270
359
  currentSessionId = r.sessionId;
271
360
  }
272
361
  catch (err) {
362
+ pendingFork = false;
363
+ forkAll = false;
273
364
  stdout.write(`error: ${String(err)}\n`);
274
365
  }
275
366
  }
@@ -799,9 +890,10 @@ flags:
799
890
  const up = await hmhWebUp(Number.isFinite(port) ? port : 7788);
800
891
  stdout.write(up ? t.webRunning(readWebPid() || 0, port) + '\n' : t.webNotRunning + '\n');
801
892
  // stale-daemon warning: the daemon is a code snapshot from spawn time;
802
- // after an upgrade it keeps serving old code until restarted
893
+ // after an upgrade it keeps serving old code until restarted. The
894
+ // comparison uses the SERVED process's self-reported version.
803
895
  const { webDaemonStale } = await import("./web-daemon.js");
804
- const v = webDaemonStale();
896
+ const v = await webDaemonStale(Number.isFinite(port) ? port : 7788);
805
897
  if (up && v.stale) {
806
898
  stdout.write(YELLOW(`⚠ daemon is running v${v.daemon} but CLI is v${v.cli} — stale code (new features missing). Run: hmh web stop && hmh web start\n`));
807
899
  }
@@ -822,7 +914,9 @@ flags:
822
914
  }
823
915
  // default: foreground server (handy for debugging)
824
916
  const { startServer } = await import('@hmharness/web');
825
- await startServer({ port: Number.isFinite(port) ? port : 7788, host: '127.0.0.1' });
917
+ const { createRequire: cr } = await import('node:module');
918
+ const ver = cr(import.meta.url)('../package.json').version ?? '';
919
+ await startServer({ port: Number.isFinite(port) ? port : 7788, host: '127.0.0.1', version: ver });
826
920
  return; // startServer keeps the process alive
827
921
  }
828
922
  if (cmd === 'pipeline') {
package/dist/tui.d.ts CHANGED
@@ -12,6 +12,43 @@ export declare function matchCommands(input: string): Array<{
12
12
  }>;
13
13
  /** `/lang` target resolver: explicit zh/en wins, a bare `/lang` toggles. */
14
14
  export declare function nextLocale(current: string, arg: string): 'zh' | 'en';
15
+ /** The trailing `@<query>` token of a task line, or null. Drives the @-file
16
+ * palette (codex/dsh @ reference): typing '@' opens it, the following
17
+ * path-ish chars extend the query, Enter inserts the picked path. */
18
+ export declare function atToken(input: string): string | null;
19
+ /** Substring history search (Ctrl+R): indices of entries containing the
20
+ * query (case-insensitive), NEWEST first, capped at 50. Empty query lists
21
+ * the most recent 50. */
22
+ export declare function histMatches(history: string[], query: string): number[];
23
+ /** `!` line prefix → the shell command to run (B3), or null. Empty `!` is
24
+ * not a command. */
25
+ export declare function shellBang(line: string): string | null;
26
+ /** Double-Esc fork-edit arming (B6): a bare Esc when idle+empty returns true
27
+ * only if the previous Esc was within `windowMs` and the arm is set. Pure
28
+ * timing decision; the runtime keeps escAt/armed state. */
29
+ export declare function forkArm(prevAt: number, now: number, armed: boolean, windowMs?: number): boolean;
30
+ /** Index of the LAST user-role message — the fork point (T13): a fork keeps
31
+ * everything BEFORE it as the new thread's resume and replaces it with the
32
+ * edited message. -1 when there is none. */
33
+ export declare function lastUserIdx(messages: Array<{
34
+ role: string;
35
+ }>): number;
36
+ /** /statusline (B11): render a configurable bottom-line template. Supported
37
+ * placeholders: {model} {cwd} {skills} {mode} {queue} {version} — unknown
38
+ * tokens stay literal so a typo is visible, never silently dropped. */
39
+ export declare function renderStatusline(template: string, ctx: {
40
+ model: string;
41
+ cwd: string;
42
+ skills: number;
43
+ mode: string;
44
+ queue: number;
45
+ version: string;
46
+ }): string;
47
+ /** /keymap (B14): parse a human key spec into the raw-mode byte string the
48
+ * TUI dispatches on. Returns null for unknown specs. */
49
+ export declare function parseKeySpec(spec: string): string | null;
50
+ /** The remappable M2/M4 actions and their defaults (B14). */
51
+ export declare const KEYMAP_DEFAULTS: Record<string, string>;
15
52
  /**
16
53
  * SGR mouse wheel decoding: '\x1b[<64;COL;ROWM' is wheel-up (-1), 65 is
17
54
  * wheel-down (+1), anything else (clicks, drags, plain keys) is 0.
@@ -62,6 +99,25 @@ export declare class TuiRuntime {
62
99
  /** screen row of each visible palette item (SGR click hit-testing); the
63
100
  * render loop records row = frame.length (1-based) as it pushes rows */
64
101
  private paletteClickRows;
102
+ /** Ctrl+R incremental history search: { query, matches (history indices), sel } */
103
+ private histSearch;
104
+ /** Ctrl+T full-transcript overlay (also the pager base for B9): title + lines + viewport top */
105
+ private overlay;
106
+ /** @-file palette (codex @ fuzzy reference): trailing @token query + ranked hits */
107
+ private atPal;
108
+ /** double-Esc fork-edit arming (T13): timestamp of the first bare Esc */
109
+ private escAt;
110
+ private forkArmed;
111
+ /** driver callbacks for the running-interaction trio (T9/T10) */
112
+ private interruptFn;
113
+ private injectFn;
114
+ private forkEditFn;
115
+ /** M5 B12: Ctrl+G hands the draft to an external editor ($EDITOR/notepad) */
116
+ private externalEditFn;
117
+ /** M5 B14: remappable key bindings (config.json tui.keymap) */
118
+ private keymap;
119
+ /** last user-submitted line, for Esc-Esc edit-and-fork (T13) */
120
+ private lastUserMsg;
65
121
  constructor();
66
122
  setModelChoices(list: Array<{
67
123
  name: string;
@@ -87,6 +143,15 @@ export declare class TuiRuntime {
87
143
  /** Full-frame picker layout (codex draw_picker): title / search+toolbar /
88
144
  * list window / two hint lines / position footer. */
89
145
  private renderResumePicker;
146
+ /** Ctrl+R history-search modal (B4): query line + matching entries,
147
+ * newest first; Enter adopts, Esc closes, ^P/^N or arrows move. */
148
+ private renderHistSearch;
149
+ /** Ctrl+T full-transcript overlay (B5): title + scrollable lines; also the
150
+ * pager base for long outputs (B9). q/Esc closes, ↑↓/PgUp/PgDn/g/G scroll. */
151
+ private renderOverlay;
152
+ /** @-file palette (B2): ranked workspace hits for the trailing @token.
153
+ * Enter inserts the path; Esc closes; arrows move. */
154
+ private renderAtPal;
90
155
  /** Run the highlighted palette row (shared by Enter and palette clicks);
91
156
  * with no palette open it just submits the typed input. */
92
157
  private pickHighlighted;
@@ -134,7 +199,47 @@ export declare class TuiRuntime {
134
199
  setQueued(n: number): void;
135
200
  requestApproval(name: string, args: Record<string, unknown>): Promise<boolean>;
136
201
  consumeInput(): string;
202
+ setInput(text: string): void;
203
+ setLastUserText(s: string): void;
204
+ /** Last user-submitted line (Esc-Esc edit-and-fork source, T13). */
205
+ getLastUserText(): string;
137
206
  onSubmit(fn: () => void): void;
207
+ onInterrupt(fn: () => void): void;
208
+ onInject(fn: (text: string) => void): void;
209
+ onForkEdit(fn: () => void): void;
210
+ onExternalEdit(fn: (draft: string) => void): void;
211
+ /** M5 B14: apply remapped keys (config.json tui.keymap); unknown actions
212
+ * are ignored so a stale config degrades to defaults, never breaks keys */
213
+ setKeymap(map: Record<string, string>): void;
214
+ /** Close any open modal (Esc priority: panels close before anything else,
215
+ * T7/T9 order). Returns true when something was open. */
216
+ private closeModal;
217
+ /** Ctrl+R: incremental history search modal (B4). Enter adopts the match
218
+ * into the input; Esc closes; ^P/^N or arrows move. */
219
+ private openHistSearch;
220
+ private histKey;
221
+ /** Ctrl+T: full-transcript overlay (B5), also the pager base for long
222
+ * outputs (B9). ↑↓/PgUp/PgDn/g/G scroll, Esc/q closes. */
223
+ private overlaySource;
224
+ setOverlaySource(fn: () => string[]): void;
225
+ private openOverlay;
226
+ /** Public pager/overlay entry (M4 /diff, B9 auto-pager). */
227
+ showOverlay(title: string, lines: string[]): void;
228
+ private toolCells;
229
+ /** Tool call + result as a collapsible cell: one folded summary line by
230
+ * default (W1/T5 spirit); the `z` key (idle + empty input) expands the
231
+ * LAST cell to its full output. */
232
+ addToolCell(folded: string, full: string): void;
233
+ toggleLastCell(): boolean;
234
+ /** Light zero-dep markdown line color for STREAMED text: headings cyan,
235
+ * list markers dim, fences dim, blockquotes dim; everything else plain.
236
+ * Applied per completed line so already-stable rows never reflow. */
237
+ static mdColor(line: string): string;
238
+ private overlayKey;
239
+ /** @-file palette (B2): opens/refreshes from the input's trailing @token. */
240
+ private refreshAtPal;
241
+ private runAtSearch;
242
+ private atPalKey;
138
243
  clearScreen(): void;
139
244
  private totalLines;
140
245
  private onKey;