@hmharness/cli 0.23.9 → 0.23.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.
@@ -0,0 +1,13 @@
1
+ export interface TuiPending {
2
+ /** the task that was running when the process died ('' = none) */
3
+ runningTask: string;
4
+ /** queued tasks, in order */
5
+ queue: string[];
6
+ /** the rollout the running task belonged to, when known */
7
+ sessionId?: string;
8
+ savedAt: string;
9
+ }
10
+ export declare function pendingPath(home: string): string;
11
+ export declare function savePending(home: string, p: TuiPending): Promise<void>;
12
+ export declare function loadPending(home: string): Promise<TuiPending | null>;
13
+ export declare function clearPending(home: string): Promise<void>;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * @hmharness/cli - tui-state (crash-safe pending-task memory)
3
+ * The TUI is where multi-hour development sessions live, and the task queue
4
+ * lives only in process memory: a crash, a terminal close, or a power loss
5
+ * took the "what was I running" state with it. This module persists exactly
6
+ * that - the running task plus the queued ones - to HMH_HOME/tui-pending.json
7
+ * on every change. A graceful quit removes the file; if the file exists at
8
+ * the next startup, the previous process died mid-work and the TUI shows a
9
+ * recall notice (the full transcript always survives in the rollout - this
10
+ * is the thread pointer, not the data). Best-effort IO throughout: a corrupt
11
+ * or unwritable file degrades to "no pending work", never a crash.
12
+ */
13
+ import { readFile, writeFile, rm } from 'node:fs/promises';
14
+ import { join } from 'node:path';
15
+ export function pendingPath(home) {
16
+ return join(home, 'tui-pending.json');
17
+ }
18
+ export async function savePending(home, p) {
19
+ try {
20
+ await writeFile(pendingPath(home), JSON.stringify(p, null, 2), 'utf8');
21
+ }
22
+ catch { /* best effort - the pending hint is a courtesy, not a contract */ }
23
+ }
24
+ export async function loadPending(home) {
25
+ try {
26
+ const j = JSON.parse(await readFile(pendingPath(home), 'utf8'));
27
+ if (!j || typeof j !== 'object')
28
+ return null;
29
+ if (typeof j.runningTask !== 'string' || !Array.isArray(j.queue))
30
+ return null;
31
+ return {
32
+ runningTask: j.runningTask,
33
+ queue: j.queue.filter((q) => typeof q === 'string'),
34
+ sessionId: typeof j.sessionId === 'string' ? j.sessionId : undefined,
35
+ savedAt: typeof j.savedAt === 'string' ? j.savedAt : '',
36
+ };
37
+ }
38
+ catch {
39
+ return null; // missing or corrupt = no pending work
40
+ }
41
+ }
42
+ export async function clearPending(home) {
43
+ try {
44
+ await rm(pendingPath(home), { force: true });
45
+ }
46
+ catch { /* best effort */ }
47
+ }
package/dist/tui.js CHANGED
@@ -13,11 +13,12 @@
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, transcriptChars, compactMessages, adaptiveContextChars, getGoal, setGoal, clearGoal } from '@hmharness/kernel';
16
+ import { loadConfig, homeDir, resolveProvider, listProviders, setChatRoute, setLocale, PROVIDER_PRESETS, addProviders, detectLocalProviders, latestSession, listSessions, loadTranscript, transcriptChars, compactMessages, adaptiveContextChars, getGoal, setGoal, clearGoal, isProviderAuthError } 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";
20
20
  import { formatRow, initialPickerState, pickerKey, reducePicker, toolbarLine, visibleRows } from "./resume-picker.js";
21
+ import { savePending, loadPending, clearPending } from "./tui-state.js";
21
22
  /** installed version, shown in the TUI header (v0.4.0) so users always
22
23
  * know which build they are talking to - resolves in both src/ and dist/ */
