@qalqi/headless-hermes 0.2.0 → 0.3.0

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,259 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ // headless-hermes <doctor|init|mcp> [options]
4
+ //
5
+ // doctor [--json] [<project dir>] (or --dir <project dir>) Is this machine's prebuilt Hermes installed and working, and does it match
6
+ // the React Native project? (checks platform pkg, tools, provenance, RN, bytecode,
7
+ // Node-API versions). Exits 1 on a failed check; warnings don't fail.
8
+ // init [<project dir>] (or --dir <project dir>) Scaffold the agent integration into a project: the MCP
9
+ // server registration, the two skills (.claude/skills/headless-hermes-{verify,port}),
10
+ // an AGENTS.md, a starter .headless/verify.json and the CI workflow that replays it.
11
+ // No build; it only writes files, and never overwrites one that exists.
12
+ // mcp Start the headless-hermes MCP server on stdio (JSON-RPC). Used by MCP clients.
13
+
14
+ const fs = require('fs');
15
+ const path = require('path');
16
+ const { spawnSync } = require('child_process');
17
+ const hh = require('..');
18
+
19
+ const NODE_API_VERSION = 10;
20
+ const args = process.argv.slice(2);
21
+ const command = args.shift();
22
+ const json = args.includes('--json');
23
+
24
+ function optValue(name, def) {
25
+ const i = args.indexOf(name);
26
+ return i !== -1 && args[i + 1] && !args[i + 1].startsWith('-') ? args[i + 1] : def;
27
+ }
28
+ // The project dir: --dir <dir>, or the first argument that isn't an option (as doctor took it in 0.2.1).
29
+ function projectArg() {
30
+ const i = args.indexOf('--dir');
31
+ return optValue('--dir', null) || args.find((a, j) => !a.startsWith('-') && (i === -1 || j !== i + 1)) || '.';
32
+ }
33
+
34
+ if (command === 'mcp') {
35
+ // Run the MCP server in-process (stdio JSON-RPC).
36
+ require(path.join(__dirname, '..', 'mcp-server.js'));
37
+ return;
38
+ }
39
+
40
+ if (command === 'init') {
41
+ runInit(projectArg());
42
+ return;
43
+ }
44
+
45
+ if (command !== 'doctor') {
46
+ console.error('usage: headless-hermes <doctor [--json] [<project dir>] | init [--dir <project dir>] | mcp>');
47
+ process.exit(2);
48
+ }
49
+
50
+ const projectDir = path.resolve(projectArg());
51
+
52
+ // ---------------------------------------------------------------------------
53
+ // init: scaffold the agent integration into a project (templates live in the
54
+ // package's agent/ directory; placeholders are filled with this build's provenance).
55
+ // ---------------------------------------------------------------------------
56
+ function runInit(targetDir) {
57
+ const target = path.resolve(targetDir);
58
+ const pkgRoot = path.join(__dirname, '..');
59
+ const tpl = path.join(pkgRoot, 'agent');
60
+ if (!fs.existsSync(tpl)) {
61
+ console.error('init: agent templates not found in the installed package (this is a source checkout without agent/).');
62
+ process.exit(2);
63
+ }
64
+
65
+ let build = {};
66
+ try {
67
+ build = hh.buildInfo();
68
+ build.version = build.version || require('../package.json').version;
69
+ build.hermesCommit = (build.hermes && build.hermes.commit || '').slice(0, 12);
70
+ build.bytecode = (build.hermes && build.hermes.bytecodeVersion) || null;
71
+ } catch (e) {
72
+ build = { version: require('../package.json').version, hermesCommit: '', bytecode: null };
73
+ }
74
+ const values = {
75
+ '{{NAPI_HOST_VERSION}}': build.version,
76
+ '{{HERMES_COMMIT}}': build.hermesCommit || '(not installed on this machine)',
77
+ '{{NODE_API_VERSION}}': String(NODE_API_VERSION),
78
+ };
79
+
80
+ const out = [];
81
+ const kept = [];
82
+ const copyTree = (srcDir, dstDir) => {
83
+ fs.mkdirSync(dstDir, { recursive: true });
84
+ for (const e of fs.readdirSync(srcDir, { withFileTypes: true })) {
85
+ const s = path.join(srcDir, e.name);
86
+ const d = path.join(dstDir, e.name);
87
+ if (e.isDirectory()) { copyTree(s, d); continue; }
88
+ if (fs.existsSync(d)) { kept.push(path.relative(target, d)); continue; }
89
+ fs.writeFileSync(d, fill(s));
90
+ out.push(path.relative(target, d));
91
+ }
92
+ };
93
+
94
+ // .claude/skills/ + AGENTS.md + .mcp.json + .github/workflows/
95
+ copyTree(path.join(tpl, 'skills'), path.join(target, '.claude', 'skills'));
96
+ copyTree(path.join(tpl, 'github'), path.join(target, '.github'));
97
+ const writeIfAbsent = (rel, content) => {
98
+ const p = path.join(target, rel);
99
+ if (!fs.existsSync(p)) { fs.writeFileSync(p, content); out.push(rel); } else kept.push(rel);
100
+ };
101
+ writeIfAbsent('AGENTS.md', fill(path.join(tpl, 'AGENTS.md')));
102
+ writeIfAbsent('.mcp.json', fill(path.join(tpl, '.mcp.json')));
103
+
104
+ // Starter manifest, pinned to this build when its provenance is known. No tests yet: --verify passes with a note
105
+ // until the agent (or you) adds them.
106
+ const manifest = {
107
+ engine: build.hermesCommit ? { hermesCommit: build.hermesCommit, bytecode: build.bytecode } : {},
108
+ tests: [],
109
+ };
110
+ const manifestPath = path.join(target, '.headless', 'verify.json');
111
+ if (!fs.existsSync(manifestPath)) {
112
+ fs.mkdirSync(path.dirname(manifestPath), { recursive: true });
113
+ fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\n');
114
+ out.push('.headless/verify.json');
115
+ } else kept.push('.headless/verify.json');
116
+
117
+ function fill(p) {
118
+ let t = fs.readFileSync(p, 'utf8');
119
+ for (const [k, v] of Object.entries(values)) t = t.split(k).join(v);
120
+ return t;
121
+ }
122
+
123
+ console.log(`init: wrote ${out.length} file(s) under ${target}`);
124
+ for (const f of out) console.log(` + ${f}`);
125
+ for (const f of kept) console.log(` = ${f} (exists, kept)`);
126
+ console.log('\nAsk your agent: "verify my native module on Hermes", or "port my JSI module to Node-API".');
127
+ console.log('Then run it in CI with: npx napi-host --verify .headless/verify.json');
128
+ process.exit(0);
129
+ }
130
+
131
+ // ---------------------------------------------------------------------------
132
+ // doctor: unchanged from 0.2.1.
133
+ // ---------------------------------------------------------------------------
134
+ const checks = [];
135
+ const add = (status, name, message) => checks.push({ status, name, message });
136
+
137
+ function bytecodeOf(binary) {
138
+ const r = spawnSync(binary, ['--version'], { encoding: 'utf8' });
139
+ const m = /HBC bytecode version:\s*(\d+)/.exec(`${r.stdout || ''}${r.stderr || ''}`);
140
+ return m ? Number(m[1]) : null;
141
+ }
142
+
143
+ function readJson(file) {
144
+ try {
145
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
146
+ } catch {
147
+ return null;
148
+ }
149
+ }
150
+
151
+ // Resolves <name>/package.json as Node would from the project, or from react-native (pnpm keeps transitive
152
+ // dependencies out of the project's node_modules). Returns its directory, or null.
153
+ function resolvePackage(name, from) {
154
+ try {
155
+ return path.dirname(require.resolve(`${name}/package.json`, { paths: from }));
156
+ } catch {
157
+ return null;
158
+ }
159
+ }
160
+
161
+ function findFile(dir, name, depth = 4) {
162
+ if (depth < 0 || !fs.existsSync(dir)) return null;
163
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
164
+ const p = path.join(dir, e.name);
165
+ if (e.isFile() && e.name === name) return p;
166
+ if (e.isDirectory()) {
167
+ const found = findFile(p, name, depth - 1);
168
+ if (found) return found;
169
+ }
170
+ }
171
+ return null;
172
+ }
173
+
174
+ // 1. This machine's prebuilt.
175
+ let info = null;
176
+ let ourBytecode = null;
177
+ try {
178
+ info = hh.buildInfo();
179
+ const where = path.relative(process.cwd(), hh.platformPackageDir());
180
+ add('ok', 'platform', `${process.platform}-${process.arch}: ${where.startsWith('..') ? hh.platformPackageDir() : where}`);
181
+ } catch (e) {
182
+ add('fail', 'platform', e.message);
183
+ }
184
+ if (info) {
185
+ const commit = info.hermes && info.hermes.commit;
186
+ ourBytecode = (info.hermes && info.hermes.bytecodeVersion) || null;
187
+ add('ok', 'build', `@qalqi/headless-hermes ${info.version || require('../package.json').version}, Hermes static_h ${commit ? commit.slice(0, 12) : 'unknown'}, Node-API ${NODE_API_VERSION}`);
188
+ const hermes = hh.bin('hermes');
189
+ const bc = fs.existsSync(hermes) ? bytecodeOf(hermes) : null;
190
+ if (bc === null) {
191
+ add('fail', 'tools', `${hermes} doesn't run (or doesn't report its bytecode version)`);
192
+ } else {
193
+ ourBytecode = bc;
194
+ add('ok', 'tools', `hermes runs; HBC bytecode version ${bc}`);
195
+ }
196
+ }
197
+
198
+ // 2. The project.
199
+ const pkg = readJson(path.join(projectDir, 'package.json'));
200
+ if (!pkg) {
201
+ add('info', 'project', `no package.json in ${projectDir}: project checks skipped`);
202
+ } else {
203
+ const deps = { ...pkg.devDependencies, ...pkg.dependencies };
204
+ const rnDir = resolvePackage('react-native', [projectDir]);
205
+ const rnPkg = rnDir && readJson(path.join(rnDir, 'package.json'));
206
+ if (rnPkg) add('info', 'react-native', `react-native ${rnPkg.version} installed`);
207
+ else if (deps['react-native']) add('info', 'react-native', `react-native ${deps['react-native']} in package.json (not installed)`);
208
+ else add('info', 'react-native', 'no react-native dependency');
209
+
210
+ // The bytecode the app's hermesc writes: precompiled .hbc runs only on a VM with the same bytecode version.
211
+ const hcDir = resolvePackage('hermes-compiler', [projectDir, ...(rnDir ? [rnDir] : [])]);
212
+ const hc = hcDir && readJson(path.join(hcDir, 'package.json'));
213
+ if (!hc) {
214
+ add('info', 'bytecode', 'hermes-compiler not installed: no app bytecode to compare (plain .js always runs)');
215
+ } else {
216
+ const hermesc = findFile(hcDir, process.platform === 'win32' ? 'hermesc.exe' : 'hermesc');
217
+ const appBytecode = hermesc ? bytecodeOf(hermesc) : null;
218
+ if (appBytecode === null) {
219
+ add('warn', 'bytecode', `hermes-compiler ${hc.version}: couldn't run its hermesc to read the bytecode version`);
220
+ } else if (ourBytecode === null) {
221
+ add('warn', 'bytecode', `the app's hermesc (hermes-compiler ${hc.version}) writes bytecode ${appBytecode}; this build's version is unknown`);
222
+ } else if (appBytecode === ourBytecode) {
223
+ add('ok', 'bytecode', `the app's hermesc (hermes-compiler ${hc.version}) and this Hermes both use bytecode ${appBytecode}: its .hbc files run here`);
224
+ } else {
225
+ add('warn', 'bytecode', `the app's hermesc (hermes-compiler ${hc.version}) writes bytecode ${appBytecode}, this Hermes runs ${ourBytecode}: run the .js sources here, not .hbc files, or use a @qalqi/headless-hermes release on bytecode ${appBytecode}`);
226
+ }
227
+ }
228
+
229
+ // Node-API versions the project's addons declare (node-pre-gyp / prebuild: "binary": { "napi_versions": [...] }).
230
+ const nodeModules = path.join(projectDir, 'node_modules');
231
+ const needs = [];
232
+ const scan = (dir) => {
233
+ if (!fs.existsSync(dir)) return;
234
+ for (const name of fs.readdirSync(dir)) {
235
+ if (name.startsWith('.')) continue;
236
+ if (name.startsWith('@')) { scan(path.join(dir, name)); continue; }
237
+ const p = readJson(path.join(dir, name, 'package.json'));
238
+ const versions = p && p.binary && p.binary.napi_versions;
239
+ if (Array.isArray(versions) && versions.length) needs.push({ name: p.name, min: Math.min(...versions) });
240
+ }
241
+ };
242
+ scan(nodeModules);
243
+ const tooNew = needs.filter((n) => n.min > NODE_API_VERSION);
244
+ if (tooNew.length) {
245
+ add('warn', 'node-api', `needs Node-API above ${NODE_API_VERSION}: ${tooNew.map((n) => `${n.name} (${n.min})`).join(', ')}`);
246
+ } else if (needs.length) {
247
+ add('ok', 'node-api', `${needs.length} addon package(s) declare Node-API versions; all within ${NODE_API_VERSION}`);
248
+ } else {
249
+ add('info', 'node-api', 'no installed package declares Node-API versions (binary.napi_versions)');
250
+ }
251
+ }
252
+
253
+ const failed = checks.some((c) => c.status === 'fail');
254
+ if (json) {
255
+ console.log(JSON.stringify({ ok: !failed, checks }, null, 1));
256
+ } else {
257
+ for (const c of checks) console.log(`${c.status.padEnd(5)} ${c.name.padEnd(13)} ${c.message}`);
258
+ }
259
+ process.exit(failed ? 1 : 0);
package/bin/napi-host.js CHANGED
@@ -1,6 +1,43 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
+ // Two modes:
4
+ // npx napi-host <script.js> [addons] [-- args] (default: the native host)
5
+ // npx napi-host --verify [manifest] [--json] (deterministic .headless/verify.json replay, no AI)
6
+ //
7
+ // --verify runs the installed napi-host once per test and diffs stdout against the golden files
8
+ // in the manifest; it is the cheap CI replay. The manifest is written once by an agent.
9
+
3
10
  const { spawnSync } = require('child_process');
