@usemosio/cli 0.0.0-stage → 1.0.0-next.2

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/LICENSE-APACHE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ https://www.apache.org/licenses/LICENSE-2.0
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Mosio
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ https://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mosio
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,30 @@
1
- # Temporary Holding Version
1
+ # @usemosio/cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The `mosio` command: agent-first programmatic video on a pinned Chromium.
4
+
5
+ ```sh
6
+ npm i -g @usemosio/cli # or: npx @usemosio/cli init ./my-video
7
+ mosio doctor # what is installed, what is missing and how to fix it
8
+ mosio init ./my-video
9
+ mosio check ./my-video
10
+ mosio render ./my-video -o my-video.mp4 # first run downloads the toolchain (see below)
11
+ mosio studio ./my-video
12
+ mosio mcp install # wire Claude Code, Codex and Cursor to Mosio
13
+ ```
14
+
15
+ Platform: **Linux x86-64** (Debian 13 or similar, glibc). macOS and Windows are not supported yet; use a container.
16
+ Node 22.12 or newer. `mosio` refuses to run as root (Chromium keeps its sandbox on).
17
+
18
+ ## What is in the package
19
+
20
+ - `@usemosio/cli` (this package) is a small launcher. It depends optionally on a platform package,
21
+ `@usemosio/cli-linux-x64`, which carries `bin/mosio`, `bin/mosio-agent`, `toolchain.lock.json`, the kit
22
+ (`scripts/`, `primitives/`, `skills/`, `fixtures/`) and the built Studio.
23
+ - The toolchain is **not** in the package. On first use `mosio` (or `mosio setup`) downloads into `$MOSIO_HOME`
24
+ (default `~/.local/share/mosio/home`), checked against the SHA-256 in `toolchain.lock.json`:
25
+ Chromium (chrome-headless-shell, about 120 MB), a static FFmpeg and ffprobe (GPL-3.0, about 58 MB, downloaded
26
+ for you rather than shipped), and the Inter font (0.9 MB).
27
+ - Chromium needs a few system libraries. `mosio doctor` and `mosio setup` list exactly which are missing and the
28
+ `apt-get` command for them.
29
+
30
+ `MOSIO_NO_FETCH=1` turns the automatic download off. Full guide: docs/INSTALL.md in the repository.
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ // `mosio-agent` from the platform package, with the same MOSIO_HOME / kit environment as `mosio`.
3
+ import { runAgent } from "../lib/launcher.mjs";
4
+
5
+ runAgent(process.argv.slice(2));
package/bin/mosio.js ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { main } from "../lib/launcher.mjs";
3
+
4
+ main().catch((e) => {
5
+ process.stderr.write(`mosio: ${e?.stack ?? e}\n`);
6
+ process.exit(1);
7
+ });
@@ -0,0 +1,66 @@
1
+ // HTTPS download with a SHA-256 check, retries and a progress callback. Node built-ins only.
2
+ import { createHash } from "node:crypto";
3
+ import { createWriteStream } from "node:fs";
4
+ import { rename, rm, mkdir } from "node:fs/promises";
5
+ import { dirname } from "node:path";
6
+ import https from "node:https";
7
+
8
+ const MAX_REDIRECTS = 5;
9
+
10
+ function get(url, redirects = 0) {
11
+ return new Promise((resolve, reject) => {
12
+ let u;
13
+ try { u = new URL(url); } catch { return reject(new Error(`bad URL ${url}`)); }
14
+ if (u.protocol !== "https:") return reject(new Error(`refusing non-https URL ${url}`));
15
+ const req = https.get(u, { headers: { "user-agent": "mosio-cli-setup" } }, (res) => {
16
+ const code = res.statusCode ?? 0;
17
+ if (code >= 300 && code < 400 && res.headers.location) {
18
+ res.resume();
19
+ if (redirects >= MAX_REDIRECTS) return reject(new Error(`too many redirects for ${url}`));
20
+ return resolve(get(new URL(res.headers.location, u).href, redirects + 1));
21
+ }
22
+ if (code !== 200) { res.resume(); return reject(new Error(`HTTP ${code} for ${url}`)); }
23
+ resolve(res);
24
+ });
25
+ req.setTimeout(60_000, () => req.destroy(new Error(`timeout connecting to ${url}`)));
26
+ req.on("error", reject);
27
+ });
28
+ }
29
+
30
+ /**
31
+ * Download `url` to `dest` (through `dest.partial`), checking `sha256` (hex) of the bytes as they arrive.
32
+ * Resolves `{ bytes, sha256 }`. Nothing is left at `dest` unless the hash matched.
33
+ */
34
+ export async function download(url, dest, { sha256, onProgress, retries = 3, label = url } = {}) {
35
+ await mkdir(dirname(dest), { recursive: true });
36
+ const partial = `${dest}.partial-${process.pid}`;
37
+ let lastErr;
38
+ for (let attempt = 1; attempt <= retries; attempt++) {
39
+ try {
40
+ const res = await get(url);
41
+ const total = Number(res.headers["content-length"] ?? 0);
42
+ const hash = createHash("sha256");
43
+ let bytes = 0;
44
+ await new Promise((resolve, reject) => {
45
+ const out = createWriteStream(partial, { mode: 0o600 });
46
+ res.on("data", (c) => { hash.update(c); bytes += c.length; onProgress?.(bytes, total); });
47
+ res.on("error", reject);
48
+ out.on("error", reject);
49
+ out.on("finish", resolve);
50
+ res.pipe(out);
51
+ });
52
+ const got = hash.digest("hex");
53
+ if (sha256 && got !== sha256) {
54
+ throw Object.assign(new Error(`SHA-256 mismatch for ${label}: got ${got}, the lock pins ${sha256}`), { fatal: true });
55
+ }
56
+ await rename(partial, dest);
57
+ return { bytes, sha256: got };
58
+ } catch (e) {
59
+ lastErr = e;
60
+ await rm(partial, { force: true });
61
+ if (e.fatal || attempt === retries) break;
62
+ await new Promise((r) => setTimeout(r, 1000 * attempt));
63
+ }
64
+ }
65
+ throw lastErr;
66
+ }
@@ -0,0 +1,255 @@
1
+ // The `mosio` command of the npm package: finds the platform package that carries the real binaries, makes sure
2
+ // the pinned toolchain is in $MOSIO_HOME, and runs the binary. Everything else (every command, every flag) is the
3
+ // Rust binary's own; this file adds `mosio setup`, a first-run fetch, doctor hints and the stable MCP path.
4
+ import { spawn, spawnSync } from "node:child_process";
5
+ import { createRequire } from "node:module";
6
+ import { cpSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
7
+ import { homedir } from "node:os";
8
+ import { dirname, join } from "node:path";
9
+ import { ensure, loadLock, quickMissing, status, aptHint, missingChromeLibs } from "./toolchain.mjs";
10
+
11
+ const require = createRequire(import.meta.url);
12
+
13
+ const PLATFORMS = {
14
+ "linux-x64": "@usemosio/cli-linux-x64",
15
+ "win32-x64": "@usemosio/cli-win32-x64",
16
+ "darwin-arm64": "@usemosio/cli-darwin-arm64",
17
+ "darwin-x64": "@usemosio/cli-darwin-x64",
18
+ };
19
+
20
+ /** A binary of the platform package (`mosio.exe` on Windows). */
21
+ export const binPath = (root, name, platform = process.platform) => join(root, "bin", platform === "win32" ? `${name}.exe` : name);
22
+
23
+ /** Commands that never start the browser or FFmpeg, so they do not trigger the first-run download. */
24
+ const NO_TOOLCHAIN = new Set(["init", "doctor", "setup", "check", "ids", "log", "status", "diff", "show", "rollback", "commit", "migrate", "registry", "help"]);
25
+
26
+ const err = (m) => process.stderr.write(m.endsWith("\n") ? m : m + "\n");
27
+
28
+ export function platformPackage(platform = process.platform, arch = process.arch) {
29
+ return { key: `${platform}-${arch}`, name: PLATFORMS[`${platform}-${arch}`] };
30
+ }
31
+
32
+ /** The directory of the installed platform package (its bin/ holds mosio and mosio-agent). */
33
+ export function findRoot() {
34
+ if (process.env.MOSIO_PLATFORM_ROOT) return process.env.MOSIO_PLATFORM_ROOT;
35
+ const { key, name } = platformPackage();
36
+ if (!name) {
37
+ err(`mosio: ${key} is not supported yet. Supported: ${Object.keys(PLATFORMS).join(", ")}.\n` +
38
+ ` Other systems can run Mosio in a container: see docs/INSTALL.md.`);
39
+ process.exit(1);
40
+ }
41
+ try {
42
+ return dirname(require.resolve(`${name}/package.json`));
43
+ } catch {
44
+ err(`mosio: the platform package ${name} is not installed.\n` +
45
+ ` It is an optional dependency of @usemosio/cli: reinstall without --omit=optional / --no-optional,\n` +
46
+ ` or install it next to the CLI: npm i -g ${name}`);
47
+ process.exit(1);
48
+ }
49
+ }
50
+
51
+ /** Per-user data directory: %LOCALAPPDATA% on Windows, $XDG_DATA_HOME or ~/.local/share elsewhere. */
52
+ export function dataDir(env = process.env, platform = process.platform) {
53
+ if (platform === "win32") return env.LOCALAPPDATA || join(homedir(), "AppData", "Local");
54
+ return env.XDG_DATA_HOME || join(homedir(), ".local", "share");
55
+ }
56
+
57
+ export function defaultHome(env = process.env, platform = process.platform) {
58
+ if (env.MOSIO_HOME) return env.MOSIO_HOME;
59
+ return join(dataDir(env, platform), "mosio", "home");
60
+ }
61
+
62
+ /** The subcommand, skipping the global flags (`--lock FILE`, `--trust-blender`) that may come before it. */
63
+ export function subcommand(args) {
64
+ for (let i = 0; i < args.length; i++) {
65
+ const a = args[i];
66
+ if (a === "--lock") { i++; continue; }
67
+ if (a.startsWith("--lock=") || a === "--trust-blender") continue;
68
+ return a;
69
+ }
70
+ return undefined;
71
+ }
72
+
73
+ /** Running from the `npx` cache: that directory can be pruned, so MCP configs must not point into it. */
74
+ export function isEphemeral(root, env = process.env) {
75
+ if (env.MOSIO_STABLE === "1") return true;
76
+ if (env.MOSIO_STABLE === "0") return false;
77
+ return /[\\/]_npx[\\/]/.test(root);
78
+ }
79
+
80
+ export function stableDir(version, env = process.env, platform = process.platform) {
81
+ return join(dataDir(env, platform), "mosio", "npm", version);
82
+ }
83
+
84
+ /** Copy the platform package to a directory that outlives the npx cache. Returns the new root. */
85
+ export function makeStable(root, env = process.env) {
86
+ const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
87
+ const dest = stableDir(pkg.version, env);
88
+ if (existsSync(join(dest, ".complete"))) return dest;
89
+ const tmp = `${dest}.tmp-${process.pid}`;
90
+ rmSync(tmp, { recursive: true, force: true });
91
+ mkdirSync(dirname(dest), { recursive: true });
92
+ cpSync(root, tmp, { recursive: true, dereference: true });
93
+ writeFileSync(join(tmp, ".complete"), `${pkg.version}\n`);
94
+ rmSync(dest, { recursive: true, force: true });
95
+ renameSync(tmp, dest);
96
+ return dest;
97
+ }
98
+
99
+ function childEnv(root, home, env = process.env) {
100
+ return { ...env, MOSIO_HOME: home, MOSIO_KIT: env.MOSIO_KIT || root, MOSIO_NODE: env.MOSIO_NODE || process.execPath };
101
+ }
102
+
103
+ /**
104
+ * Pass signals on to the child. On Windows the child shares this console and gets Ctrl-C itself (and cancels
105
+ * cleanly); `child.kill` there would be TerminateProcess, so the launcher only stays alive until the child exits.
106
+ */
107
+ function forwardSignals(child) {
108
+ for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"]) {
109
+ process.on(sig, () => { if (process.platform !== "win32") child.kill(sig); });
110
+ }
111
+ }
112
+
113
+ function exec(root, args, env) {
114
+ const bin = binPath(root, "mosio");
115
+ const child = spawn(bin, args, { stdio: "inherit", env });
116
+ forwardSignals(child);
117
+ child.on("error", (e) => { err(`mosio: cannot start ${bin}: ${e.message}`); process.exit(127); });
118
+ child.on("exit", (code, signal) => {
119
+ if (signal) { process.removeAllListeners(signal); process.kill(process.pid, signal); } else process.exit(code ?? 1);
120
+ });
121
+ }
122
+
123
+ function parseSetup(args) {
124
+ const o = { chromium: true, ffmpeg: true, fonts: true, libraries: true, check: false, force: false, help: false };
125
+ for (const a of args) {
126
+ if (a === "--no-ffmpeg") o.ffmpeg = false;
127
+ else if (a === "--no-libraries") o.libraries = false;
128
+ else if (a === "--no-fonts") o.fonts = false;
129
+ else if (a === "--no-browser") o.chromium = false;
130
+ else if (a === "--check") o.check = true;
131
+ else if (a === "--force") o.force = true;
132
+ else if (a === "-h" || a === "--help") o.help = true;
133
+ else { err(`mosio setup: unknown option ${a} (see mosio setup --help)`); process.exit(2); }
134
+ }
135
+ return o;
136
+ }
137
+
138
+ const SETUP_HELP = `mosio setup [--check] [--force] [--no-ffmpeg] [--no-fonts] [--no-browser] [--no-libraries]
139
+
140
+ Download the pinned toolchain that is not in the npm package into $MOSIO_HOME and check every file against the
141
+ SHA-256 in toolchain.lock.json: Chromium (chrome-headless-shell), a static FFmpeg and ffprobe, the Inter font and the
142
+ scene libraries registry scenes use (GSAP, three.js, lottie-web, d3; from registry.npmjs.org).
143
+ It needs no root, curl, unzip or xz. Prints one JSON document on stdout; progress goes to stderr.
144
+ --check only report what is installed (nothing is downloaded)
145
+ --force download again even when present
146
+ --no-ffmpeg keep the FFmpeg you have (the pinned Debian package, or another build: mosio doctor says if it matches)
147
+ --no-libraries skip the scene libraries (a project that declares one then fails to render)
148
+ MOSIO_HOME where it goes (default ~/.local/share/mosio/home)
149
+ MOSIO_NO_FETCH=1 never download on first use (mosio then stops with a pointer to this command)
150
+ `;
151
+
152
+ async function setup(root, home, args) {
153
+ const o = parseSetup(args);
154
+ if (o.help) { process.stdout.write(SETUP_HELP); return 0; }
155
+ const lock = await loadLock(root);
156
+ if (o.check) {
157
+ const st = await status(home, lock);
158
+ const ok = st.chromium.installed && st.ffmpeg.installed && st.fonts.installed && st.libraries.installed;
159
+ process.stdout.write(JSON.stringify({ ok, mosio_home: home, ...st }, null, 2) + "\n");
160
+ return ok ? 0 : 1;
161
+ }
162
+ try {
163
+ const r = await ensure(home, lock, o, { log: err, force: o.force });
164
+ const ok = r.missing_system_libraries.length === 0;
165
+ if (!ok) err(aptHint(r.missing_system_libraries));
166
+ process.stdout.write(JSON.stringify({ ok, mosio_home: home, ...r, next: ok ? "mosio doctor" : "install the system libraries above, then run mosio doctor" }, null, 2) + "\n");
167
+ return ok ? 0 : 1;
168
+ } catch (e) {
169
+ process.stdout.write(JSON.stringify({ ok: false, code: "E_SETUP", error: `E_SETUP: ${e.message}`, fix: "check the network (HTTPS to storage.googleapis.com, github.com and registry.npmjs.org) and run mosio setup again; nothing partial is kept" }, null, 2) + "\n");
170
+ return 1;
171
+ }
172
+ }
173
+
174
+ /** `mosio doctor` plus what to do about every failure, on stderr (stdout stays the binary's one JSON document). */
175
+ function doctor(root, args, env) {
176
+ const r = spawnSync(binPath(root, "mosio"), args, { env, encoding: "utf8", maxBuffer: 64 << 20 });
177
+ process.stdout.write(r.stdout ?? "");
178
+ process.stderr.write(r.stderr ?? "");
179
+ let report;
180
+ try { report = JSON.parse(r.stdout); } catch { return r.status ?? 1; }
181
+ const bad = (report.checks ?? []).filter((c) => c.status === "fail" || c.status === "blocked");
182
+ if (bad.length) {
183
+ err("\nmosio doctor: what to do");
184
+ const missing = bad.filter((c) => c.fix);
185
+ const seen = new Set();
186
+ for (const c of missing) if (!seen.has(c.fix)) { seen.add(c.fix); err(` - ${c.name}: ${c.fix}`); }
187
+ if (bad.some((c) => /chrome\./.test(c.name))) {
188
+ const libs = existsSync(report.chrome_path ?? "") ? missingChromeLibs(report.chrome_path) : [];
189
+ if (libs.length) err(" - " + aptHint(libs).replace(/\n/g, "\n "));
190
+ else if (!existsSync(report.chrome_path ?? "")) err(" - chromium: not downloaded yet: run `mosio setup`");
191
+ }
192
+ if (bad.some((c) => c.name.startsWith("ffmpeg")) && !seen.has("ffmpeg")) err(" - ffmpeg: `mosio setup` downloads the pinned static build; `mosio setup --no-ffmpeg` keeps your own");
193
+ }
194
+ const curl = spawnSync("curl", ["--version"], { stdio: "ignore" });
195
+ if (curl.error) err(` - note: \`curl\` is not installed; \`mosio registry fetch\` and \`mosio media sfx fetch\` need it${process.platform === "linux" ? " (apt-get install curl)" : ""}`);
196
+ return r.status ?? 1;
197
+ }
198
+
199
+ export async function main(argv = process.argv.slice(2)) {
200
+ const root0 = findRoot();
201
+ const home = defaultHome();
202
+ const env = childEnv(root0, home);
203
+ const cmd = subcommand(argv);
204
+ const isMcpInstall = cmd === "mcp" && (argv.includes("install") || argv.includes("uninstall"));
205
+
206
+ if (cmd === "setup") process.exit(await setup(root0, home, argv.slice(argv.indexOf("setup") + 1)));
207
+ if (cmd === "doctor") process.exit(doctor(root0, argv, env));
208
+
209
+ let root = root0;
210
+ // `mosio mcp install` records the absolute path of the running binary in the agent's config: never an npx cache path
211
+ if (isMcpInstall && isEphemeral(root0)) {
212
+ if (argv.includes("--dry-run")) {
213
+ err(`mosio: running from a temporary npx directory; a real install first copies itself to ${stableDir(JSON.parse(readFileSync(join(root0, "package.json"), "utf8")).version)} (this dry run shows the temporary paths)`);
214
+ } else {
215
+ root = makeStable(root0);
216
+ err(`mosio: copied the install to ${root} so the agent configs do not point into the npx cache`);
217
+ }
218
+ env.MOSIO_KIT = root;
219
+ }
220
+
221
+ // first run: download what the command needs (the browser and FFmpeg are not in the package)
222
+ const asksHelp = argv.includes("--help") || argv.includes("-h");
223
+ const needs = !asksHelp && cmd !== undefined && cmd !== "" && !cmd.startsWith("-") && (!NO_TOOLCHAIN.has(cmd) || (isMcpInstall && !argv.includes("--dry-run")));
224
+ if (needs) {
225
+ const lock = await loadLock(root);
226
+ const missing = await quickMissing(home, lock);
227
+ if (missing.length) {
228
+ if (process.env.MOSIO_NO_FETCH === "1") {
229
+ err(`mosio: ${missing.join(", ")} not installed in ${home} and MOSIO_NO_FETCH=1: run \`mosio setup\` while online.`);
230
+ } else {
231
+ err(`mosio: first run: downloading the pinned toolchain (${missing.join(", ")}) into ${home}; this happens once (mosio setup --check shows the state)`);
232
+ try {
233
+ const r = await ensure(home, lock, { chromium: missing.includes("chromium"), ffmpeg: missing.includes("ffmpeg"), fonts: missing.includes("fonts"), libraries: missing.includes("libraries") }, { log: err });
234
+ if (r.missing_system_libraries.length) err(aptHint(r.missing_system_libraries));
235
+ err(`mosio: toolchain ready (${(r.downloaded_bytes / 1048576).toFixed(0)} MB in ${r.seconds}s)`);
236
+ } catch (e) {
237
+ err(`mosio: E_SETUP: ${e.message}\nmosio: run \`mosio setup\` again when the network works.`);
238
+ process.exit(1);
239
+ }
240
+ }
241
+ }
242
+ }
243
+ exec(root, argv, env);
244
+ }
245
+
246
+
247
+ /** `mosio-agent ...`: run the platform package's agent host. */
248
+ export function runAgent(argv) {
249
+ const root = findRoot();
250
+ const env = childEnv(root, defaultHome());
251
+ const child = spawn(binPath(root, "mosio-agent"), argv, { stdio: "inherit", env });
252
+ forwardSignals(child);
253
+ child.on("error", (e) => { err(`mosio-agent: ${e.message}`); process.exit(127); });
254
+ child.on("exit", (code, signal) => { if (signal) { process.removeAllListeners(signal); process.kill(process.pid, signal); } else process.exit(code ?? 1); });
255
+ }
package/lib/tar.mjs ADDED
@@ -0,0 +1,55 @@
1
+ // Reading a .tgz (an npm package tarball) without a `tar` binary: gunzip, then the ustar headers, with the long names
2
+ // of GNU (`L`) and pax (`x`) entries. Regular files only; links and devices are skipped. Node built-ins only.
3
+ import { gunzipSync } from "node:zlib";
4
+
5
+ function str(buf, start, len) {
6
+ const b = buf.subarray(start, start + len);
7
+ const nul = b.indexOf(0);
8
+ return b.subarray(0, nul < 0 ? b.length : nul).toString("utf8");
9
+ }
10
+
11
+ function octal(buf, start, len) {
12
+ const s = str(buf, start, len).trim();
13
+ return s ? parseInt(s, 8) : 0;
14
+ }
15
+
16
+ /** The `path` record of a pax extended header, if any. */
17
+ function paxPath(data) {
18
+ const text = data.toString("utf8");
19
+ let i = 0;
20
+ while (i < text.length) {
21
+ const sp = text.indexOf(" ", i);
22
+ if (sp < 0) break;
23
+ const len = parseInt(text.slice(i, sp), 10);
24
+ if (!(len > 0)) break;
25
+ const rec = text.slice(sp + 1, i + len - 1);
26
+ const eq = rec.indexOf("=");
27
+ if (eq > 0 && rec.slice(0, eq) === "path") return rec.slice(eq + 1);
28
+ i += len;
29
+ }
30
+ return null;
31
+ }
32
+
33
+ /** Every regular file of a gzipped tarball, as `[{ path, data }]` in archive order. */
34
+ export function readTgz(tgz) {
35
+ const buf = gunzipSync(tgz);
36
+ const out = [];
37
+ let off = 0;
38
+ let longName = null;
39
+ while (off + 512 <= buf.length) {
40
+ const h = buf.subarray(off, off + 512);
41
+ if (h.every((b) => b === 0)) break;
42
+ const size = octal(h, 124, 12);
43
+ const type = String.fromCharCode(h[156] || 48);
44
+ const data = buf.subarray(off + 512, off + 512 + size);
45
+ off += 512 + Math.ceil(size / 512) * 512;
46
+ if (type === "L") { longName = str(data, 0, data.length); continue; }
47
+ if (type === "x") { longName = paxPath(data) ?? longName; continue; }
48
+ if (type === "g") continue;
49
+ const prefix = str(h, 345, 155);
50
+ const name = longName ?? (prefix ? `${prefix}/${str(h, 0, 100)}` : str(h, 0, 100));
51
+ longName = null;
52
+ if (type === "0" || type === "\0" || type === "7") out.push({ path: name.replace(/^\.\//, ""), data: Buffer.from(data) });
53
+ }
54
+ return out;
55
+ }
@@ -0,0 +1,411 @@
1
+ // The first-run toolchain: everything `toolchain.lock.json` pins that is not in the npm package. Chromium, the
2
+ // static FFmpeg, the Inter font, the Noto Color Emoji font and the scene libraries (GSAP, three.js, lottie-web, d3) are
3
+ // downloaded into $MOSIO_HOME and checked against the SHA-256 in the lock, the way scripts/bootstrap.sh does for a
4
+ // checkout. Nothing here needs root, curl, tar, unzip or xz.
5
+ import { createHash } from "node:crypto";
6
+ import { createReadStream, existsSync } from "node:fs";
7
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
8
+ import { spawnSync } from "node:child_process";
9
+ import { createGunzip } from "node:zlib";
10
+ import { createWriteStream } from "node:fs";
11
+ import { pipeline } from "node:stream/promises";
12
+ import { join, dirname, basename, normalize, isAbsolute } from "node:path";
13
+ import { download } from "./download.mjs";
14
+ import { extractZip } from "./zip.mjs";
15
+ import { readTgz } from "./tar.mjs";
16
+
17
+ /** Chromium's runtime libraries, as scripts/bootstrap.sh installs them (Debian 13). */
18
+ export const CHROMIUM_APT = [
19
+ "libnss3", "libatk1.0-0t64", "libatk-bridge2.0-0t64", "libcups2t64", "libdrm2", "libxkbcommon0", "libxcomposite1",
20
+ "libxdamage1", "libxfixes3", "libxrandr2", "libgbm1", "libpango-1.0-0", "libcairo2", "libasound2t64", "libxshmfence1",
21
+ "libdbus-1-3", "fontconfig",
22
+ ];
23
+
24
+ export async function sha256File(file) {
25
+ const h = createHash("sha256");
26
+ await pipeline(createReadStream(file), h);
27
+ return h.digest("hex");
28
+ }
29
+
30
+ /** Chrome for Testing's platform name for a Node platform/arch (`null`: the lock's top-level values, linux64). */
31
+ const CFT = { "darwin-arm64": "mac-arm64", "darwin-x64": "mac-x64", "win32-x64": "win64" };
32
+
33
+ /**
34
+ * The lock as it applies to one platform: `chrome_headless_shell` and `ffmpeg.static` get their `platforms` entry for
35
+ * this platform laid over the top-level (Linux x86-64) values. Versions and licences are shared.
36
+ */
37
+ export function forPlatform(lock, platform = process.platform, arch = process.arch) {
38
+ const key = `${platform}-${arch}`;
39
+ const over = (v, k) => (k && v?.platforms?.[k] ? { ...v, ...v.platforms[k] } : v);
40
+ return {
41
+ ...lock,
42
+ chrome_headless_shell: over(lock.chrome_headless_shell, CFT[key]),
43
+ ffmpeg: { ...lock.ffmpeg, static: over(lock.ffmpeg.static, key === "linux-x64" ? null : key) },
44
+ };
45
+ }
46
+
47
+ export async function loadLock(kitRoot) {
48
+ return forPlatform(JSON.parse(await readFile(join(kitRoot, "toolchain.lock.json"), "utf8")));
49
+ }
50
+
51
+ /** macOS: drop a quarantine attribute (a tarball downloaded with a browser) so Gatekeeper does not block the tools. */
52
+ export function unquarantine(path) {
53
+ if (process.platform === "darwin") run("xattr", ["-dr", "com.apple.quarantine", path]);
54
+ }
55
+
56
+ export function layout(home, lock, platform = process.platform) {
57
+ const c = lock.chrome_headless_shell;
58
+ const exe = platform === "win32" ? ".exe" : "";
59
+ const chromeDir = join(home, "browsers", `chrome-headless-shell-${c.version}`);
60
+ const ff = join(home, "ffmpeg", "bin");
61
+ const font = lock.fonts.download;
62
+ return {
63
+ chromeDir,
64
+ chrome: join(chromeDir, c.binary_relpath),
65
+ ffmpegBin: ff,
66
+ ffmpeg: join(ff, `ffmpeg${exe}`),
67
+ ffprobe: join(ff, `ffprobe${exe}`),
68
+ fontFile: join(home, "fonts", font.file),
69
+ emojiFile: emojiFor(lock, platform) ? join(home, "fonts", emojiFor(lock, platform).file) : null,
70
+ fontConf: join(home, "fontconfig", "fonts.conf"),
71
+ };
72
+ }
73
+
74
+ const mb = (n) => `${(n / 1048576).toFixed(1)} MB`;
75
+
76
+ function run(cmd, args) {
77
+ const r = spawnSync(cmd, args, { encoding: "utf8", timeout: 20_000 });
78
+ return r.error ? null : r;
79
+ }
80
+
81
+ /** True when the machine already has the pinned Debian FFmpeg (and ffprobe): then no download is needed. */
82
+ export function systemFfmpegIsPinned(lock) {
83
+ const want = lock.ffmpeg.version_line;
84
+ const r = run("ffmpeg", ["-hide_banner", "-version"]);
85
+ if (!r || r.status !== 0 || !String(r.stdout).split("\n")[0].startsWith(want)) return false;
86
+ const p = run("ffprobe", ["-hide_banner", "-version"]);
87
+ return !!p && p.status === 0;
88
+ }
89
+
90
+ /**
91
+ * The pinned emoji font, or null where it does not apply: `fonts.emoji.platforms` lists the Node platforms that need
92
+ * it (Linux; Windows and macOS have a system emoji font and Chrome there does not read fontconfig).
93
+ */
94
+ export function emojiFor(lock, platform = process.platform) {
95
+ const e = lock.fonts?.emoji;
96
+ return e && (!e.platforms || e.platforms.includes(platform)) ? e : null;
97
+ }
98
+
99
+ export function systemHasInter() {
100
+ const r = run("fc-list", [":family=Inter"]);
101
+ return !!r && r.status === 0 && String(r.stdout).trim().length > 0;
102
+ }
103
+
104
+ /** True when fontconfig already knows an emoji font the lock accepts (the Debian package fonts-noto-color-emoji). */
105
+ export function systemHasEmoji(lock) {
106
+ const e = emojiFor(lock);
107
+ if (!e) return true;
108
+ const r = run("fc-list", [`:family=${e.family}`]);
109
+ return !!r && r.status === 0 && String(r.stdout).trim().length > 0;
110
+ }
111
+
112
+ async function fileHasSha(file, sha) {
113
+ try { return (await sha256File(file)) === sha; } catch { return false; }
114
+ }
115
+
116
+ /** What is installed, without downloading anything. Hashes every file (a few hundred MB: about a second). */
117
+ export async function status(home, lock) {
118
+ const L = layout(home, lock);
119
+ const c = lock.chrome_headless_shell;
120
+ const s = lock.ffmpeg.static;
121
+ const f = lock.fonts.download;
122
+ const out = {};
123
+ out.chromium = { installed: await fileHasSha(L.chrome, c.binary_sha256), path: L.chrome, version: c.version };
124
+ const ffHome = (await fileHasSha(L.ffmpeg, s.ffmpeg.binary_sha256)) && (await fileHasSha(L.ffprobe, s.ffprobe.binary_sha256));
125
+ const ffSys = !ffHome && systemFfmpegIsPinned(lock);
126
+ out.ffmpeg = { installed: ffHome || ffSys, source: ffHome ? "download" : ffSys ? "system (pinned Debian package)" : null, path: ffHome ? L.ffmpegBin : null, version: s.version };
127
+ const fontHome = await fileHasSha(L.fontFile, f.file_sha256);
128
+ const fontSys = !fontHome && systemHasInter();
129
+ const e = emojiFor(lock);
130
+ const emojiHome = !!e && (await fileHasSha(L.emojiFile, e.file_sha256));
131
+ const emojiSys = !emojiHome && systemHasEmoji(lock);
132
+ out.fonts = {
133
+ installed: (fontHome || fontSys) && (emojiHome || emojiSys),
134
+ source: fontHome ? "download" : fontSys ? "system (fonts-inter)" : null,
135
+ path: fontHome ? L.fontFile : null,
136
+ emoji: { installed: emojiHome || emojiSys, source: emojiHome ? "download" : emojiSys ? "system" : null, path: emojiHome ? L.emojiFile : null },
137
+ };
138
+ const libs = libraries(home, lock);
139
+ out.libraries = { installed: await librariesInstalled(home, lock), source: "download", items: libs.map((l) => `${l.name}@${l.version}`), path: join(home, "lib") };
140
+ return out;
141
+ }
142
+
143
+ // every 1.5 s: MB, percent and speed, so a slow connection never looks like a hang
144
+ function progress(label, log) {
145
+ let last = 0;
146
+ const start = Date.now();
147
+ return (bytes, total) => {
148
+ const now = Date.now();
149
+ if (now - last < 1500 && bytes !== total) return;
150
+ last = now;
151
+ const pct = total ? ` (${Math.floor((bytes / total) * 100)}%)` : "";
152
+ const secs = (now - start) / 1000;
153
+ const rate = secs >= 1 ? `, ${(bytes / 1048576 / secs).toFixed(1)} MB/s` : "";
154
+ log(` ${label}: ${mb(bytes)}${total ? ` of ${mb(total)}` : ""}${pct}${rate}`);
155
+ };
156
+ }
157
+
158
+ async function installChromium(home, lock, log) {
159
+ const c = lock.chrome_headless_shell;
160
+ const L = layout(home, lock);
161
+ const dl = join(home, "downloads");
162
+ const zip = join(dl, `chrome-headless-shell-${c.version}-${c.url.split("/").at(-2)}.zip`);
163
+ log(`Chromium ${c.version} (chrome-headless-shell, ${c.url})`);
164
+ const t0 = Date.now();
165
+ const { bytes } = await download(c.url, zip, { sha256: c.zip_sha256, onProgress: progress("downloading", log), label: "chrome-headless-shell zip" });
166
+ const tmp = `${L.chromeDir}.tmp-${process.pid}`;
167
+ await rm(tmp, { recursive: true, force: true });
168
+ await mkdir(tmp, { recursive: true });
169
+ try {
170
+ await extractZip(zip, tmp);
171
+ if (!(await fileHasSha(join(tmp, c.binary_relpath), c.binary_sha256))) throw new Error("chrome-headless-shell binary SHA-256 mismatch after unzip");
172
+ await rm(L.chromeDir, { recursive: true, force: true });
173
+ await rename(tmp, L.chromeDir);
174
+ unquarantine(L.chromeDir);
175
+ } catch (e) {
176
+ await rm(tmp, { recursive: true, force: true });
177
+ throw e;
178
+ }
179
+ await rm(zip, { force: true });
180
+ log(` installed at ${L.chromeDir}`);
181
+ return { bytes, seconds: (Date.now() - t0) / 1000 };
182
+ }
183
+
184
+ async function gunzipTo(src, dest, sha, mode) {
185
+ const tmp = `${dest}.tmp-${process.pid}`;
186
+ await pipeline(createReadStream(src), createGunzip(), createWriteStream(tmp, { mode }));
187
+ if ((await sha256File(tmp)) !== sha) { await rm(tmp, { force: true }); throw new Error(`${dest}: SHA-256 mismatch after gunzip`); }
188
+ await chmod(tmp, mode);
189
+ await rename(tmp, dest);
190
+ }
191
+
192
+ async function unzipOne(zip, member, dest, sha) {
193
+ const tmp = `${dest}.unzip-${process.pid}`;
194
+ await rm(tmp, { recursive: true, force: true });
195
+ await mkdir(tmp, { recursive: true });
196
+ try {
197
+ await extractZip(zip, tmp);
198
+ const got = join(tmp, member);
199
+ if ((await sha256File(got)) !== sha) throw new Error(`${dest}: SHA-256 mismatch after unzip`);
200
+ await chmod(got, 0o755);
201
+ await rename(got, dest);
202
+ } finally {
203
+ await rm(tmp, { recursive: true, force: true });
204
+ }
205
+ }
206
+
207
+ async function installFfmpeg(home, lock, log) {
208
+ const s = lock.ffmpeg.static;
209
+ const L = layout(home, lock);
210
+ const dl = join(home, "downloads");
211
+ log(`FFmpeg ${s.version} static build (GPL-3.0-or-later; downloaded for you, not shipped in the npm package)`);
212
+ const t0 = Date.now();
213
+ let bytes = 0;
214
+ await mkdir(L.ffmpegBin, { recursive: true });
215
+ // zips by SHA-256: ffmpeg and ffprobe may come from the same archive (Windows), downloaded once
216
+ const zips = new Map();
217
+ for (const [name, spec, dest] of [["ffmpeg", s.ffmpeg, L.ffmpeg], ["ffprobe", s.ffprobe, L.ffprobe]]) {
218
+ if (s.archive === "zip") {
219
+ // macOS builds: one zip per binary holding just `ffmpeg` / `ffprobe`; Windows: one zip, `member` names the file
220
+ let zip = zips.get(spec.zip_sha256);
221
+ if (!zip) {
222
+ zip = join(dl, `ffmpeg-${s.version}-${process.platform}-${process.arch}-${spec.zip_sha256.slice(0, 12)}.zip`);
223
+ const r = await download(spec.url, zip, { sha256: spec.zip_sha256, onProgress: progress(name, log), label: `${name} zip` });
224
+ bytes += r.bytes;
225
+ zips.set(spec.zip_sha256, zip);
226
+ }
227
+ await unzipOne(zip, spec.member ?? name, dest, spec.binary_sha256);
228
+ continue;
229
+ }
230
+ const gz = join(dl, `${name}-${s.version}-linux-x64.gz`);
231
+ const r = await download(spec.url, gz, { sha256: spec.gz_sha256, onProgress: progress(name, log), label: `${name} gz` });
232
+ bytes += r.bytes;
233
+ await gunzipTo(gz, dest, spec.binary_sha256, 0o755);
234
+ await rm(gz, { force: true });
235
+ }
236
+ for (const zip of zips.values()) await rm(zip, { force: true });
237
+ unquarantine(L.ffmpegBin);
238
+ const lic = join(dirname(L.ffmpegBin), "LICENSE.txt");
239
+ const r = await download(s.license_file.url, lic, { sha256: s.license_file.sha256, label: "FFmpeg licence text" });
240
+ bytes += r.bytes;
241
+ log(` installed at ${L.ffmpegBin}`);
242
+ return { bytes, seconds: (Date.now() - t0) / 1000 };
243
+ }
244
+
245
+ async function installFonts(home, lock, log) {
246
+ const f = lock.fonts.download;
247
+ const L = layout(home, lock);
248
+ const t0 = Date.now();
249
+ let bytes = 0;
250
+ if (!(await fileHasSha(L.fontFile, f.file_sha256)) && !systemHasInter()) {
251
+ log(`Font ${f.family} ${f.version} (${f.license})`);
252
+ bytes += (await download(f.url, L.fontFile, { sha256: f.file_sha256, label: "Inter font" })).bytes;
253
+ bytes += (await download(f.license_file.url, join(dirname(L.fontFile), "Inter-LICENSE.txt"), { sha256: f.license_file.sha256, label: "Inter licence" })).bytes;
254
+ }
255
+ // emoji: no project ships an emoji font, so without this every emoji renders as an empty box
256
+ const e = emojiFor(lock);
257
+ if (e && !(await fileHasSha(L.emojiFile, e.file_sha256)) && !systemHasEmoji(lock)) {
258
+ log(`Font ${e.family} ${e.version} (${e.license})`);
259
+ bytes += (await download(e.url, L.emojiFile, { sha256: e.file_sha256, label: "emoji font" })).bytes;
260
+ bytes += (await download(e.license_file.url, join(dirname(L.emojiFile), "NotoColorEmoji-LICENSE.txt"), { sha256: e.license_file.sha256, label: "emoji font licence" })).bytes;
261
+ }
262
+ // the browser reads fontconfig: the system configuration plus the downloaded directory, with the pinned emoji font
263
+ // preferred for the generic "emoji" family (Chromium's fallback for emoji characters asks fontconfig for it)
264
+ const esc = (x) => x.replace(/&/g, "&amp;").replace(/</g, "&lt;");
265
+ const alias = e ? ` <alias binding="same">\n <family>emoji</family>\n <prefer><family>${esc(e.family)}</family></prefer>\n </alias>\n` : "";
266
+ await mkdir(dirname(L.fontConf), { recursive: true });
267
+ await writeFile(
268
+ L.fontConf,
269
+ `<?xml version="1.0"?>\n<!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd">\n<fontconfig>\n <include ignore_missing="yes">/etc/fonts/fonts.conf</include>\n <dir>${esc(dirname(L.fontFile))}</dir>\n <cachedir>${esc(join(dirname(L.fontConf), "cache"))}</cachedir>\n${alias}</fontconfig>\n`,
270
+ );
271
+ log(` installed in ${dirname(L.fontFile)}`);
272
+ return { bytes, seconds: (Date.now() - t0) / 1000 };
273
+ }
274
+
275
+ /**
276
+ * The scene libraries of the lock (`libraries`: GSAP, three.js, lottie-web, d3), each where `mosio` looks for it:
277
+ * `$MOSIO_HOME/lib/<name>@<version>/<file>`, `file` being `file_at`, else the base name of `file_in_tarball`.
278
+ * Registry scenes and recipes declare them (`"libraries": ["gsap@3.15.1"]`), so a render needs them on disk.
279
+ */
280
+ export function libraries(home, lock) {
281
+ return Object.entries(lock.libraries ?? {}).map(([name, l]) => {
282
+ const dir = join(home, "lib", `${name}@${l.version}`);
283
+ return { name, version: l.version, spec: l, dir, file: join(dir, l.file_at ?? basename(l.file_in_tarball)) };
284
+ });
285
+ }
286
+
287
+ async function installLibraries(home, lock, log) {
288
+ const t0 = Date.now();
289
+ let bytes = 0;
290
+ for (const lib of libraries(home, lock)) {
291
+ const l = lib.spec;
292
+ if (await fileHasSha(lib.file, l.file_sha256)) continue;
293
+ log(`Library ${lib.name}@${lib.version} (${l.tarball})`);
294
+ const tgz = join(home, "downloads", `${lib.name}-${lib.version}.tgz`);
295
+ bytes += (await download(l.tarball, tgz, { sha256: l.tarball_sha256, label: `${lib.name} tarball` })).bytes;
296
+ const entries = readTgz(await readFile(tgz));
297
+ // extract_dirs keeps the layout below the package root (three: build/, examples/jsm/); otherwise the one file
298
+ const pick = l.extract_dirs
299
+ ? entries.filter((e) => l.extract_dirs.some((d) => e.path === d || e.path.startsWith(`${d}/`))).map((e) => [e, e.path.split("/").slice(1).join("/")])
300
+ : entries.filter((e) => e.path === l.file_in_tarball).map((e) => [e, basename(e.path)]);
301
+ const tmp = `${lib.dir}.tmp-${process.pid}`;
302
+ await rm(tmp, { recursive: true, force: true });
303
+ try {
304
+ for (const [e, rel] of pick) {
305
+ const n = normalize(rel);
306
+ if (!n || isAbsolute(n) || n.startsWith("..")) throw new Error(`${lib.name}: unsafe path ${e.path} in the tarball`);
307
+ await mkdir(dirname(join(tmp, n)), { recursive: true });
308
+ await writeFile(join(tmp, n), e.data);
309
+ }
310
+ const rel = l.file_at ?? basename(l.file_in_tarball);
311
+ if (!(await fileHasSha(join(tmp, rel), l.file_sha256))) throw new Error(`${lib.name}: SHA-256 mismatch of ${rel} after extraction`);
312
+ await rm(lib.dir, { recursive: true, force: true });
313
+ await mkdir(dirname(lib.dir), { recursive: true });
314
+ await rename(tmp, lib.dir);
315
+ } catch (e) {
316
+ await rm(tmp, { recursive: true, force: true });
317
+ throw e;
318
+ } finally {
319
+ await rm(tgz, { force: true });
320
+ }
321
+ log(` installed at ${lib.dir}`);
322
+ }
323
+ return { bytes, seconds: (Date.now() - t0) / 1000 };
324
+ }
325
+
326
+ async function librariesInstalled(home, lock) {
327
+ for (const lib of libraries(home, lock)) if (!(await fileHasSha(lib.file, lib.spec.file_sha256))) return false;
328
+ return true;
329
+ }
330
+
331
+ const stampFile = (home) => join(home, ".mosio-setup.json");
332
+
333
+ async function readStamp(home) {
334
+ try { return JSON.parse(await readFile(stampFile(home), "utf8")); } catch { return {}; }
335
+ }
336
+
337
+ /**
338
+ * Cheap "is it there" for every command (no hashing: the stamp records the lock hashes `mosio setup` verified, and
339
+ * `mosio` itself re-checks the browser's SHA-256 on every run). Returns the components that are missing.
340
+ */
341
+ export async function quickMissing(home, lock) {
342
+ const L = layout(home, lock);
343
+ const stamp = await readStamp(home);
344
+ const missing = [];
345
+ if (!(stamp.chromium === lock.chrome_headless_shell.binary_sha256 && existsSync(L.chrome))) missing.push("chromium");
346
+ const ffOk = stamp.ffmpeg === lock.ffmpeg.static.ffmpeg.binary_sha256 && existsSync(L.ffmpeg) && existsSync(L.ffprobe);
347
+ if (!ffOk && !systemFfmpegIsPinned(lock)) missing.push("ffmpeg");
348
+ const fontOk = stamp.fonts === lock.fonts.download.file_sha256 && existsSync(L.fontFile);
349
+ const e = emojiFor(lock);
350
+ const emojiOk = !e || (stamp.emoji === e.file_sha256 && existsSync(L.emojiFile));
351
+ if ((!fontOk && !systemHasInter()) || (!emojiOk && !systemHasEmoji(lock))) missing.push("fonts");
352
+ const libs = libraries(home, lock);
353
+ if (libs.length && !(stamp.libraries === libsKey(lock) && libs.every((l) => existsSync(l.file)))) missing.push("libraries");
354
+ return missing;
355
+ }
356
+
357
+ /** What the stamp records for the libraries: their pinned file hashes, so a new lock fetches again. */
358
+ const libsKey = (lock) => Object.values(lock.libraries ?? {}).map((l) => l.file_sha256).join(",");
359
+
360
+ /** The shared libraries `ldd` cannot resolve for the browser (empty when it can start, or ldd is missing). */
361
+ export function missingChromeLibs(chrome) {
362
+ const r = run("ldd", [chrome]);
363
+ if (!r) return [];
364
+ return String(r.stdout).split("\n").filter((l) => l.includes("not found")).map((l) => l.trim().split(/\s+/)[0]);
365
+ }
366
+
367
+ export function aptHint(libs) {
368
+ return `Chromium needs system libraries that are missing (${libs.join(", ")}). On Debian/Ubuntu, as root:\n apt-get install -y --no-install-recommends ${CHROMIUM_APT.join(" ")}`;
369
+ }
370
+
371
+ /**
372
+ * Install what is missing. `want` = { chromium, ffmpeg, fonts, libraries } (booleans; `libraries` left out means yes). Returns a report; throws on a failed
373
+ * download or a hash mismatch (nothing is installed in that case).
374
+ */
375
+ export async function ensure(home, lock, want, { log = () => {}, force = false } = {}) {
376
+ await mkdir(home, { recursive: true });
377
+ const st = force ? {} : await status(home, lock);
378
+ const report = [];
379
+ const t0 = Date.now();
380
+ const steps = [
381
+ ["chromium", want.chromium, st.chromium?.installed, installChromium],
382
+ ["ffmpeg", want.ffmpeg, st.ffmpeg?.installed, installFfmpeg],
383
+ ["fonts", want.fonts, st.fonts?.installed, installFonts],
384
+ ["libraries", want.libraries !== false, st.libraries?.installed, installLibraries],
385
+ ];
386
+ for (const [name, wanted, have, fn] of steps) {
387
+ if (!wanted) { report.push({ name, state: "skipped" }); continue; }
388
+ if (have) { report.push({ name, state: "present", source: st[name].source ?? "download" }); continue; }
389
+ const r = await fn(home, lock, log);
390
+ report.push({ name, state: "installed", bytes: r.bytes, seconds: Number(r.seconds.toFixed(1)) });
391
+ }
392
+ // record what is now verified in $MOSIO_HOME, so later commands can check cheaply
393
+ const after = await status(home, lock);
394
+ const stamp = await readStamp(home);
395
+ if (after.chromium.installed) stamp.chromium = lock.chrome_headless_shell.binary_sha256;
396
+ if (after.ffmpeg.source === "download") stamp.ffmpeg = lock.ffmpeg.static.ffmpeg.binary_sha256;
397
+ if (after.fonts.source === "download") stamp.fonts = lock.fonts.download.file_sha256;
398
+ if (after.fonts.emoji.source === "download") stamp.emoji = emojiFor(lock).file_sha256;
399
+ if (after.libraries.installed) stamp.libraries = libsKey(lock);
400
+ await writeFile(stampFile(home), JSON.stringify(stamp, null, 2) + "\n");
401
+ const L = layout(home, lock);
402
+ let libs = [];
403
+ if (existsSync(L.chrome)) libs = missingChromeLibs(L.chrome);
404
+ return {
405
+ components: report,
406
+ downloaded_bytes: report.reduce((a, r) => a + (r.bytes ?? 0), 0),
407
+ seconds: Number(((Date.now() - t0) / 1000).toFixed(1)),
408
+ missing_system_libraries: libs,
409
+ };
410
+ }
411
+
package/lib/zip.mjs ADDED
@@ -0,0 +1,85 @@
1
+ // Minimal ZIP extractor (stored and deflated entries, no ZIP64, no encryption) so the first-run download needs
2
+ // neither `unzip` nor any npm dependency. The archive's SHA-256 is checked before this runs; this still refuses
3
+ // names that would escape the destination and symbolic links.
4
+ import { open } from "node:fs/promises";
5
+ import { createReadStream, createWriteStream } from "node:fs";
6
+ import { mkdir, chmod } from "node:fs/promises";
7
+ import { createInflateRaw } from "node:zlib";
8
+ import { pipeline } from "node:stream/promises";
9
+ import { dirname, resolve, sep } from "node:path";
10
+
11
+ const EOCD_SIG = 0x06054b50;
12
+ const CEN_SIG = 0x02014b50;
13
+ const LOC_SIG = 0x04034b50;
14
+
15
+ /** The entries of a zip file: [{ name, method, csize, usize, offset, mode }] */
16
+ export async function listZip(file) {
17
+ const fh = await open(file, "r");
18
+ try {
19
+ const { size } = await fh.stat();
20
+ const tailLen = Math.min(size, 65_557);
21
+ const tail = Buffer.alloc(tailLen);
22
+ await fh.read(tail, 0, tailLen, size - tailLen);
23
+ let e = -1;
24
+ for (let i = tailLen - 22; i >= 0; i--) if (tail.readUInt32LE(i) === EOCD_SIG) { e = i; break; }
25
+ if (e < 0) throw new Error("not a zip file (no end-of-central-directory record)");
26
+ const count = tail.readUInt16LE(e + 10);
27
+ const cdSize = tail.readUInt32LE(e + 12);
28
+ const cdOff = tail.readUInt32LE(e + 16);
29
+ if (count === 0xffff || cdSize === 0xffffffff || cdOff === 0xffffffff) throw new Error("ZIP64 archives are not supported");
30
+ const cd = Buffer.alloc(cdSize);
31
+ await fh.read(cd, 0, cdSize, cdOff);
32
+ const out = [];
33
+ let p = 0;
34
+ for (let i = 0; i < count; i++) {
35
+ if (cd.readUInt32LE(p) !== CEN_SIG) throw new Error("corrupt zip central directory");
36
+ const flags = cd.readUInt16LE(p + 8);
37
+ const method = cd.readUInt16LE(p + 10);
38
+ const csize = cd.readUInt32LE(p + 20);
39
+ const usize = cd.readUInt32LE(p + 24);
40
+ const nlen = cd.readUInt16LE(p + 28), xlen = cd.readUInt16LE(p + 30), clen = cd.readUInt16LE(p + 32);
41
+ const ext = cd.readUInt32LE(p + 38);
42
+ const offset = cd.readUInt32LE(p + 42);
43
+ const name = cd.toString("utf8", p + 46, p + 46 + nlen);
44
+ if (flags & 1) throw new Error(`encrypted zip entry ${name}`);
45
+ out.push({ name, method, csize, usize, offset, mode: (ext >>> 16) & 0xffff });
46
+ p += 46 + nlen + xlen + clen;
47
+ }
48
+ return out;
49
+ } finally {
50
+ await fh.close();
51
+ }
52
+ }
53
+
54
+ /** Extract every entry below `destDir`. Returns the number of files written. */
55
+ export async function extractZip(file, destDir, { onlyPrefix } = {}) {
56
+ const entries = await listZip(file);
57
+ const root = resolve(destDir);
58
+ const fh = await open(file, "r");
59
+ let files = 0;
60
+ try {
61
+ for (const en of entries) {
62
+ if (onlyPrefix && !en.name.startsWith(onlyPrefix)) continue;
63
+ const target = resolve(root, en.name);
64
+ if (target !== root && !target.startsWith(root + sep)) throw new Error(`zip entry escapes the destination: ${en.name}`);
65
+ if (en.name.endsWith("/")) { await mkdir(target, { recursive: true }); continue; }
66
+ if ((en.mode & 0o170000) === 0o120000) throw new Error(`zip entry ${en.name} is a symbolic link; refusing`);
67
+ const lh = Buffer.alloc(30);
68
+ await fh.read(lh, 0, 30, en.offset);
69
+ if (lh.readUInt32LE(0) !== LOC_SIG) throw new Error(`corrupt zip local header for ${en.name}`);
70
+ const start = en.offset + 30 + lh.readUInt16LE(26) + lh.readUInt16LE(28);
71
+ await mkdir(dirname(target), { recursive: true });
72
+ const src = createReadStream(file, { start, end: start + en.csize - 1 });
73
+ const dst = createWriteStream(target);
74
+ if (en.csize === 0) { dst.end(); await new Promise((r) => dst.on("close", r)); }
75
+ else if (en.method === 0) await pipeline(src, dst);
76
+ else if (en.method === 8) await pipeline(src, createInflateRaw(), dst);
77
+ else throw new Error(`unsupported zip method ${en.method} for ${en.name}`);
78
+ await chmod(target, en.mode & 0o111 ? 0o755 : 0o644);
79
+ files++;
80
+ }
81
+ } finally {
82
+ await fh.close();
83
+ }
84
+ return files;
85
+ }
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@usemosio/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0-next.2",
4
+ "description": "Mosio: agent-first programmatic video on a pinned Chromium. The `mosio` command (init, check, render, studio, mcp).",
5
+ "license": "MIT OR Apache-2.0",
6
+ "type": "module",
7
+ "bin": {
8
+ "mosio": "bin/mosio.js",
9
+ "mosio-agent": "bin/mosio-agent.js"
10
+ },
11
+ "files": [
12
+ "bin",
13
+ "lib",
14
+ "README.md",
15
+ "LICENSE-MIT",
16
+ "LICENSE-APACHE"
17
+ ],
18
+ "engines": {
19
+ "node": ">=22.12"
20
+ },
21
+ "optionalDependencies": {
22
+ "@usemosio/cli-linux-x64": "1.0.0-next.2",
23
+ "@usemosio/cli-darwin-arm64": "1.0.0-next.2",
24
+ "@usemosio/cli-darwin-x64": "1.0.0-next.2",
25
+ "@usemosio/cli-win32-x64": "1.0.0-next.2"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/usemosio/mosio.git",
33
+ "directory": "packaging/npm/cli"
34
+ },
35
+ "homepage": "https://github.com/usemosio/mosio#readme",
36
+ "keywords": [
37
+ "video",
38
+ "motion-graphics",
39
+ "mcp",
40
+ "agent",
41
+ "render"
42
+ ]
43
+ }