@motionharness/cli 0.0.16 → 0.0.17

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.
package/README.md CHANGED
@@ -1,6 +1,10 @@
1
1
  # MH CLI
2
2
 
3
- Install the CLI with npm (currently macOS Apple Silicon / arm64 only):
3
+ Install the CLI with npm on macOS Apple Silicon / arm64 or Windows 10/11 x64:
4
+
5
+ Some versions are published for only one platform. Install a version that includes
6
+ your platform; if `latest` omits it, select an older compatible version explicitly
7
+ with `npm install -g @motionharness/cli@<version>`.
4
8
 
5
9
  ```sh
6
10
  npm install -g @motionharness/cli
@@ -15,18 +19,22 @@ Or run without a global installation:
15
19
  npx @motionharness/cli --help
16
20
  ```
17
21
 
18
- Node.js 22.13+ and pnpm 10.x must already be installed. The CLI does not install
22
+ Node.js 22.15+ and pnpm 10.x must already be installed. The CLI does not install
19
23
  or manage them. Project initialization needs registry access to the matching
20
24
  `@motionharness/sdk` and project dependencies. Run `mh skill` for the authoring
21
25
  and Agent guide.
22
26
 
23
27
  `@motionharness/cli` provides the `mh` command and selects an exactly matching
24
28
  platform package. `@motionharness/cli-darwin-arm64` contains the macOS arm64 native
25
- binary; install the main package for the command. Other platforms are not yet
26
- supported. Keep optional dependencies enabled. Installation works with
29
+ binary; `@motionharness/cli-win32-x64` contains `mh.exe`. Install the main package
30
+ for the command. Windows ARM64, WSL and Linux packages are not provided; Linux
31
+ can run from source. Keep optional dependencies enabled. Installation works with
27
32
  `--ignore-scripts`: there are no postinstall hooks or extra binary downloads.
28
33
 
29
- The npm command uses a short Node package resolver and then execs the Rust CLI.
34
+ The npm command verifies the platform package and its version. On macOS it uses
35
+ experimental `process.execve()` to replace Node with Rust; unavailable API support
36
+ produces an upgrade prompt. On Windows it starts and waits for `mh.exe`, preserving
37
+ arguments, stdin/stdout/stderr and exit status.
30
38
  `mh open [directory]` returns a Studio URL and exits without opening a browser.
31
39
  Use `--browser` to open it explicitly. Project commands default to the current
32
40
  working directory (`--project` selects another) and start sessions on demand.
@@ -38,7 +46,11 @@ normal close/reclamation. Node runs only for transient build/dependency tasks;
38
46
  Chrome automation uses Rust chromiumoxide.
39
47
 
40
48
  The binary embeds MH's fixed runtime resources. On first use these expand into
