@hmharness/cli 0.23.12 → 0.23.14

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.
@@ -1,264 +1,264 @@
1
- #!/usr/bin/env node
2
- // install-kaihongos.cjs — one-command board installer for @hmharness/cli on
3
- // TWIN COPY: scripts/install-kaihongos.cjs (repo installs) and
4
- // packages/cli/board/install-kaihongos.cjs (ships in the npm package - the
5
- // board auto-update channel runs THIS one, settled design T28). Keep both
6
- // in sync when bumping FALLBACK_PINS.
7
- // KaihongOS / OpenHarmony 5.0 boards (no npm, no Python, read-only rootfs).
8
- //
9
- // What it does (idempotent, re-run any time):
10
- // 1. locates a usable Node >= 22 (the running one, or known board paths)
11
- // 2. resolves the @hmharness/* version set from registry.npmjs.org
12
- // (offline fallback: known-good pins below)
13
- // 3. downloads the 10 first-party tarballs and unpacks them under
14
- // <BOARD_HOME>/.local/hmharness/node_modules (staged, verified, swapped)
15
- // 4. writes a hardened launcher and installs it into THREE locations:
16
- // <BOARD_HOME>/.local/bin/hmh (user path, always writable)
17
- // /usr/local/bin/hmh (default PATH on classic shells)
18
- // /system/bin/hmh (read-only rootfs, remount dance;
19
- // ALSO visible inside isolated
20
- // tmpfs mount-namespace terminals
21
- // where /bin -> /system/bin)
22
- // 5. first run: `hmh init` if config.json is missing
23
- //
24
- // Usage:
25
- // node install-kaihongos.cjs # install/upgrade to latest
26
- // node install-kaihongos.cjs --bin-only # only (re)write launchers
27
- // node install-kaihongos.cjs --home=/x # non-default board home
28
- //
29
- // Only Node core modules are used; tar extraction uses busybox tar.
30
- const fs = require('fs');
31
- const path = require('path');
32
- const https = require('https');
33
- const { spawnSync } = require('child_process');
34
-
35
- // ---------- board constants -------------------------------------------------
36
- let BOARD_HOME = '/data/local/home'; // KaihongOS board home
37
- let BIN_ONLY = false;
38
-
39
- for (const a of process.argv.slice(2)) {
40
- if (a.startsWith('--home=')) BOARD_HOME = a.slice(7);
41
- else if (a === '--bin-only') BIN_ONLY = true;
42
- else { console.error('unknown arg:', a); process.exit(2); }
43
- }
44
-
45
- const ROOT = path.join(BOARD_HOME, '.local', 'hmharness');
46
- const NM = path.join(ROOT, 'node_modules');
47
- const HMH_HOME = path.join(BOARD_HOME, '.hmharness');
48
- const REG = 'https://registry.npmjs.org';
49
- const PACKAGES = ['cli', 'web', 'agent', 'kernel', 'sandbox', 'evolution',
50
- 'domain-ops', 'evaluation', 'observability', 'domain-harmony'];
51
-
52
- // Known-good pin set (offline fallback when the registry is unreachable).
53
- const FALLBACK_PINS = {
54
- cli: '0.23.10', web: '0.23.10', agent: '0.23.10', kernel: '0.23.10',
55
- sandbox: '0.23.10', evolution: '0.23.10', 'domain-ops': '0.23.10',
56
- evaluation: '0.23.10', observability: '0.23.10', 'domain-harmony': '0.23.10',
57
- };
58
-
59
- // ---------- helpers ---------------------------------------------------------
60
- function log(msg) { console.log(msg); }
61
-
62
- function httpsJSON(url, timeoutMs) {
63
- return new Promise((resolve, reject) => {
64
- const req = https.request(new URL(url), { headers: { 'User-Agent': 'hmh-kaihongos-installer' }, timeout: timeoutMs || 20000 }, (res) => {
65
- if (res.statusCode !== 200) { res.resume(); reject(new Error(url + ' -> ' + res.statusCode)); return; }
66
- const chunks = [];
67
- res.on('data', (c) => chunks.push(c));
68
- res.on('end', () => { try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))); } catch (e) { reject(e); } });
69
- });
70
- req.on('timeout', () => { req.destroy(new Error('timeout')); });
71
- req.on('error', reject);
72
- req.end();
73
- });
74
- }
75
-
76
- function download(url, file) {
77
- return new Promise((resolve, reject) => {
78
- let attempt = 0;
79
- function go() {
80
- attempt++;
81
- const req = https.request(new URL(url), { headers: { 'User-Agent': 'hmh-kaihongos-installer' }, timeout: 30000 }, (res) => {
82
- if (res.statusCode !== 200) { res.resume(); reject(new Error(url + ' -> ' + res.statusCode)); return; }
83
- const out = fs.createWriteStream(file);
84
- res.pipe(out);
85
- out.on('finish', () => out.close(resolve));
86
- out.on('error', reject);
87
- });
88
- req.on('timeout', () => { req.destroy(); retry(); });
89
- req.on('error', (e) => {
90
- if (attempt < 10 && /EAI_AGAIN|ENOTFOUND|ECONNRESET|ETIMEDOUT/.test(e.code || '')) setTimeout(retry, 1500 * attempt);
91
- else reject(e);
92
- });
93
- req.end();
94
- }
95
- function retry() { if (attempt < 10) go(); else reject(new Error('retries exhausted: ' + url)); }
96
- go();
97
- });
98
- }
99
-
100
- function extract(tgz, dest) {
101
- fs.mkdirSync(dest, { recursive: true });
102
- // busybox tar is present on KaihongOS / OpenHarmony boards and understands
103
- // --strip-components. (GNU/toybox tar also fine if busybox is missing.)
104
- const cmds = [
105
- ['busybox', ['tar', '-xzf', tgz, '-C', dest, '--strip-components=1']],
106
- ['tar', ['-xzf', tgz, '-C', dest, '--strip-components=1']],
107
- ];
108
- for (const [bin, args] of cmds) {
109
- const r = spawnSync(bin, args, { encoding: 'utf8' });
110
- if (r.status === 0) return;
111
- if (r.error && r.error.code !== 'ENOENT') log(' warn: ' + bin + ' tar: ' + (r.stderr || r.error.message).slice(0, 120));
112
- }
113
- throw new Error('no usable tar (tried busybox tar, tar)');
114
- }
115
-
116
- async function resolveVersions() {
117
- log('resolving latest @hmharness/cli from registry ...');
118
- const meta = await httpsJSON(REG + '/@hmharness/cli');
119
- const cliLatest = meta['dist-tags'].latest;
120
- const deps = (meta.versions[cliLatest].dependencies) || {};
121
- const pins = { cli: cliLatest };
122
- for (const n of PACKAGES.slice(1)) {
123
- const want = deps['@hmharness/' + n];
124
- if (want && want !== '*') { pins[n] = want.replace(/[^0-9.]/g, ''); continue; }
125
- const m = await httpsJSON(REG + '/@hmharness/' + n);
126
- pins[n] = m['dist-tags'].latest;
127
- }
128
- return pins;
129
- }
130
-
131
- // ---------- node discovery --------------------------------------------------
132
- function findNode() {
133
- const cands = [process.execPath,
134
- path.join(BOARD_HOME, 'dsh-pack/node/bin/node'),
135
- path.join(BOARD_HOME, '.ohos/node/bin/node'),
136
- '/usr/local/bin/node', '/usr/bin/node', '/system/bin/node'];
137
- for (const c of cands) {
138
- try {
139
- fs.accessSync(c, fs.constants.X_OK);
140
- const v = spawnSync(c, ['--version'], { encoding: 'utf8' });
141
- if (v.status === 0) { const maj = parseInt((v.stdout || '').replace('v', ''), 10); if (maj >= 22) return c; }
142
- } catch (_) { /* next */ }
143
- }
144
- return null;
145
- }
146
-
147
- // ---------- launcher --------------------------------------------------------
148
- function launcherSource(nodeBin) {
149
- return [
150
- '#!/system/bin/sh',
151
- '# hmh launcher — KaihongOS board install (generated by install-kaihongos.cjs)',
152
- '# Board layout is fixed under ' + BOARD_HOME + ', independent of caller HOME/PATH.',
153
- 'HROOT="' + ROOT + '"',
154
- 'HNODE="' + nodeBin + '"',
155
- '[ -x "$HNODE" ] || for c in node ' + BOARD_HOME + '/dsh-pack/node/bin/node ' + BOARD_HOME + '/.ohos/node/bin/node; do',
156
- ' [ -x "$c" ] && HNODE="$c" && break',
157
- 'done',
158
- '# optional board-wide secrets file (edit or remove — keys normally live in config.json)',
159
- '[ -f ' + BOARD_HOME + '/.config/apikeys.env ] && . ' + BOARD_HOME + '/.config/apikeys.env',
160
- '# board shells run with HOME=/ — force a real writable HOME and a stable state dir',
161
- '[ -z "${HMH_HOME:-}" ] && export HMH_HOME="' + HMH_HOME + '"',
162
- 'export HOME="' + BOARD_HOME + '"',
163
- 'export NODE_ALLOW_JIT="${NODE_ALLOW_JIT:-1}"',
164
- '# drop --jitless inherited from sandbox profiles; board root shell can JIT',
165
- 'NODE_OPTIONS="$(echo "${NODE_OPTIONS:-}" | sed \'s|--jitless||g; s/ */ /g\')"',
166
- 'NODE_OPTIONS="$(echo "$NODE_OPTIONS" | sed \'s/^ *//;s/ *$//\')"',
167
- '[ -n "$NODE_OPTIONS" ] && export NODE_OPTIONS',
168
- '# optional DevEco-layout toolchain shims (hvigorw / ohpm)',
169
- '[ -z "${HM_DEVECO_HOME:-}" ] && [ -d ' + BOARD_HOME + '/.local/hm-devtools ] && export HM_DEVECO_HOME="' + BOARD_HOME + '/.local/hm-devtools"',
170
- 'exec "$HNODE" "$HROOT/node_modules/@hmharness/cli/dist/main.js" "$@"',
171
- '',
172
- ].join('\n');
173
- }
174
-
175
- function writeLauncher(nodeBin) {
176
- const src = launcherSource(nodeBin);
177
- const userBin = path.join(BOARD_HOME, '.local', 'bin');
178
- fs.mkdirSync(userBin, { recursive: true });
179
- fs.writeFileSync(path.join(userBin, 'hmh'), src);
180
- fs.chmodSync(path.join(userBin, 'hmh'), 0o755);
181
- log('launcher: ' + path.join(userBin, 'hmh'));
182
-
183
- // System locations live on the read-only rootfs — remount rw, copy, restore ro.
184
- // /system/bin matters most: isolated tmpfs-namespace terminals (ttyd web
185
- // terminals, containers) see no /usr at all, but /bin -> /system/bin + /data.
186
- for (const sysBin of ['/usr/local/bin', '/system/bin']) {
187
- try { fs.mkdirSync(sysBin, { recursive: true }); } catch (_) { /* exists */ }
188
- const target = path.join(sysBin, 'hmh');
189
- const rw = spawnSync('mount', ['-o', 'remount,rw', '/'], { encoding: 'utf8' });
190
- try {
191
- fs.writeFileSync(target, src);
192
- fs.chmodSync(target, 0o755);
193
- log('launcher: ' + target + (rw.status === 0 ? ' (rootfs remounted rw then ro)' : ''));
194
- } catch (e) {
195
- log('warn: could not write ' + target + ': ' + e.message);
196
- } finally {
197
- if (rw.status === 0) spawnSync('mount', ['-o', 'remount,ro', '/'], { encoding: 'utf8' });
198
- }
199
- }
200
- }
201
-
202
- // ---------- main ------------------------------------------------------------
203
- (async () => {
204
- log('board home: ' + BOARD_HOME);
205
- const nodeBin = findNode();
206
- if (!nodeBin) { console.error('FATAL: no Node >= 22 found (looked at PATH, dsh-pack, .ohos). hmh needs Node >= 22.'); process.exit(1); }
207
- log('node: ' + nodeBin + ' (' + (spawnSync(nodeBin, ['--version'], { encoding: 'utf8' }).stdout || '').trim() + ')');
208
-
209
- if (!BIN_ONLY) {
210
- let pins;
211
- try { pins = await resolveVersions(); }
212
- catch (e) {
213
- log('warn: registry unreachable (' + e.message.slice(0, 80) + ') — falling back to known-good pins');
214
- pins = Object.assign({}, FALLBACK_PINS);
215
- }
216
- for (const n of PACKAGES) log(' @hmharness/' + n + '@' + pins[n]);
217
-
218
- const STAGE = NM + '.new';
219
- fs.rmSync(STAGE, { recursive: true, force: true });
220
- fs.mkdirSync(path.join(STAGE, '@hmharness'), { recursive: true });
221
- for (const name of PACKAGES) {
222
- const ver = pins[name];
223
- const tgz = path.join(ROOT, '.stage.tgz');
224
- process.stdout.write('download ' + name + '@' + ver + ' ... ');
225
- await download(REG + '/@hmharness/' + name + '/-/' + name + '-' + ver + '.tgz', tgz);
226
- const dest = path.join(STAGE, '@hmharness', name);
227
- extract(tgz, dest);
228
- const pkg = JSON.parse(fs.readFileSync(path.join(dest, 'package.json'), 'utf8'));
229
- if (pkg.version !== ver) throw new Error(name + ': unpacked ' + pkg.version + ' != ' + ver);
230
- log('ok');
231
- }
232
- fs.rmSync(path.join(ROOT, '.stage.tgz'), { force: true });
233
-
234
- // syntax-check the staged CLI entrypoint before swapping anything
235
- const main = path.join(STAGE, '@hmharness', 'cli', 'dist', 'main.js');
236
- const chk = spawnSync(nodeBin, ['--check', main], { encoding: 'utf8' });
237
- if (chk.status !== 0) throw new Error('staged main.js failed --check: ' + (chk.stderr || '').slice(0, 200));
238
- log('staged CLI entrypoint OK');
239
-
240
- const BAK = NM + '.bak';
241
- fs.rmSync(BAK, { recursive: true, force: true });
242
- if (fs.existsSync(NM)) fs.renameSync(NM, BAK);
243
- fs.renameSync(STAGE, NM);
244
- log('installed @hmharness/cli@' + pins.cli + ' (previous tree kept at ' + BAK + ')');
245
- }
246
-
247
- writeLauncher(nodeBin);
248
-
249
- // first run: create the state skeleton + blank config (never overwrite)
250
- if (!fs.existsSync(path.join(HMH_HOME, 'config.json'))) {
251
- log('first run: creating config skeleton at ' + HMH_HOME);
252
- const r = spawnSync(nodeBin, [path.join(NM, '@hmharness', 'cli', 'dist', 'main.js'), 'init'], {
253
- encoding: 'utf8', env: Object.assign({}, process.env, { HMH_HOME, HOME: BOARD_HOME }),
254
- });
255
- log((r.stdout || r.stderr || '').trim().split('\n').slice(-3).join('\n'));
256
- }
257
-
258
- console.log('\nnext steps:');
259
- console.log(' 1. put your provider keys in ' + path.join(HMH_HOME, 'config.json'));
260
- console.log(' (presets for 38 vendors: docs/PROVIDERS.md)');
261
- console.log(' 2. hmh check # verify toolchain');
262
- console.log(' 3. hmh tui # or: hmh web start → http://127.0.0.1:7788');
263
- console.log('pitfalls & details: docs/KAIHONGOS.md');
264
- })().catch((e) => { console.error('INSTALL FAILED:', e.message); process.exit(1); });
1
+ #!/usr/bin/env node
2
+ // install-kaihongos.cjs — one-command board installer for @hmharness/cli on
3
+ // TWIN COPY: scripts/install-kaihongos.cjs (repo installs) and
4
+ // packages/cli/board/install-kaihongos.cjs (ships in the npm package - the
5
+ // board auto-update channel runs THIS one, settled design T28). Keep both
6
+ // in sync when bumping FALLBACK_PINS.
7
+ // KaihongOS / OpenHarmony 5.0 boards (no npm, no Python, read-only rootfs).
8
+ //
9
+ // What it does (idempotent, re-run any time):
10
+ // 1. locates a usable Node >= 22 (the running one, or known board paths)
11
+ // 2. resolves the @hmharness/* version set from registry.npmjs.org
12
+ // (offline fallback: known-good pins below)
13
+ // 3. downloads the 10 first-party tarballs and unpacks them under
14
+ // <BOARD_HOME>/.local/hmharness/node_modules (staged, verified, swapped)
15
+ // 4. writes a hardened launcher and installs it into THREE locations:
16
+ // <BOARD_HOME>/.local/bin/hmh (user path, always writable)
17
+ // /usr/local/bin/hmh (default PATH on classic shells)
18
+ // /system/bin/hmh (read-only rootfs, remount dance;
19
+ // ALSO visible inside isolated
20
+ // tmpfs mount-namespace terminals
21
+ // where /bin -> /system/bin)
22
+ // 5. first run: `hmh init` if config.json is missing
23
+ //
24
+ // Usage:
25
+ // node install-kaihongos.cjs # install/upgrade to latest
26
+ // node install-kaihongos.cjs --bin-only # only (re)write launchers
27
+ // node install-kaihongos.cjs --home=/x # non-default board home
28
+ //
29
+ // Only Node core modules are used; tar extraction uses busybox tar.
30
+ const fs = require('fs');
31
+ const path = require('path');
32
+ const https = require('https');
33
+ const { spawnSync } = require('child_process');
34
+
35
+ // ---------- board constants -------------------------------------------------
36
+ let BOARD_HOME = '/data/local/home'; // KaihongOS board home
37
+ let BIN_ONLY = false;
38
+
39
+ for (const a of process.argv.slice(2)) {
40
+ if (a.startsWith('--home=')) BOARD_HOME = a.slice(7);
41
+ else if (a === '--bin-only') BIN_ONLY = true;
42
+ else { console.error('unknown arg:', a); process.exit(2); }
43
+ }
44
+
45
+ const ROOT = path.join(BOARD_HOME, '.local', 'hmharness');
46
+ const NM = path.join(ROOT, 'node_modules');
47
+ const HMH_HOME = path.join(BOARD_HOME, '.hmharness');
48
+ const REG = 'https://registry.npmjs.org';
49
+ const PACKAGES = ['cli', 'web', 'agent', 'kernel', 'sandbox', 'evolution',
50
+ 'domain-ops', 'evaluation', 'observability', 'domain-harmony'];
51
+
52
+ // Known-good pin set (offline fallback when the registry is unreachable).
53
+ const FALLBACK_PINS = {
54
+ cli: '0.23.10', web: '0.23.10', agent: '0.23.10', kernel: '0.23.10',
55
+ sandbox: '0.23.10', evolution: '0.23.10', 'domain-ops': '0.23.10',
56
+ evaluation: '0.23.10', observability: '0.23.10', 'domain-harmony': '0.23.10',
57
+ };
58
+
59
+ // ---------- helpers ---------------------------------------------------------
60
+ function log(msg) { console.log(msg); }
61
+
62
+ function httpsJSON(url, timeoutMs) {
63
+ return new Promise((resolve, reject) => {
64
+ const req = https.request(new URL(url), { headers: { 'User-Agent': 'hmh-kaihongos-installer' }, timeout: timeoutMs || 20000 }, (res) => {
65
+ if (res.statusCode !== 200) { res.resume(); reject(new Error(url + ' -> ' + res.statusCode)); return; }
66
+ const chunks = [];
67
+ res.on('data', (c) => chunks.push(c));
68
+ res.on('end', () => { try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))); } catch (e) { reject(e); } });
69
+ });
70
+ req.on('timeout', () => { req.destroy(new Error('timeout')); });
71
+ req.on('error', reject);
72
+ req.end();
73
+ });
74
+ }
75
+
76
+ function download(url, file) {
77
+ return new Promise((resolve, reject) => {
78
+ let attempt = 0;
79
+ function go() {
80
+ attempt++;
81
+ const req = https.request(new URL(url), { headers: { 'User-Agent': 'hmh-kaihongos-installer' }, timeout: 30000 }, (res) => {
82
+ if (res.statusCode !== 200) { res.resume(); reject(new Error(url + ' -> ' + res.statusCode)); return; }
83
+ const out = fs.createWriteStream(file);
84
+ res.pipe(out);
85
+ out.on('finish', () => out.close(resolve));
86
+ out.on('error', reject);
87
+ });
88
+ req.on('timeout', () => { req.destroy(); retry(); });
89
+ req.on('error', (e) => {
90
+ if (attempt < 10 && /EAI_AGAIN|ENOTFOUND|ECONNRESET|ETIMEDOUT/.test(e.code || '')) setTimeout(retry, 1500 * attempt);
91
+ else reject(e);
92
+ });
93
+ req.end();
94
+ }
95
+ function retry() { if (attempt < 10) go(); else reject(new Error('retries exhausted: ' + url)); }
96
+ go();
97
+ });
98
+ }
99
+
100
+ function extract(tgz, dest) {
101
+ fs.mkdirSync(dest, { recursive: true });
102
+ // busybox tar is present on KaihongOS / OpenHarmony boards and understands
103
+ // --strip-components. (GNU/toybox tar also fine if busybox is missing.)
104
+ const cmds = [
105
+ ['busybox', ['tar', '-xzf', tgz, '-C', dest, '--strip-components=1']],
106
+ ['tar', ['-xzf', tgz, '-C', dest, '--strip-components=1']],
107
+ ];
108
+ for (const [bin, args] of cmds) {
109
+ const r = spawnSync(bin, args, { encoding: 'utf8' });
110
+ if (r.status === 0) return;
111
+ if (r.error && r.error.code !== 'ENOENT') log(' warn: ' + bin + ' tar: ' + (r.stderr || r.error.message).slice(0, 120));
112
+ }
113
+ throw new Error('no usable tar (tried busybox tar, tar)');
114
+ }
115
+
116
+ async function resolveVersions() {
117
+ log('resolving latest @hmharness/cli from registry ...');
118
+ const meta = await httpsJSON(REG + '/@hmharness/cli');
119
+ const cliLatest = meta['dist-tags'].latest;
120
+ const deps = (meta.versions[cliLatest].dependencies) || {};
121
+ const pins = { cli: cliLatest };
122
+ for (const n of PACKAGES.slice(1)) {
123
+ const want = deps['@hmharness/' + n];
124
+ if (want && want !== '*') { pins[n] = want.replace(/[^0-9.]/g, ''); continue; }
125
+ const m = await httpsJSON(REG + '/@hmharness/' + n);
126
+ pins[n] = m['dist-tags'].latest;
127
+ }
128
+ return pins;
129
+ }
130
+
131
+ // ---------- node discovery --------------------------------------------------
132
+ function findNode() {
133
+ const cands = [process.execPath,
134
+ path.join(BOARD_HOME, 'dsh-pack/node/bin/node'),
135
+ path.join(BOARD_HOME, '.ohos/node/bin/node'),
136
+ '/usr/local/bin/node', '/usr/bin/node', '/system/bin/node'];
137
+ for (const c of cands) {
138
+ try {
139
+ fs.accessSync(c, fs.constants.X_OK);
140
+ const v = spawnSync(c, ['--version'], { encoding: 'utf8' });
141
+ if (v.status === 0) { const maj = parseInt((v.stdout || '').replace('v', ''), 10); if (maj >= 22) return c; }
142
+ } catch (_) { /* next */ }
143
+ }
144
+ return null;
145
+ }
146
+
147
+ // ---------- launcher --------------------------------------------------------
148
+ function launcherSource(nodeBin) {
149
+ return [
150
+ '#!/system/bin/sh',
151
+ '# hmh launcher — KaihongOS board install (generated by install-kaihongos.cjs)',
152
+ '# Board layout is fixed under ' + BOARD_HOME + ', independent of caller HOME/PATH.',
153
+ 'HROOT="' + ROOT + '"',
154
+ 'HNODE="' + nodeBin + '"',
155
+ '[ -x "$HNODE" ] || for c in node ' + BOARD_HOME + '/dsh-pack/node/bin/node ' + BOARD_HOME + '/.ohos/node/bin/node; do',
156
+ ' [ -x "$c" ] && HNODE="$c" && break',
157
+ 'done',
158
+ '# optional board-wide secrets file (edit or remove — keys normally live in config.json)',
159
+ '[ -f ' + BOARD_HOME + '/.config/apikeys.env ] && . ' + BOARD_HOME + '/.config/apikeys.env',
160
+ '# board shells run with HOME=/ — force a real writable HOME and a stable state dir',
161
+ '[ -z "${HMH_HOME:-}" ] && export HMH_HOME="' + HMH_HOME + '"',
162
+ 'export HOME="' + BOARD_HOME + '"',
163
+ 'export NODE_ALLOW_JIT="${NODE_ALLOW_JIT:-1}"',
164
+ '# drop --jitless inherited from sandbox profiles; board root shell can JIT',
165
+ 'NODE_OPTIONS="$(echo "${NODE_OPTIONS:-}" | sed \'s|--jitless||g; s/ */ /g\')"',
166
+ 'NODE_OPTIONS="$(echo "$NODE_OPTIONS" | sed \'s/^ *//;s/ *$//\')"',
167
+ '[ -n "$NODE_OPTIONS" ] && export NODE_OPTIONS',
168
+ '# optional DevEco-layout toolchain shims (hvigorw / ohpm)',
169
+ '[ -z "${HM_DEVECO_HOME:-}" ] && [ -d ' + BOARD_HOME + '/.local/hm-devtools ] && export HM_DEVECO_HOME="' + BOARD_HOME + '/.local/hm-devtools"',
170
+ 'exec "$HNODE" "$HROOT/node_modules/@hmharness/cli/dist/main.js" "$@"',
171
+ '',
172
+ ].join('\n');
173
+ }
174
+
175
+ function writeLauncher(nodeBin) {
176
+ const src = launcherSource(nodeBin);
177
+ const userBin = path.join(BOARD_HOME, '.local', 'bin');
178
+ fs.mkdirSync(userBin, { recursive: true });
179
+ fs.writeFileSync(path.join(userBin, 'hmh'), src);
180
+ fs.chmodSync(path.join(userBin, 'hmh'), 0o755);
181
+ log('launcher: ' + path.join(userBin, 'hmh'));
182
+
183
+ // System locations live on the read-only rootfs — remount rw, copy, restore ro.
184
+ // /system/bin matters most: isolated tmpfs-namespace terminals (ttyd web
185
+ // terminals, containers) see no /usr at all, but /bin -> /system/bin + /data.
186
+ for (const sysBin of ['/usr/local/bin', '/system/bin']) {
187
+ try { fs.mkdirSync(sysBin, { recursive: true }); } catch (_) { /* exists */ }
188
+ const target = path.join(sysBin, 'hmh');
189
+ const rw = spawnSync('mount', ['-o', 'remount,rw', '/'], { encoding: 'utf8' });
190
+ try {
191
+ fs.writeFileSync(target, src);
192
+ fs.chmodSync(target, 0o755);
193
+ log('launcher: ' + target + (rw.status === 0 ? ' (rootfs remounted rw then ro)' : ''));
194
+ } catch (e) {
195
+ log('warn: could not write ' + target + ': ' + e.message);
196
+ } finally {
197
+ if (rw.status === 0) spawnSync('mount', ['-o', 'remount,ro', '/'], { encoding: 'utf8' });
198
+ }
199
+ }
200
+ }
201
+
202
+ // ---------- main ------------------------------------------------------------
203
+ (async () => {
204
+ log('board home: ' + BOARD_HOME);
205
+ const nodeBin = findNode();
206
+ if (!nodeBin) { console.error('FATAL: no Node >= 22 found (looked at PATH, dsh-pack, .ohos). hmh needs Node >= 22.'); process.exit(1); }
207
+ log('node: ' + nodeBin + ' (' + (spawnSync(nodeBin, ['--version'], { encoding: 'utf8' }).stdout || '').trim() + ')');
208
+
209
+ if (!BIN_ONLY) {
210
+ let pins;
211
+ try { pins = await resolveVersions(); }
212
+ catch (e) {
213
+ log('warn: registry unreachable (' + e.message.slice(0, 80) + ') — falling back to known-good pins');
214
+ pins = Object.assign({}, FALLBACK_PINS);
215
+ }
216
+ for (const n of PACKAGES) log(' @hmharness/' + n + '@' + pins[n]);
217
+
218
+ const STAGE = NM + '.new';
219
+ fs.rmSync(STAGE, { recursive: true, force: true });
220
+ fs.mkdirSync(path.join(STAGE, '@hmharness'), { recursive: true });
221
+ for (const name of PACKAGES) {
222
+ const ver = pins[name];
223
+ const tgz = path.join(ROOT, '.stage.tgz');
224
+ process.stdout.write('download ' + name + '@' + ver + ' ... ');
225
+ await download(REG + '/@hmharness/' + name + '/-/' + name + '-' + ver + '.tgz', tgz);
226
+ const dest = path.join(STAGE, '@hmharness', name);
227
+ extract(tgz, dest);
228
+ const pkg = JSON.parse(fs.readFileSync(path.join(dest, 'package.json'), 'utf8'));
229
+ if (pkg.version !== ver) throw new Error(name + ': unpacked ' + pkg.version + ' != ' + ver);
230
+ log('ok');
231
+ }
232
+ fs.rmSync(path.join(ROOT, '.stage.tgz'), { force: true });
233
+
234
+ // syntax-check the staged CLI entrypoint before swapping anything
235
+ const main = path.join(STAGE, '@hmharness', 'cli', 'dist', 'main.js');
236
+ const chk = spawnSync(nodeBin, ['--check', main], { encoding: 'utf8' });
237
+ if (chk.status !== 0) throw new Error('staged main.js failed --check: ' + (chk.stderr || '').slice(0, 200));
238
+ log('staged CLI entrypoint OK');
239
+
240
+ const BAK = NM + '.bak';
241
+ fs.rmSync(BAK, { recursive: true, force: true });
242
+ if (fs.existsSync(NM)) fs.renameSync(NM, BAK);
243
+ fs.renameSync(STAGE, NM);
244
+ log('installed @hmharness/cli@' + pins.cli + ' (previous tree kept at ' + BAK + ')');
245
+ }
246
+
247
+ writeLauncher(nodeBin);
248
+
249
+ // first run: create the state skeleton + blank config (never overwrite)
250
+ if (!fs.existsSync(path.join(HMH_HOME, 'config.json'))) {
251
+ log('first run: creating config skeleton at ' + HMH_HOME);
252
+ const r = spawnSync(nodeBin, [path.join(NM, '@hmharness', 'cli', 'dist', 'main.js'), 'init'], {
253
+ encoding: 'utf8', env: Object.assign({}, process.env, { HMH_HOME, HOME: BOARD_HOME }),
254
+ });
255
+ log((r.stdout || r.stderr || '').trim().split('\n').slice(-3).join('\n'));
256
+ }
257
+
258
+ console.log('\nnext steps:');
259
+ console.log(' 1. put your provider keys in ' + path.join(HMH_HOME, 'config.json'));
260
+ console.log(' (presets for 38 vendors: docs/PROVIDERS.md)');
261
+ console.log(' 2. hmh check # verify toolchain');
262
+ console.log(' 3. hmh tui # or: hmh web start → http://127.0.0.1:7788');
263
+ console.log('pitfalls & details: docs/KAIHONGOS.md');
264
+ })().catch((e) => { console.error('INSTALL FAILED:', e.message); process.exit(1); });
@@ -48,41 +48,41 @@ function daemonPid(home) {
48
48
  * latent bug in the old runner). */
