@hmharness/cli 0.18.5 → 0.18.6

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.
@@ -107,6 +107,12 @@ export function ensureEvolutionDaemon() {
107
107
  env: { ...process.env, HMH_HOME: home },
108
108
  });
109
109
  child.unref();
110
+ // the child inherited a dup of this fd; closing ours prevents the
111
+ // "Closing file descriptor on garbage collection" startup warnings
112
+ try {
113
+ require('node:fs').closeSync(log);
114
+ }
115
+ catch { /* already gone */ }
110
116
  return { running: true, pid: child.pid, started: true };
111
117
  }
112
118
  export function stopEvolutionDaemon() {
@@ -18,11 +18,65 @@ export declare function checkForUpdate(opts: {
18
18
  * say nothing at all. Never rejects. */
19
19
  export declare function notifyUpdate(home: string, current: string, say: (line: string) => void): Promise<void>;
20
20
  /** Background self-update (product direction 2026-09-21: zero-action updates,
21
- * notify only). NEVER swaps files under the running process - npm runs
22
- * detached and the new version is picked up on the NEXT launch, so a
23
- * mid-session install cannot corrupt the live TUI (Windows also locks
24
- * files in use, and this machine EPERMs on locked writes). A lock file
25
- * keeps concurrent hmh instances from racing one npm install. */
21
+ * notify only; 2026-09-25 redesign: SMART update).
22
+ *
23
+ * The old version hard-coded `spawn('npm', ...)` - which (a) silently fails
24
+ * on Windows since Node 18.20 refuses to spawn .cmd shims without a shell,
25
+ * while the UI still claimed "已在后台自动更新", and (b) leaked the log
26
+ * FileHandle (DEP0137 GC-close warnings on every startup).
27
+ *
28
+ * The smart design adapts instead of hard-coding:
29
+ * 1. buildUpdateCommand() picks the launcher per platform (cmd.exe shell
30
+ * escape on win32, direct exec elsewhere) - the SAME JS runs everywhere,
31
+ * no per-OS program;
32
+ * 2. if the standard install fails to even start, aiRepairUpdate() asks the
33
+ * user's configured chat model for ONE corrective install command based
34
+ * on the real error + environment facts (nvm/fnm/pnpm global dirs,
35
+ * permission quirks - the long tail no static table covers), validates
36
+ * it against an allow/deny filter and runs it detached. That is the
37
+ * "AI-driven" layer: the model adapts to the machine, not our code.
38
+ * A lock file keeps concurrent hmh instances from racing one install. */
39
+ export interface UpdateLaunch {
40
+ file: string;
41
+ args: string[];
42
+ /** shell:true semantics are needed when the package manager is a .cmd shim */
43
+ shellEscaped: boolean;
44
+ }
45
+ /** Platform-correct launcher for `npm install -g @hmharness/cli@<v>`.
46
+ * Pure; tested. */
47
+ export declare function buildUpdateCommand(platform: string, version: string): UpdateLaunch;
48
+ /** Model-proposed commands must be an install/update OF THE CLI PACKAGE and
49
+ * must not touch anything else. Pure; tested. */
50
+ export declare function isSafeUpdateCommand(cmd: string): boolean;
51
+ /** The environment fact sheet handed to the model for AI repair - everything
52
+ * it needs to diagnose an exotic setup (nvm dir, pnpm global, EPERM...). */
53
+ export declare function updateEnvFacts(platform: string, execPath: string, distDir: string, error: string): string;
54
+ /** One AI attempt to fix a failed self-update. Returns the command it ran
55
+ * (already spawned detached), or null when the model/answer is unusable.
56
+ * chatImpl is injectable for tests. */
57
+ export declare function aiRepairUpdate(opts: {
58
+ home: string;
59
+ platform: string;
60
+ execPath: string;
61
+ distDir: string;
62
+ error: string;
63
+ version: string;
64
+ chatImpl?: (prompt: string) => Promise<string>;
65
+ spawnImpl?: (cmd: string, args: string[], o: {
66
+ detached: boolean;
67
+ stdio: unknown;
68
+ cwd: string;
69
+ }) => {
70
+ unref: () => void;
71
+ on: (ev: string, fn: () => void) => void;
72
+ };
73
+ logFd: number;
74
+ }): Promise<string | null>;
75
+ /** Wait ~3s for a spawn 'error' (ENOENT/EINVAL fire immediately) so the UI
76
+ * only claims success when the installer actually started. */
77
+ export declare function spawnStarted(child: {
78
+ on: (ev: string, fn: () => void) => void;
79
+ }, ms?: number): Promise<boolean>;
26
80
  export declare function autoUpdate(opts: {
27
81
  home: string;
28
82
  current: string;
@@ -34,6 +88,8 @@ export declare function autoUpdate(opts: {
34
88
  cwd: string;
35
89
  }) => {
36
90
  unref: () => void;
91
+ on: (ev: string, fn: () => void) => void;
37
92
  };
38
93
  now?: number;
94
+ aiChat?: (prompt: string) => Promise<string>;
39
95
  }): Promise<void>;
@@ -67,12 +67,85 @@ export async function notifyUpdate(home, current, say) {
67
67
  }
68
68
  catch { /* never surface update-check failures */ }
69
69
  }
70
- /** Background self-update (product direction 2026-09-21: zero-action updates,
71
- * notify only). NEVER swaps files under the running process - npm runs
72
- * detached and the new version is picked up on the NEXT launch, so a
73
- * mid-session install cannot corrupt the live TUI (Windows also locks
74
- * files in use, and this machine EPERMs on locked writes). A lock file
75
- * keeps concurrent hmh instances from racing one npm install. */
70
+ /** Platform-correct launcher for `npm install -g @hmharness/cli@<v>`.
71
+ * Pure; tested. */
72
+ export function buildUpdateCommand(platform, version) {
73
+ const installArgs = ['install', '-g', '@hmharness/cli@' + version, '--registry=https://registry.npmjs.org/', '--no-fund', '--no-audit'];
74
+ if (platform === 'win32') {
75
+ // Node >= 18.20 throws EINVAL when spawning .cmd shims without a shell -
76
+ // route through cmd.exe explicitly
77
+ return { file: 'cmd.exe', args: ['/d', '/s', '/c', 'npm ' + installArgs.join(' ')], shellEscaped: true };
78
+ }
79
+ return { file: 'npm', args: installArgs, shellEscaped: false };
80
+ }
81
+ /** Model-proposed commands must be an install/update OF THE CLI PACKAGE and
82
+ * must not touch anything else. Pure; tested. */
83
+ export function isSafeUpdateCommand(cmd) {
84
+ const c = cmd.trim();
85
+ if (!/^(npm|pnpm|bun|yarn|corepack|node)\b/i.test(c))
86
+ return false;
87
+ if (/\brm\s|-rf\b|\bsudo\b|\bdel\s|\bformat\s|shutdown|reboot|mkfs|\bdd\s|\/etc\/|curl[^|]*\|\s*(ba)?sh/i.test(c))
88
+ return false;
89
+ return /@hmharness\/cli/i.test(c);
90
+ }
91
+ /** The environment fact sheet handed to the model for AI repair - everything
92
+ * it needs to diagnose an exotic setup (nvm dir, pnpm global, EPERM...). */
93
+ export function updateEnvFacts(platform, execPath, distDir, error) {
94
+ return [
95
+ 'platform=' + platform,
96
+ 'node=' + process.version,
97
+ 'execPath=' + execPath,
98
+ 'cliDist=' + distDir,
99
+ 'error=' + error.slice(0, 400),
100
+ ].join('\n');
101
+ }
102
+ /** One AI attempt to fix a failed self-update. Returns the command it ran
103
+ * (already spawned detached), or null when the model/answer is unusable.
104
+ * chatImpl is injectable for tests. */
105
+ export async function aiRepairUpdate(opts) {
106
+ try {
107
+ const chat = opts.chatImpl ?? (async () => {
108
+ const kernel = await import('@hmharness/kernel');
109
+ const cfg = await kernel.loadConfig();
110
+ const provider = kernel.resolveProvider(cfg, 'chat');
111
+ const r = await kernel.chat(provider, [
112
+ { role: 'system', content: 'You fix package-manager installs. Reply with STRICT JSON {"command":"<one shell command>"} - a single install/update command for the @hmharness/cli package (npm/pnpm/bun/yarn/corepack). No other text, no markdown fence. Never destructive.' },
113
+ { role: 'user', content: 'The standard "npm install -g @hmharness/cli@' + opts.version + '" failed on this machine:\n' + opts.error + '\n\nEnvironment:\n' + updateEnvFacts(opts.platform, opts.execPath, opts.distDir, opts.error) + '\n\nGive the ONE command that installs @hmharness/cli@' + opts.version + ' globally on THIS setup.' },
114
+ ]);
115
+ return r.message?.content ?? '';
116
+ });
117
+ // chat returns RAW model text; the {"command": ...} extraction lives HERE
118
+ // so an injected test chat has the same contract as the real one
119
+ const raw = await chat('fix update');
120
+ const m = /\{[\s\S]*\}/.exec(raw ?? '');
121
+ const cmd = m ? String(JSON.parse(m[0]).command ?? '').trim() : '';
122
+ if (!cmd || !isSafeUpdateCommand(cmd))
123
+ return null;
124
+ const spawnFn = opts.spawnImpl ?? (await import('node:child_process')).spawn;
125
+ const plat = opts.platform;
126
+ const child = plat === 'win32'
127
+ ? spawnFn('cmd.exe', ['/d', '/s', '/c', cmd], { detached: true, stdio: ['ignore', opts.logFd, opts.logFd], cwd: opts.home })
128
+ : spawnFn(cmd.split(' ')[0], cmd.split(' ').slice(1), { detached: true, stdio: ['ignore', opts.logFd, opts.logFd], cwd: opts.home });
129
+ child.unref();
130
+ return cmd;
131
+ }
132
+ catch {
133
+ return null; // AI repair is best-effort; the hint line still shows
134
+ }
135
+ }
136
+ /** Wait ~3s for a spawn 'error' (ENOENT/EINVAL fire immediately) so the UI
137
+ * only claims success when the installer actually started. */
138
+ export function spawnStarted(child, ms = 3000) {
139
+ return new Promise((resolve) => {
140
+ let settled = false;
141
+ const done = (ok) => { if (!settled) {
142
+ settled = true;
143
+ resolve(ok);
144
+ } };
145
+ child.on('error', () => done(false));
146
+ setTimeout(() => done(true), ms);
147
+ });
148
+ }
76
149
  export async function autoUpdate(opts) {
77
150
  try {
78
151
  const info = await checkForUpdate({ home: opts.home, current: opts.current, now: opts.now });
@@ -91,15 +164,49 @@ export async function autoUpdate(opts) {
91
164
  catch { /* no lock */ }
92
165
  await mkdir(opts.home, { recursive: true });
93
166
  const log = await open(join(opts.home, 'update.log'), 'a');
94
- const spawnFn = opts.spawnImpl ?? ((await import('node:child_process')).spawn);
95
- const child = spawnFn('npm', ['install', '-g', '@hmharness/cli@' + info.latest, '--registry=https://registry.npmjs.org/', '--no-fund', '--no-audit'], {
96
- detached: true,
97
- stdio: ['ignore', log.fd, log.fd],
98
- cwd: opts.home,
99
- });
100
- child.unref();
101
- await writeFile(lockFile, JSON.stringify({ time: now, to: info.latest }), 'utf8');
102
- opts.say(info.latest);
167
+ try {
168
+ const launch = buildUpdateCommand(process.platform, info.latest);
169
+ const spawnFn = opts.spawnImpl ?? (await import('node:child_process')).spawn;
170
+ const child = spawnFn(launch.file, launch.args, {
171
+ detached: true,
172
+ stdio: ['ignore', log.fd, log.fd],
173
+ cwd: opts.home,
174
+ });
175
+ child.unref();
176
+ await writeFile(lockFile, JSON.stringify({ time: now, to: info.latest }), 'utf8');
177
+ const started = await spawnStarted(child);
178
+ if (!started)
179
+ throw new Error('installer failed to start');
180
+ opts.say(info.latest);
181
+ }
182
+ catch (err) {
183
+ // SMART layer: let the user's own model adapt to this machine
184
+ const errText = String(err).slice(0, 400);
185
+ const distDir = join(import.meta.dirname ?? '.', '');
186
+ const ran = await aiRepairUpdate({
187
+ home: opts.home,
188
+ platform: process.platform,
189
+ execPath: process.execPath,
190
+ distDir,
191
+ error: errText,
192
+ version: info.latest,
193
+ chatImpl: opts.aiChat,
194
+ spawnImpl: opts.spawnImpl,
195
+ logFd: log.fd,
196
+ });
197
+ if (ran) {
198
+ await writeFile(lockFile, JSON.stringify({ time: now, to: info.latest, via: 'ai-repair', cmd: ran }), 'utf8');
199
+ opts.say(info.latest + ' (AI 修复安装)');
200
+ }
201
+ else {
202
+ opts.sayFail?.(errText.slice(0, 80));
203
+ }
204
+ }
205
+ finally {
206
+ // the child inherited a dup of this fd; closing ours kills the
207
+ // DEP0137 "closed on garbage collection" startup warnings
208
+ await log.close().catch(() => { });
209
+ }
103
210
  }
104
211
  catch (err) {
105
212
  opts.sayFail?.(String(err).slice(0, 80));
@@ -13,7 +13,7 @@
13
13
  import { spawn } from 'node:child_process';
14
14
  import { execSync } from 'node:child_process';
15
15
  import { createRequire } from 'node:module';
16
- import { openSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
16
+ import { openSync, readFileSync, unlinkSync, writeFileSync, closeSync } from 'node:fs';
17
17
  import { join } from 'node:path';
18
18
  import { homeDir } from '@hmharness/kernel';
19
19
  export const DEFAULT_WEB_PORT = 7788;
@@ -120,6 +120,11 @@ function spawnWebDaemon(port, entry = process.argv[1]) {
120
120
  cwd: process.cwd(),
121
121
  });
122
122
  child.unref();
123
+ // the child inherited a dup; closing ours prevents GC-close fd warnings
124
+ try {
125
+ closeSync(log);
126
+ }
127
+ catch { /* already gone */ }
123
128
  const pid = child.pid ?? 0;
124
129
  if (pid > 0) {
125
130
  writeFileSync(join(home, 'web.pid'), String(pid));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hmharness/cli",
3
- "version": "0.18.5",
3
+ "version": "0.18.6",
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",