41
- `~/Library/Caches/mh/runtime/<payload-sha256>/`. `MH_CACHE_DIR` can select an
49
+ `~/Library/Caches/mh/runtime/<payload-sha256>/` on macOS or
50
+ `%LOCALAPPDATA%\mh\cache\runtime\<payload-sha256>\` on Windows. Windows authentication
51
+ and daemon state use separate `auth` and `daemon` directories under `%LOCALAPPDATA%\mh`.
52
+ These directories require current-user ownership and private ACLs, with no reparse
53
+ points. `MH_CACHE_DIR` can select an
42
54
  absolute private writable base; `mh doctor` reports the resource location.
43
55
  A damaged cache is an error: stop processes using the affected hash, remove only
44
56
  that hash directory and retry. Older hashes are retained across upgrades.
@@ -73,6 +85,9 @@ are excluded. If a different Node/npm installation is active, switch back to the
73
85
  one that owns MH. Project-local, npx and other package-manager installs receive
74
86
  manual instructions. Standalone binaries must be replaced manually.
75
87
 
88
+ Close active sessions and finish exports before updating. Idle daemons stop
89
+ normally. On Windows a helper outside the npm installation waits for the original
90
+ exe to exit before installation; the wrapper waits for the final result.
76
91
  Updates retain the npm prefix, enable optional dependencies and disable install
77
92
  scripts. Success means the entry package, platform package and native executable
78
93
  all report the requested version. No administrator escalation is attempted. npm
@@ -88,7 +103,8 @@ stderr and show the current/latest versions. Network or cache failures are silen
88
103
  and do not change the command's result. Checks are disabled for non-interactive
89
104
  runs, CI, default JSON output, help and version output. Set `MH_NO_UPDATE_NOTIFIER=1` to opt
90
105
  out. Attempts and results are cached separately under `mh/updates` in the user's
91
- cache directory (on macOS, `~/Library/Caches`, or absolute `XDG_CACHE_HOME`).
106
+ cache directory (macOS: `~/Library/Caches/mh`, Windows: `%LOCALAPPDATA%\mh\cache`,
107
+ or absolute `XDG_CACHE_HOME` with an `mh` subdirectory).
92
108
 
93
109
  Explicit `update --check` bypasses that cache and reports registry errors. Its
94
110
  successful exit status is 0 even when an update is available. Default JSON output returns
package/bin/mh CHANGED
@@ -1,26 +1,50 @@
1
- #!/bin/sh
2
- # npm installs this entry as a symlink. Resolve it without evaluating path text.
3
- mh_entry=$0
4
- mh_links=0
5
- while [ -L "$mh_entry" ]; do
6
- mh_links=$((mh_links + 1))
7
- if [ "$mh_links" -gt 40 ]; then
8
- echo 'mh: too many launcher symlinks' >&2
9
- exit 1
10
- fi
11
- mh_directory=$(CDPATH= cd -P -- "$(dirname -- "$mh_entry")" && pwd) || exit 1
12
- mh_target=$(readlink "$mh_entry") || exit 1
13
- case "$mh_target" in
14
- /*) mh_entry=$mh_target ;;
15
- *) mh_entry=$mh_directory/$mh_target ;;
16
- esac
17
- done
18
- mh_directory=$(CDPATH= cd -P -- "$(dirname -- "$mh_entry")" && pwd) || exit 1
19
- MH_NPM_PACKAGE_JSON=$mh_directory/../package.json
20
- export MH_NPM_PACKAGE_JSON
21
- mh_binary=$(node "$mh_directory/npm-resolve.mjs" "$MH_NPM_PACKAGE_JSON") || exit 1
22
- if [ ! -x "$mh_binary" ]; then
23
- echo 'mh: Cannot start platform binary; reinstall @motionharness/cli with --include=optional' >&2
24
- exit 1
25
- fi
26
- exec "$mh_binary" "$@"
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'node:child_process';
3
+ import { mkdtemp, readFile, copyFile, rm } from 'node:fs/promises';
4
+ import { dirname, join } from 'node:path';
5
+ import { tmpdir } from 'node:os';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { resolveBinary } from './npm-resolve.mjs';
8
+
9
+ const packageJson=join(dirname(fileURLToPath(import.meta.url)),'../package.json');
10
+ const args=process.argv.slice(2);
11
+ async function run(binary,args,env,watchParent=false) {
12
+ return await new Promise((resolve,reject)=> {
13
+ // libuv's default Windows Job kills Node children abruptly on parent exit.
14
+ // The updater must survive just long enough to cancel npm and unlock.
15
+ const child=spawn(binary,args,{env,stdio:watchParent?['inherit','inherit','inherit','ipc']:'inherit',detached:watchParent,windowsHide:true});
16
+ // Native MH receives the console signal; the detached updater receives IPC.
17
+ // Keep the wrapper alive until either finishes cancellation and cleanup.
18
+ const interrupted=()=>{if(watchParent&&child.connected)child.send({type:'cancel'},()=>{});};
19
+ process.on('SIGINT',interrupted);
20
+ child.once('error',reject);
21
+ child.once('close',(code,signal)=>{process.removeListener('SIGINT',interrupted);resolve(code ?? (signal==='SIGINT'?130:1));});
22
+ });
23
+ }
24
+ try {
25
+ const [major,minor]=process.versions.node.split('.').map(Number);
26
+ if(major<22||major===22&&minor<15) throw new Error('MH CLI requires Node.js 22.15 or later. Upgrade Node.js and retry.');
27
+ const binary=resolveBinary(packageJson);
28
+ const env={...process.env,MH_NPM_PACKAGE_JSON:packageJson};
29
+ delete env.MH_WINDOWS_UPDATE_REQUEST;
30
+ if(process.platform!=='win32') {
31
+ if(typeof process.execve!=='function') throw new Error('This Node.js version has no process.execve(). Use Node.js 22.15+ or a supported LTS release.');
32
+ process.execve(binary,[binary,...args],env);
33
+ } else {
34
+ env.MH_WINDOWS_WRAPPER_PID=String(process.pid);
35
+ let temporary;
36
+ try {
37
+ if(args.includes('update')&&!args.includes('--check')&&!args.includes('--help')&&!args.includes('-h')) {
38
+ temporary=await mkdtemp(join(tmpdir(),'mh-update-'));
39
+ env.MH_WINDOWS_UPDATE_REQUEST=join(temporary,'request.json');
40
+ await copyFile(join(dirname(fileURLToPath(import.meta.url)),'windows-update.mjs'),join(temporary,'update.mjs'));
41
+ }
42
+ const code=await run(binary,args,env);
43
+ if(code===0&&temporary) {
44
+ let request;
45
+ try {request=JSON.parse(await readFile(env.MH_WINDOWS_UPDATE_REQUEST,'utf8'));} catch(error) {if(error.code!=='ENOENT') throw error;}
46
+ process.exitCode=request ? await run(process.execPath,[join(temporary,'update.mjs'),env.MH_WINDOWS_UPDATE_REQUEST],env,true) : code;
47
+ } else process.exitCode=code;
48
+ } finally {if(temporary) await rm(temporary,{recursive:true,force:true,maxRetries:10,retryDelay:100});}
49
+ }
50
+ } catch(error) {console.error(`mh: ${error.message}`);process.exitCode=1;}
@@ -4,25 +4,30 @@ import { createRequire } from 'node:module';
4
4
  import { dirname, join, resolve } from 'node:path';
5
5
  import { fileURLToPath, pathToFileURL } from 'node:url';
6
6
 
7
- export const platforms = Object.freeze({ 'darwin-arm64': '@motionharness/cli-darwin-arm64' });
7
+ export const platforms = Object.freeze({ 'darwin-arm64': '@motionharness/cli-darwin-arm64', 'win32-x64': '@motionharness/cli-win32-x64' });
8
8
 
9
9
  export function resolveBinary(packageJson, platform = process.platform, arch = process.arch) {
10
- const name = platforms[`${platform}-${arch}`];
11
- if (!name) throw new Error(`MH does not support ${platform}-${arch}. Supported platforms: ${Object.keys(platforms).join(', ')}.`);
12
10
  const entry = JSON.parse(readFileSync(packageJson, 'utf8'));
13
- let manifestPath;
14
- try { manifestPath = createRequire(packageJson).resolve(`${name}/package.json`); }
11
+ const supported = Object.keys(platforms).filter(id => Object.hasOwn(entry.optionalDependencies ?? {}, platforms[id]));
12
+ const name = platforms[`${platform}-${arch}`];
13
+ if (!name || !supported.includes(`${platform}-${arch}`)) {
14
+ throw new Error(`MH ${entry.version} does not support ${platform}-${arch}. Supported platforms for this version: ${supported.join(', ') || 'none'}. Install a version that includes your platform.`);
15
+ }
16
+ let manifestPath, installed;
17
+ try {
18
+ manifestPath = createRequire(packageJson).resolve(`${name}/package.json`);
19
+ installed = JSON.parse(readFileSync(manifestPath, 'utf8'));
20
+ }
15
21
  catch (error) {
16
- if (error.code !== 'MODULE_NOT_FOUND') throw error;
22
+ if (!['MODULE_NOT_FOUND', 'ENOENT'].includes(error.code)) throw error;
17
23
  throw new Error(`Missing ${name}@${entry.version}. Reinstall @motionharness/cli with optional dependencies enabled (npm install -g @motionharness/cli@${entry.version} --include=optional).`);
18
24
  }
19
- const installed = JSON.parse(readFileSync(manifestPath, 'utf8'));
20
25
  if (installed.name !== name || installed.version !== entry.version || entry.optionalDependencies?.[name] !== entry.version)
21
26
  throw new Error(`MH platform package version mismatch: expected ${name}@${entry.version}, found ${installed.name}@${installed.version}. Reinstall @motionharness/cli.`);
22
- return join(dirname(manifestPath), 'bin', 'mh');
27
+ return join(dirname(manifestPath), 'bin', platform==='win32'?'mh.exe':'mh');
23
28
  }
24
29
 
25
- // Short-lived package resolver. The shell launcher execs the returned binary.
30
+ // Optional diagnostic entry; the unified Node launcher imports this resolver.
26
31
  if (process.argv[1] && pathToFileURL(realpathSync(resolve(process.argv[1]))).href === import.meta.url) {
27
32
  try {
28
33
  const manifest = process.argv[2];
@@ -0,0 +1,97 @@
1
+ // Copied outside the npm installation before the original executable exits.
2
+ import { spawn } from 'node:child_process';
3
+ import { readFile, writeFile, rm, realpath, open } from 'node:fs/promises';
4
+ import { existsSync } from 'node:fs';
5
+ import { join, dirname } from 'node:path';
6
+ import { createRequire } from 'node:module';
7
+ const request=JSON.parse(await readFile(process.argv[2],'utf8'));
8
+ const {prefix,root,packageJson,latest,summary,json,timeoutSeconds}=request;
9
+ let lock, installedStarted=false, interrupted=false, activeChild;
10
+ const deadline=Date.now()+timeoutSeconds*1000;
11
+ const env={...process.env};delete env.MH_WINDOWS_UPDATE_REQUEST;
12
+ const npmScript=join(dirname(process.execPath),'node_modules/npm/bin/npm-cli.js');
13
+ const interrupt=()=>{interrupted=true;activeChild?.kill();};
14
+ process.on('SIGINT',interrupt);process.on('SIGTERM',interrupt);
15
+ // The wrapper waits for our final result. Its IPC pipe also reports forced
16
+ // wrapper termination, so a detached installation cannot keep running.
17
+ process.on('disconnect',interrupt);
18
+ const message=value=>{if(value?.type==='cancel')interrupt();};
19
+ process.on('message',message);
20
+ function available(){if(interrupted)throw new Error('Update interrupted');if(Date.now()>=deadline)throw new Error('Update timed out');}
21
+ function run(program,args) {return new Promise((resolve,reject)=>{
22
+ try{available();}catch(error){reject(error);return;}
23
+ const child=spawn(program,args,{env,windowsHide:true,stdio:['ignore','pipe','pipe']});let stdout='',stderr='';
24
+ activeChild=child;let failure;
25
+ const timer=setTimeout(()=>{failure=new Error('Update timed out');child.kill();},Math.max(1,deadline-Date.now()));
26
+ child.stdout.on('data',b=>{stdout+=b;if(stdout.length>2*1024*1024){failure=new Error('Update output exceeded limit');child.kill();}});child.stderr.on('data',b=>{stderr=(stderr+b).slice(-16000);});
27
+ child.once('error',e=>{clearTimeout(timer);activeChild=undefined;reject(e);});child.once('close',code=>{clearTimeout(timer);activeChild=undefined;interrupted?reject(new Error('Update interrupted')):failure?reject(failure):code===0?resolve(stdout.trim()):reject(new Error(`Update subprocess failed (${code}): ${stderr}`));});
28
+ });}
29
+ const npm=args=>run(process.execPath,[npmScript,...args]);
30
+ const pause=async()=>{available();await new Promise(resolve=>setTimeout(resolve,100));available();};
31
+ function newer(a,b) {
32
+ const parse=value=>{const match=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(value);if(!match)throw new Error('Invalid installed version');return [match.slice(1,4).map(BigInt),match[4]?.split('.')];};
33
+ const [av,ap]=parse(a),[bv,bp]=parse(b);
34
+ for(let i=0;i<3;i++)if(av[i]!==bv[i])return av[i]>bv[i];
35
+ if(!ap||!bp)return !ap&&Boolean(bp);
36
+ for(let i=0;i<Math.max(ap.length,bp.length);i++) {
37
+ if(ap[i]===bp[i])continue;if(ap[i]===undefined)return false;if(bp[i]===undefined)return true;
38
+ const an=/^\d+$/.test(ap[i]),bn=/^\d+$/.test(bp[i]);
39
+ return an&&bn?BigInt(ap[i])>BigInt(bp[i]):an!==bn?!an:ap[i]>bp[i];
40
+ }
41
+ return false;
42
+ }
43
+ async function acquire() {
44
+ while(Date.now()<deadline) {
45
+ available();
46
+ try {await writeFile(lock,JSON.stringify({pid:process.pid,createdAt:Date.now()}),{flag:'wx'});return;}
47
+ catch(error) {
48
+ if(error.code!=='EEXIST')throw error;
49
+ let owner;
50
+ try {owner=JSON.parse(await readFile(lock,'utf8'));}catch(error){if(error.code==='ENOENT'||error instanceof SyntaxError){await pause();continue;}throw error;}
51
+ if(!Number.isInteger(owner.pid)||owner.pid<1)throw new Error(`Invalid update lock: ${lock}`);
52
+ try{process.kill(owner.pid,0);}catch(error){if(error.code==='ESRCH')throw new Error(`Stale update lock: ${lock}. Remove it after confirming no update is running.`);throw error;}
53
+ await pause();
54
+ }
55
+ }
56
+ throw new Error('Update timed out waiting for the installation lock');
57
+ }
58
+ try {
59
+ if(!existsSync(npmScript))throw new Error('Cannot locate the Node installation’s npm entry');
60
+ if(await realpath(join(prefix,'node_modules'))!==await realpath(root)||await realpath(packageJson)!==join(await realpath(root),'@motionharness','cli','package.json'))throw new Error('npm global installation identity changed');
61
+ lock=join(root,'@motionharness/.mh-update.lock');
62
+ await acquire();
63
+ const manifest=JSON.parse(await readFile(packageJson,'utf8'));
64
+ if(manifest.name!=='@motionharness/cli')throw new Error('Invalid npm entry package');
65
+ summary.currentVersion=manifest.version;summary.updateAvailable=newer(latest,manifest.version);
66
+ if(!summary.updateAvailable) {
67
+ console.log(json?JSON.stringify(summary):`MH is up to date (${manifest.version})`);
68
+ } else {
69
+ // A stopping daemon may remove its descriptor just before exiting. Verify
70
+ // Windows has released the old image before asking npm to replace it.
71
+ const platformManifest = () => createRequire(packageJson).resolve('@motionharness/cli-win32-x64/package.json');
72
+ const oldBinary=join(dirname(platformManifest()),'bin/mh.exe');
73
+ while(true) {
74
+ available();
75
+ try {const file=await open(oldBinary,'r+');await file.close();break;}
76
+ catch(error) {if(!['EBUSY','EPERM','EACCES'].includes(error.code))throw error;if(Date.now()>=deadline)throw new Error('Close other MH commands before updating; the executable is still in use');await pause();}
77
+ }
78
+ installedStarted=true;
79
+ await npm(['install','--global','--prefix',prefix,`@motionharness/cli@${latest}`,'--include=optional','--ignore-scripts','--no-audit','--no-fund']);
80
+ const installed=JSON.parse(await readFile(packageJson,'utf8'));
81
+ const platformJson=platformManifest();
82
+ const platform=JSON.parse(await readFile(platformJson,'utf8'));
83
+ if(installed.version!==latest||platform.name!=='@motionharness/cli-win32-x64'||platform.version!==latest||installed.optionalDependencies?.[platform.name]!==latest)throw new Error('Installed package versions differ');
84
+ if(await run(join(dirname(platformJson),'bin/mh.exe'),['--version'])!==`mh ${latest}`)throw new Error('Installed binary version differs');
85
+ summary.updated=true;summary.installedVersion=latest;
86
+ console.log(json?JSON.stringify(summary):`MH updated: ${summary.currentVersion} → ${latest}`);
87
+ }
88
+ } catch(error) {
89
+ const repair=`npm install -g --prefix "${prefix}" @motionharness/cli@${latest} --include=optional --ignore-scripts`;
90
+ console.error(JSON.stringify({error:installedStarted?`${error.message}\nInstallation may be incomplete. Repair the same npm prefix with: ${repair}`:error.message}));process.exitCode=interrupted?130:1;
91
+ } finally {
92
+ if(lock) {try{const owner=JSON.parse(await readFile(lock,'utf8'));if(owner.pid===process.pid)await rm(lock);}catch{}}
93
+ process.removeListener('SIGINT',interrupt);process.removeListener('SIGTERM',interrupt);
94
+ process.removeListener('disconnect',interrupt);
95
+ process.removeListener('message',message);
96
+ if(process.connected)process.disconnect();
97
+ }
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
- "version": "0.0.16",
2
+ "version": "0.0.17",
3
3
  "license": "Apache-2.0",
4
4
  "type": "module",
5
5
  "engines": {
6
- "node": ">=22.13.0"
6
+ "node": ">=22.15.0"
7
7
  },
8
8
  "publishConfig": {
9
9
  "access": "public",
@@ -14,12 +14,19 @@
14
14
  "bin": {
15
15
  "mh": "bin/mh"
16
16
  },
17
+ "os": [
18
+ "darwin"
19
+ ],
20
+ "cpu": [
21
+ "arm64"
22
+ ],
17
23
  "optionalDependencies": {
18
- "@motionharness/cli-darwin-arm64": "0.0.16"
24
+ "@motionharness/cli-darwin-arm64": "0.0.17"
19
25
  },
20
26
  "files": [
21
27
  "bin/mh",
22
28
  "bin/npm-resolve.mjs",
29
+ "bin/windows-update.mjs",
23
30
  "README.md",
24
31
  "LICENSE"
25
32
  ]