49
49
  export function daemonRunnerSource(pidFile, entryAbs) {
50
50
  const entryJson = JSON.stringify(entryAbs);
51
- return `
52
- const { execFile } = require('node:child_process');
53
- const { writeFileSync, unlinkSync } = require('node:fs');
54
- const { join } = require('node:path');
55
- const home = process.env.HMH_HOME || join(require('node:os').homedir(), '.hmharness');
56
- const hmhBin = process.execPath;
57
- const hmhEntry = ${entryJson};
58
- const HOURS = Number(process.env.HMH_EVOLVE_EVERY_HOURS || 6);
59
- function stamp() { return new Date().toISOString(); }
60
- function runHmh(args, timeoutMs) {
61
- return new Promise((resolve) => {
62
- execFile(hmhBin, [hmhEntry, ...args], { timeout: timeoutMs, windowsHide: true }, (err, stdout, stderr) => {
63
- resolve({ err, out: String(stdout || '') + String(stderr || '') });
64
- });
65
- });
66
- }
67
- async function cycle() {
68
- try {
69
- const evo = await runHmh(['evolve'], 600000);
70
- console.log(stamp(), 'evolve cycle done', evo.err ? ('err ' + String(evo.err).slice(0, 120)) : '');
71
- } catch (e) { console.error(stamp(), 'evolve error:', String(e).slice(0, 200)); }
72
- // finetune gate after every evolve cycle - the command itself decides
73
- // (labels threshold, no running job, cooldown, kill-switch) so an
74
- // unattended run is always safe and cheap when nothing is due
75
- try {
76
- const ft = await runHmh(['auto-finetune', '--submit'], 900000);
77
- const interesting = ft.out.split('\\n').filter((l) => l.includes('\\u2713') || l.includes('\\u5fae\\u8c03') || l.includes('ERR')).slice(0, 3);
78
- console.log(stamp(), 'finetune gate:', interesting.join(' | ') || 'not due');
79
- } catch (e) { console.error(stamp(), 'finetune error:', String(e).slice(0, 200)); }
80
- }
81
- writeFileSync(join(home, '${pidFile}'), String(process.pid));
82
- setTimeout(cycle, 30000);
83
- setInterval(cycle, HOURS * 3600000);
84
- process.on('SIGTERM', () => { try { unlinkSync(join(home, '${pidFile}')); } catch {} process.exit(0); });
85
- process.on('SIGINT', () => { try { unlinkSync(join(home, '${pidFile}')); } catch {} process.exit(0); });
51
+ return `
52
+ const { execFile } = require('node:child_process');
53
+ const { writeFileSync, unlinkSync } = require('node:fs');
54
+ const { join } = require('node:path');
55
+ const home = process.env.HMH_HOME || join(require('node:os').homedir(), '.hmharness');
56
+ const hmhBin = process.execPath;
57
+ const hmhEntry = ${entryJson};
58
+ const HOURS = Number(process.env.HMH_EVOLVE_EVERY_HOURS || 6);
59
+ function stamp() { return new Date().toISOString(); }
60
+ function runHmh(args, timeoutMs) {
61
+ return new Promise((resolve) => {
62
+ execFile(hmhBin, [hmhEntry, ...args], { timeout: timeoutMs, windowsHide: true }, (err, stdout, stderr) => {
63
+ resolve({ err, out: String(stdout || '') + String(stderr || '') });
64
+ });
65
+ });
66
+ }
67
+ async function cycle() {
68
+ try {
69
+ const evo = await runHmh(['evolve'], 600000);
70
+ console.log(stamp(), 'evolve cycle done', evo.err ? ('err ' + String(evo.err).slice(0, 120)) : '');
71
+ } catch (e) { console.error(stamp(), 'evolve error:', String(e).slice(0, 200)); }
72
+ // finetune gate after every evolve cycle - the command itself decides
73
+ // (labels threshold, no running job, cooldown, kill-switch) so an
74
+ // unattended run is always safe and cheap when nothing is due
75
+ try {
76
+ const ft = await runHmh(['auto-finetune', '--submit'], 900000);
77
+ const interesting = ft.out.split('\\n').filter((l) => l.includes('\\u2713') || l.includes('\\u5fae\\u8c03') || l.includes('ERR')).slice(0, 3);
78
+ console.log(stamp(), 'finetune gate:', interesting.join(' | ') || 'not due');
79
+ } catch (e) { console.error(stamp(), 'finetune error:', String(e).slice(0, 200)); }
80
+ }
81
+ writeFileSync(join(home, '${pidFile}'), String(process.pid));
82
+ setTimeout(cycle, 30000);
83
+ setInterval(cycle, HOURS * 3600000);
84
+ process.on('SIGTERM', () => { try { unlinkSync(join(home, '${pidFile}')); } catch {} process.exit(0); });
85
+ process.on('SIGINT', () => { try { unlinkSync(join(home, '${pidFile}')); } catch {} process.exit(0); });
86
86
  `;
87
87
  }
88
88
  /**
package/dist/main.js CHANGED
@@ -1126,6 +1126,49 @@ flags:
1126
1126
  }
1127
1127
  return;
1128
1128
  }
1129
+ if (sub === 'slice') {
1130
+ // review P0-2/P0-3: run ONE real task through the full cognitive
1131
+ // pipeline (observe/goal/plan/act/evaluate/learn). act = a REAL agent
1132
+ // run in a subprocess; --check=<command> = INDEPENDENT evaluator
1133
+ // (claim-blind: it inspects the workspace, never the agent output).
1134
+ const task = rest.slice(1).find((a) => !a.startsWith('-'));
1135
+ const check = rest.find((a) => a.startsWith('--check='))?.slice(8);
1136
+ if (!task) {
1137
+ stdout.write('用法: hmh cognitive slice "任务" [--check="验证命令"] — 认知纵切片:观察→目标→计划→执行→独立评估→学习\n');
1138
+ stdout.write(DIM(' --check 的命令只看工作区不看 agent 输出(claim-blind);exit 0=PASS。省略时用结构性检查并如实标注\n'));
1139
+ return;
1140
+ }
1141
+ const { runVerticalSlice, formatSliceReport, independentEvaluator } = await import('@hmharness/cognitive');
1142
+ const sliceCwd = rest.find((a) => a.startsWith('--cwd='))?.slice(6) ?? process.cwd();
1143
+ const { spawnSync } = await import('node:child_process');
1144
+ const report = await runVerticalSlice({
1145
+ home: homeDir(),
1146
+ cwd: sliceCwd,
1147
+ task,
1148
+ act: async () => {
1149
+ // REAL execution: this CLI as a subprocess (its recorder lands the
1150
+ // trajectory + episodic index exactly like any user task)
1151
+ const r = spawnSync(process.execPath, [process.argv[1], task, '--yes'], {
1152
+ cwd: sliceCwd, encoding: 'utf8', timeout: 300_000,
1153
+ env: { ...process.env, NO_COLOR: '1' },
1154
+ });
1155
+ const out = (r.stdout || '') + (r.stderr || '');
1156
+ const claim = `[exit ${r.status}${r.signal ? '/' + r.signal : ''}] ` + out.trim().split('\n').filter(Boolean).slice(-3).join(' | ').slice(0, 240);
1157
+ return { completed: r.status === 0, claim: claim || '(no output)' };
1158
+ },
1159
+ evaluate: check
1160
+ ? independentEvaluator(async (_task, cwd) => {
1161
+ // shell:true lets node do the platform-correct escaping; a raw
1162
+ // cmd.exe /s /c form eats embedded quotes and breaks node -e
1163
+ const r = spawnSync(check, { cwd, encoding: 'utf8', timeout: 120_000, shell: true });
1164
+ const reason = ((r.stdout || '') + (r.stderr || '')).trim().split('\n').filter(Boolean).slice(-2).join(' | ').slice(0, 200);
1165
+ return { pass: r.status === 0, reasons: [r.status === 0 ? 'check command exited 0' : `check exited ${r.status}: ${reason || '(no output)'}`] };
1166
+ })
1167
+ : undefined,
1168
+ });
1169
+ stdout.write(formatSliceReport(report) + '\n');
1170
+ return;
1171
+ }
1129
1172
  if (sub === 'learn') {
1130
1173
  // blueprint M8 live: diagnose -> train memory-target opportunities ->
1131
1174
  // entries land with provenance; promotion continues via evolve bench.
@@ -59,9 +59,16 @@ export declare function isBoardInstall(distDir: string): boolean;
59
59
  * <home> is the segment BEFORE /.local/hmharness - exactly what the
60
60
  * installer's --home flag wants. Pure; tested. */
61
61
  export declare function boardHomeFromDistDir(distDir: string): string;
62
- /** Platform-correct launcher for `npm install -g @hmharness/cli@<v>`.
62
+ /** Platform-correct launcher for installing @hmharness/cli@<v>.
63
+ *
64
+ * Preferred on EVERY platform: run npm's own cli.js through node directly
65
+ * (`node <npm>/bin/npm-cli.js install -g ...`). No .cmd shim, no shell -
66
+ * and therefore nothing that can flash a console window: on Windows the
67
+ * cmd.exe route hid ITS console (windowsHide) but npm.cmd's own node child
68
+ * still opened a visible window on real machines (repro: MainWindowHandle
69
+ * != 0 titled "npm install @hmharness/cli@..." - T27's first attempt).
63
70
  * Pure; tested. */
64
- export declare function buildUpdateCommand(platform: string, version: string): UpdateLaunch;
71
+ export declare function buildUpdateCommand(platform: string, version: string, execPath?: string): UpdateLaunch;
65
72
  /** Model-proposed commands must be an install/update OF THE CLI PACKAGE and
66
73
  * must not touch anything else. Pure; tested. */
67
74
  export declare function isSafeUpdateCommand(cmd: string): boolean;
@@ -7,7 +7,7 @@
7
7
  */
8
8
  import { readFile, writeFile, mkdir } from 'node:fs/promises';
9
9
  import { existsSync } from 'node:fs';
10
- import { join } from 'node:path';
10
+ import { join, dirname } from 'node:path';
11
11
  const REGISTRY = 'https://registry.npmjs.org/-/package/@hmharness/cli/dist-tags';
12
12
  // 5 minutes for auto-update mode (fresh enough to catch new releases same-session);
13
13
  // the check is a single lightweight GET, not worth caching longer
@@ -88,13 +88,26 @@ export function boardHomeFromDistDir(distDir) {
88
88
  const at = d.indexOf('/.local/hmharness/');
89
89
  return at > 0 ? d.slice(0, at) : '/';
90
90
  }
91
- /** Platform-correct launcher for `npm install -g @hmharness/cli@<v>`.
91
+ /** Platform-correct launcher for installing @hmharness/cli@<v>.
92
+ *
93
+ * Preferred on EVERY platform: run npm's own cli.js through node directly
94
+ * (`node <npm>/bin/npm-cli.js install -g ...`). No .cmd shim, no shell -
95
+ * and therefore nothing that can flash a console window: on Windows the
96
+ * cmd.exe route hid ITS console (windowsHide) but npm.cmd's own node child
97
+ * still opened a visible window on real machines (repro: MainWindowHandle
98
+ * != 0 titled "npm install @hmharness/cli@..." - T27's first attempt).
92
99
  * Pure; tested. */
93
- export function buildUpdateCommand(platform, version) {
100
+ export function buildUpdateCommand(platform, version, execPath = process.execPath) {
94
101
  const installArgs = ['install', '-g', '@hmharness/cli@' + version, '--registry=https://registry.npmjs.org/', '--no-fund', '--no-audit'];
102
+ const npmCli = join(dirname(execPath), 'node_modules', 'npm', 'bin', 'npm-cli.js');
103
+ try {
104
+ if (existsSync(npmCli))
105
+ return { file: execPath, args: [npmCli, ...installArgs], shellEscaped: false };
106
+ }
107
+ catch { /* fall through to the shim routes */ }
95
108
  if (platform === 'win32') {
96
- // Node >= 18.20 throws EINVAL when spawning .cmd shims without a shell -
97
- // route through cmd.exe explicitly
109
+ // fallback: Node >= 18.20 throws EINVAL spawning .cmd shims without a
110
+ // shell - route through cmd.exe explicitly (still windowsHide'd)
98
111
  return { file: 'cmd.exe', args: ['/d', '/s', '/c', 'npm ' + installArgs.join(' ')], shellEscaped: true };
99
112
  }
100
113
  return { file: 'npm', args: installArgs, shellEscaped: false };
package/package.json CHANGED
@@ -1,60 +1,60 @@
1
- {
2
- "name": "@hmharness/cli",
3
- "version": "0.23.12",
4
- "description": "hmharness command line: one-shot tasks, an interactive REPL, a fullscreen TUI, the web frontend, and direct tool invocation.",
5
- "type": "module",
6
- "main": "dist/main.js",
7
- "exports": {
8
- ".": {
9
- "types": "./dist/main.d.ts",
10
- "default": "./dist/main.js"
11
- }
12
- },
13
- "types": "dist/main.d.ts",
14
- "bin": {
15
- "hmh": "dist/main.js"
16
- },
17
- "files": [
18
- "dist",
19
- "board"
20
- ],
21
- "engines": {
22
- "node": ">=22"
23
- },
24
- "keywords": [
25
- "harmonyos",
26
- "openharmony",
27
- "ohos",
28
- "agent",
29
- "ai",
30
- "cli",
31
- "coding-agent",
32
- "arkts",
33
- "self-evolving",
34
- "mcp"
35
- ],
36
- "repository": {
37
- "type": "git",
38
- "url": "git+https://github.com/swsgbl/hmharness.git"
39
- },
40
- "homepage": "https://swsgbl.github.io/hmharness/",
41
- "bugs": "https://github.com/swsgbl/hmharness/issues",
42
- "license": "MIT",
43
- "scripts": {
44
- "build": "tsc -p tsconfig.build.json"
45
- },
46
- "dependencies": {
47
- "@hmharness/agent": "0.23.12",
48
- "@hmharness/cognitive": "0.23.12",
49
- "@hmharness/domain-harmony": "0.23.12",
50
- "@hmharness/domain-ops": "0.23.12",
51
- "@hmharness/environments": "0.23.12",
52
- "@hmharness/evaluation": "0.23.12",
53
- "@hmharness/evolution": "0.23.12",
54
- "@hmharness/kernel": "0.23.12",
55
- "@hmharness/observability": "0.23.12",
56
- "@hmharness/sandbox": "0.23.12",
57
- "@hmharness/web": "0.23.12",
58
- "qrcode": "^1.5.4"
59
- }
60
- }
1
+ {
2
+ "name": "@hmharness/cli",
3
+ "version": "0.23.14",
4
+ "description": "hmharness command line: one-shot tasks, an interactive REPL, a fullscreen TUI, the web frontend, and direct tool invocation.",
5
+ "type": "module",
6
+ "main": "dist/main.js",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/main.d.ts",
10
+ "default": "./dist/main.js"
11
+ }
12
+ },
13
+ "types": "dist/main.d.ts",
14
+ "bin": {
15
+ "hmh": "dist/main.js"
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "board"
20
+ ],
21
+ "engines": {
22
+ "node": ">=22"
23
+ },
24
+ "keywords": [
25
+ "harmonyos",
26
+ "openharmony",
27
+ "ohos",
28
+ "agent",
29
+ "ai",
30
+ "cli",
31
+ "coding-agent",
32
+ "arkts",
33
+ "self-evolving",
34
+ "mcp"
35
+ ],
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/swsgbl/hmharness.git"
39
+ },
40
+ "homepage": "https://swsgbl.github.io/hmharness/",
41
+ "bugs": "https://github.com/swsgbl/hmharness/issues",
42
+ "license": "MIT",
43
+ "scripts": {
44
+ "build": "tsc -p tsconfig.build.json"
45
+ },
46
+ "dependencies": {
47
+ "@hmharness/agent": "0.23.14",
48
+ "@hmharness/cognitive": "0.23.14",
49
+ "@hmharness/domain-harmony": "0.23.14",
50
+ "@hmharness/domain-ops": "0.23.14",
51
+ "@hmharness/environments": "0.23.14",
52
+ "@hmharness/evaluation": "0.23.14",
53
+ "@hmharness/evolution": "0.23.14",
54
+ "@hmharness/kernel": "0.23.14",
55
+ "@hmharness/observability": "0.23.14",
56
+ "@hmharness/sandbox": "0.23.14",
57
+ "@hmharness/web": "0.23.14",
58
+ "qrcode": "^1.5.4"
59
+ }
60
+ }