23
24
  const HMH_VERSION = (() => {
@@ -1713,6 +1714,17 @@ export async function tui(yes, noWeb = false, opts = {}) {
1713
1714
  rt.setModelChoices(listProviders(cfg).map((v) => ({ name: v.name, desc: `${v.model}${v.purposes.length ? ' (' + v.purposes.join('/') + ')' : ''}` })));
1714
1715
  rt.setModes(autoApprove); // always-visible badge, ask mode included
1715
1716
  rt.addText(t.tuiWelcome(chatModel), 'dim');
1717
+ // crash recall (断点记忆): a leftover tui-pending.json means the previous
1718
+ // process died with work in flight. The transcript survives in the rollout;
1719
+ // this is the pointer so the thread is not silently lost. Shown once.
1720
+ {
1721
+ const pend = await loadPending(home);
1722
+ if (pend && (pend.runningTask || pend.queue.length > 0)) {
1723
+ const shown = pend.runningTask || pend.queue[0] || '';
1724
+ rt.addText(t.tuiPendingNote(shown.slice(0, 80), pend.runningTask ? pend.queue.length : Math.max(0, pend.queue.length - 1)), 'dim');
1725
+ }
1726
+ await clearPending(home);
1727
+ }
1716
1728
  if (webUp)
1717
1729
  rt.addText(t.tuiWebLinked(DEFAULT_WEB_PORT), 'dim');
1718
1730
  // update reminder: cached (1/day) registry check, resolved async into the
@@ -1774,6 +1786,27 @@ export async function tui(yes, noWeb = false, opts = {}) {
1774
1786
  let planMode = false;
1775
1787
  /** /copy source: the last completed assistant text */
1776
1788
  let lastAiText = '';
1789
+ /** circuit-breaker latch: set when a task dies on a PERMANENT provider
1790
+ * auth/balance error (401/402/403). The queue stops draining - every
1791
+ * remaining task would fail identically against an unpaid bill. */
1792
+ let authErrorHit = false;
1793
+ /** Crash-safe pending-task memory (settled design T25): what the TUI was
1794
+ * doing at any moment, persisted so an abnormal exit (crash, terminal
1795
+ * close, power loss) can show a recall notice on the next start. Graceful
1796
+ * quit clears it. */
1797
+ const syncPending = (runningTask) => {
1798
+ if (runningTask || taskQueue.length > 0) {
1799
+ void savePending(home, {
1800
+ runningTask: runningTask ?? '',
1801
+ queue: [...taskQueue],
1802
+ sessionId: currentSessionId,
1803
+ savedAt: new Date().toISOString(),
1804
+ });
1805
+ }
1806
+ else {
1807
+ void clearPending(home);
1808
+ }
1809
+ };
1777
1810
  async function runShellBang(cmd) {
1778
1811
  // B3: `! command` runs the local shell through the SAME gate as the
1779
1812
  // agent's run_command tool — DENY_PATTERNS hard-refuse destructive
@@ -1825,6 +1858,7 @@ export async function tui(yes, noWeb = false, opts = {}) {
1825
1858
  if (taskRunning) {
1826
1859
  taskQueue.push(line);
1827
1860
  rt.setQueued(taskQueue.length);
1861
+ syncPending(null); // queue grew while a task runs - persist the new depth
1828
1862
  rt.addText(`📋 queued: "${line.slice(0, 60)}${line.length > 60 ? '…' : ''}" (${taskQueue.length} waiting)`, 'dim');
1829
1863
  return;
1830
1864
  }
@@ -1930,16 +1964,29 @@ export async function tui(yes, noWeb = false, opts = {}) {
1930
1964
  let task = firstTask;
1931
1965
  let first = true;
1932
1966
  while (task) {
1967
+ syncPending(task);
1933
1968
  await runSingleTask(task, first ? forkFrom : undefined, first ? forkResume : undefined);
1934
1969
  first = false;
1970
+ // circuit breaker (settled design T24): a permanent provider
1971
+ // auth/balance error means every queued task would fail the same way -
1972
+ // hold the queue for the user instead of burning through it
1973
+ if (authErrorHit && taskQueue.length > 0) {
1974
+ rt.setQueued(taskQueue.length);
1975
+ rt.addText(t.tuiQueueHeld(taskQueue.length), 'dim');
1976
+ syncPending(null);
1977
+ return;
1978
+ }
1935
1979
  task = taskQueue.shift();
1936
1980
  rt.setQueued(taskQueue.length);
1981
+ syncPending(task ?? null);
1937
1982
  if (task)
1938
1983
  rt.addText(`▶ next queued: "${task.slice(0, 60)}${task.length > 60 ? '…' : ''}"`, 'dim');
1939
1984
  }
1940
1985
  taskRunning = false;
1986
+ syncPending(null);
1941
1987
  }
1942
1988
  async function runSingleTask(line, forkFrom, forkResume) {
1989
+ authErrorHit = false; // fresh latch per task attempt
1943
1990
  rt.addUser(line);
1944
1991
  // the folded echo hides everything past line 2 - keep the full prompt
1945
1992
  // retrievable in the Ctrl+T replay
@@ -2057,6 +2104,7 @@ export async function tui(yes, noWeb = false, opts = {}) {
2057
2104
  catch (err) {
2058
2105
  rt.setBusy(false);
2059
2106
  currentInject = null;
2107
+ authErrorHit = isProviderAuthError(String(err));
2060
2108
  rt.addText(String(err), 'err');
2061
2109
  // Recovery First (docx TUI 专项): every task failure names the next step
2062
2110
  // instead of leaving a bare stack - retry is one up-arrow away
@@ -2075,7 +2123,12 @@ export async function tui(yes, noWeb = false, opts = {}) {
2075
2123
  rt.addText(t.cmdResumeNotFound(tr?.id ?? file), 'err');
2076
2124
  return;
2077
2125
  }
2078
- history = tr.messages;
2126
+ // bounded resume (settled design T26): the rollout keeps everything
2127
+ // forever (audit), but the in-memory thread is compacted to the model
2128
+ // budget immediately - the loop would do this on the next call anyway;
2129
+ // doing it here keeps /usage, fork copies and memory footprint honest
2130
+ // from the first turn
2131
+ history = compactMessages(tr.messages, adaptiveContextChars(resolveProvider(cfg, 'chat')));
2079
2132
  currentSessionId = tr.id;
2080
2133
  rt.clearScreen();
2081
2134
  // long sessions render from the tail so the visible window stays usable
@@ -2120,6 +2173,7 @@ export async function tui(yes, noWeb = false, opts = {}) {
2120
2173
  const n = taskQueue.length;
2121
2174
  taskQueue.length = 0;
2122
2175
  rt.setQueued(0);
2176
+ syncPending(null);
2123
2177
  rt.addText(n > 0 ? 'cleared ' + n + ' queued task(s)' : 'queue was already empty', 'dim');
2124
2178
  return;
2125
2179
  }
@@ -2724,6 +2778,9 @@ export async function tui(yes, noWeb = false, opts = {}) {
2724
2778
  process.off('SIGINT', sigCleanup);
2725
2779
  process.off('SIGTERM', sigCleanup);
2726
2780
  process.off('SIGHUP', sigCleanup);
2781
+ // graceful exit: whatever was pending was deliberately abandoned (the
2782
+ // crash-recall notice must NOT fire on a clean quit)
2783
+ await clearPending(home);
2727
2784
  for (const c of clients)
2728
2785
  c.close();
2729
2786
  stdout.write('\n');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hmharness/cli",
3
- "version": "0.23.9",
3
+ "version": "0.23.10",
4
4
  "description": "hmharness command line: one-shot tasks, an interactive REPL, a fullscreen TUI, the web frontend, and direct tool invocation.",
5
5
  "type": "module",
6
6
  "main": "dist/main.js",
@@ -43,17 +43,17 @@
43
43
  "build": "tsc -p tsconfig.build.json"
44
44
  },
45
45
  "dependencies": {
46
- "@hmharness/agent": "0.23.9",
47
- "@hmharness/cognitive": "0.23.9",
48
- "@hmharness/domain-harmony": "0.23.9",
49
- "@hmharness/domain-ops": "0.23.9",
50
- "@hmharness/environments": "0.23.9",
51
- "@hmharness/evaluation": "0.23.9",
52
- "@hmharness/evolution": "0.23.9",
53
- "@hmharness/kernel": "0.23.9",
54
- "@hmharness/observability": "0.23.9",
55
- "@hmharness/sandbox": "0.23.9",
56
- "@hmharness/web": "0.23.9",
46
+ "@hmharness/agent": "0.23.10",
47
+ "@hmharness/cognitive": "0.23.10",
48
+ "@hmharness/domain-harmony": "0.23.10",
49
+ "@hmharness/domain-ops": "0.23.10",
50
+ "@hmharness/environments": "0.23.10",
51
+ "@hmharness/evaluation": "0.23.10",
52
+ "@hmharness/evolution": "0.23.10",
53
+ "@hmharness/kernel": "0.23.10",
54
+ "@hmharness/observability": "0.23.10",
55
+ "@hmharness/sandbox": "0.23.10",
56
+ "@hmharness/web": "0.23.10",
57
57
  "qrcode": "^1.5.4"
58
58
  }
59
59
  }