4
- const r = spawnSync(require('..').bin('napi-host'), process.argv.slice(2), { stdio: 'inherit' });
11
+ const path = require('path');
12
+
13
+ const args = process.argv.slice(2);
14
+ if (args[0] === '--verify') {
15
+ const manifestPath = args.find((a) => !a.startsWith('--')) || path.join(process.cwd(), '.headless', 'verify.json');
16
+ let verify;
17
+ try { verify = require('../lib/verify.js'); }
18
+ catch { verify = require(path.join(__dirname, '..', 'lib', 'verify.js')); }
19
+
20
+ let report;
21
+ try {
22
+ report = verify.replay(path.resolve(manifestPath), process.cwd());
23
+ } catch (e) {
24
+ console.error(`verify: ${e.message}`);
25
+ process.exit(2);
26
+ }
27
+ if (process.argv.includes('--json')) {
28
+ console.log(JSON.stringify({ ok: report.ok, engine: report.engine, tests: report.tests, note: report.note }, null, 1));
29
+ } else {
30
+ const pin = report.engine;
31
+ console.log(`${pin.ok ? 'ok ' : 'FAIL'} engine ${pin.note}`);
32
+ if (report.note) console.log(`ok ${report.note}`);
33
+ for (const t of report.tests) {
34
+ console.log(`${t.ok ? 'ok ' : 'FAIL'} ${t.name}`);
35
+ if (!t.ok && t.reason) console.log(` ${t.reason.split('\n').join('\n ')}`);
36
+ }
37
+ }
38
+ process.exit(report.ok ? 0 : 1);
39
+ }
40
+
41
+ const r = spawnSync(require('..').bin('napi-host'), args, { stdio: 'inherit' });
5
42
  if (r.error) { console.error(r.error.message); process.exit(1); }
6
43
  process.exit(r.status === null ? 1 : r.status);