@hmharness/cli 0.23.24 → 0.23.26

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).
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
53
  const FALLBACK_PINS = {
54
- cli: '0.23.24', web: '0.23.24', agent: '0.23.24', kernel: '0.23.24',
55
- sandbox: '0.23.24', evolution: '0.23.24', 'domain-ops': '0.23.24',
56
- evaluation: '0.23.24', observability: '0.23.24', 'domain-harmony': '0.23.24',
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); });
54
+ cli: '0.23.26', web: '0.23.26', agent: '0.23.26', kernel: '0.23.26',
55
+ sandbox: '0.23.26', evolution: '0.23.26', 'domain-ops': '0.23.26',
56
+ evaluation: '0.23.26', observability: '0.23.26', 'domain-harmony': '0.23.26',
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
  /**
@@ -0,0 +1,21 @@
1
+ /**
2
+ * @hmharness/cli - extension chat brain (round 45)
3
+ *
4
+ * The other end of the browser-side chat panel: a compact tool-loop agent
5
+ * turn that reads/acts on the user's CURRENT tab through the live bridge and
6
+ * answers with the user's configured provider (routing 'chat' — the same
7
+ * one the web UI and CLI agent use). One HTTP request = one turn; the
8
+ * transcript between turns lives in the bridge (in-memory).
9
+ */
10
+ import { chat, type ProviderConfig } from '@hmharness/kernel';
11
+ import type { ChatTurnInput, PageAct } from '@hmharness/extension';
12
+ export interface ChatBrainDeps {
13
+ readPage: () => Promise<unknown>;
14
+ act: (act: PageAct) => Promise<unknown>;
15
+ /** audit line sink — page_act is user-visible but still logged */
16
+ log?: (line: string) => void;
17
+ }
18
+ /** Run ONE conversational turn (message + history → reply string). */
19
+ export declare function answerChatTurn(input: ChatTurnInput, deps: ChatBrainDeps): Promise<string>;
20
+ /** The tool loop, separated so tests can inject a fake chat implementation. */
21
+ export declare function runChatTurn(provider: ProviderConfig, input: ChatTurnInput, deps: ChatBrainDeps, chatImpl: typeof chat): Promise<string>;