Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

The agent shell's Node core speaks Windows: platform, arch, ppid, paths, file URLs (#169)

shinyobjectz3f9d5eda2d71
diff --git a/engine/native/src/js.rs b/engine/native/src/js.rs
index e1a1eb0b..572ca366 100644
--- a/engine/native/src/js.rs
+++ b/engine/native/src/js.rs
@@ -186,7 +186,9 @@ fn run_here(root: &Path, cwd: &Path, entry: Entry, argv: Vec<String>, env: serde
let globals = [
("__raea_argv", json!(argv)),
("__raea_env", Value::Object(env)),
- ("__raea_platform", json!(if cfg!(target_os = "ios") { "ios" } else { std::env::consts::OS })),
+ // process.platform in Node's words (darwin, win32, linux): until 0.1.8 Rust's (macos, windows), so the agent
+ // shell's every test for a Mac or a Windows PC was false (#169)
+ ("__raea_platform", json!(match std::env::consts::OS { "macos" => "darwin", "windows" => "win32", os => os })),
("__raea_stdin", json!(stdin)),
("__raea_cwd", json!(cwd.display().to_string())),
];
diff --git a/engine/native/src/node.js b/engine/native/src/node.js
index 840ffe71..4fce2e4e 100644
--- a/engine/native/src/node.js
+++ b/engine/native/src/node.js
@@ -97,7 +97,12 @@
return encoding ? b.toString(encoding) : b;
};
- // ---- path (POSIX) -------------------------------------------------------------------------------------------------
+ // ---- path ---------------------------------------------------------------------------------------------------------
+ // POSIX's, and on Windows Windows' parsing: a drive's root (C:\), a share's (\\server\share\) and the cwd's drive's
+ // (\) start an absolute path, and \ separates as / does. A Windows path comes out with / (which Windows' calls all
+ // take), so the tools' own "a/b" joins, splits and prefix tests hold there too. Until 0.1.8 every Windows path was a
+ // relative one here: resolve(".") named "/C:\Users\...", no folder at all, and isAbsolute("C:\x") was false (#169).
+ const win = g.process.platform === "win32";
const normalizeParts = (parts, abs) => {
const out = [];
for (const p of parts) {
@@ -107,48 +112,79 @@
}
return out;
};
- const path = {
- sep: "/", delimiter: ":",
- normalize(p) {
- if (p === "") return ".";
- const abs = p.startsWith("/"), trail = p.endsWith("/");
- let s = normalizeParts(p.split("/"), abs).join("/");
- if (!s && !abs) s = ".";
- if (s && trail) s += "/";
- return (abs ? "/" : "") + s;
- },
- join(...a) { const s = a.filter((x) => x !== "").join("/"); return s ? path.normalize(s) : "."; },
- resolve(...a) {
- let r = "";
- for (let i = a.length - 1; i >= 0 && !r.startsWith("/"); i--) if (a[i]) r = a[i] + (r ? "/" + r : "");
- if (!r.startsWith("/")) r = proc.cwd() + (r ? "/" + r : "");
- const s = "/" + normalizeParts(r.split("/"), true).join("/");
- return s;
- },
- isAbsolute: (p) => p.startsWith("/"),
- dirname(p) {
- if (!p) return ".";
- const s = p.replace(/\/+$/, "");
- if (!s) return "/";
- const i = s.lastIndexOf("/");
- return i < 0 ? "." : i === 0 ? "/" : s.slice(0, i);
- },
- basename(p, ext) {
- let b = p.replace(/\/+$/, "");
- b = b.slice(b.lastIndexOf("/") + 1);
- return ext && b.endsWith(ext) && b !== ext ? b.slice(0, -ext.length) : b;
- },
- extname(p) { const b = path.basename(p); const i = b.lastIndexOf("."); return i <= 0 ? "" : b.slice(i); },
- relative(from, to) {
- const f = path.resolve(from).split("/").filter(Boolean), t = path.resolve(to).split("/").filter(Boolean);
- let i = 0;
- while (i < f.length && i < t.length && f[i] === t[i]) i++;
- return [...Array(f.length - i).fill(".."), ...t.slice(i)].join("/");
- },
- parse(p) { const base = path.basename(p), ext = path.extname(p); return { root: p.startsWith("/") ? "/" : "", dir: path.dirname(p), base, ext, name: ext ? base.slice(0, -ext.length) : base }; },
- format(o) { return (o.dir ? o.dir + "/" : o.root || "") + (o.base || (o.name || "") + (o.ext || "")); },
+ /** path for POSIX or (`windows`) Windows, its paths written with / */
+ const pathFor = (windows) => {
+ const slash = windows ? (x) => String(x).replace(/\\/g, "/") : (x) => String(x);
+ // the root an absolute path starts with, "" for a relative one: "/", and on Windows "C:/" or "//server/share/"
+ const rootOf = (x) => {
+ if (!windows) return x.startsWith("/") ? "/" : "";
+ const share = /^\/\/[^/]+\/[^/]+(?:\/|$)/.exec(x);
+ if (share) return share[0].endsWith("/") ? share[0] : share[0] + "/";
+ const drive = /^[A-Za-z]:\//.exec(x);
+ return drive ? drive[0] : x.startsWith("/") ? "/" : "";
+ };
+ // Windows' names don't care about case
+ const same = windows ? (a, b) => a.toLowerCase() === b.toLowerCase() : (a, b) => a === b;
+ const P = {
+ sep: "/", delimiter: windows ? ";" : ":",
+ normalize(x) {
+ x = slash(x);
+ if (x === "") return ".";
+ const root = rootOf(x), trail = x.endsWith("/") && x.length > root.length;
+ let s = normalizeParts(x.slice(root.length).split("/"), !!root).join("/");
+ if (!s && !root) s = ".";
+ if (s && trail) s += "/";
+ return root + s;
+ },
+ join(...a) { const s = a.filter((x) => x !== "").join("/"); return s ? P.normalize(s) : "."; },
+ resolve(...a) {
+ let r = "";
+ for (let i = a.length - 1; i >= 0 && !rootOf(r); i--) if (a[i]) r = slash(a[i]) + (r ? "/" + r : "");
+ const here = slash(proc.cwd());
+ if (!rootOf(r)) r = here + (r ? "/" + r : "");
+ // a bare \ on Windows is the cwd's drive's root
+ if (windows && rootOf(r) === "/") r = (/^[A-Za-z]:/.exec(here) || [""])[0] + r;
+ const root = rootOf(r);
+ return root + normalizeParts(r.slice(root.length).split("/"), true).join("/");
+ },
+ isAbsolute: (x) => rootOf(slash(x)) !== "",
+ dirname(x) {
+ if (!x) return ".";
+ x = slash(x);
+ const root = rootOf(x), s = x.replace(/\/+$/, "");
+ if (s.length < root.length) return root;
+ const i = s.lastIndexOf("/");
+ return i < 0 ? "." : i < root.length ? root : s.slice(0, i);
+ },
+ basename(x, ext) {
+ x = slash(x);
+ let b = x.replace(/\/+$/, "");
+ b = b.length < rootOf(x).length ? "" : b.slice(b.lastIndexOf("/") + 1);
+ return ext && b.endsWith(ext) && b !== ext ? b.slice(0, -ext.length) : b;
+ },
+ extname(x) { const b = P.basename(x); const i = b.lastIndexOf("."); return i <= 0 ? "" : b.slice(i); },
+ relative(from, to) {
+ const a = P.resolve(from), b = P.resolve(to);
+ // another drive (or share) on Windows: no way there but the whole path
+ if (!same(rootOf(a), rootOf(b))) return b;
+ const f = a.slice(rootOf(a).length).split("/").filter(Boolean), t = b.slice(rootOf(b).length).split("/").filter(Boolean);
+ let i = 0;
+ while (i < f.length && i < t.length && same(f[i], t[i])) i++;
+ return [...Array(f.length - i).fill(".."), ...t.slice(i)].join("/");
+ },
+ parse(x) { const base = P.basename(x), ext = P.extname(x); return { root: rootOf(slash(x)), dir: P.dirname(x), base, ext, name: ext ? base.slice(0, -ext.length) : base }; },
+ format(o) { return (o.dir ? o.dir + "/" : o.root || "") + (o.base || (o.name || "") + (o.ext || "")); },
+ };
+ return P;
};
- path.posix = path;
+ const path = pathFor(win);
+ path.posix = win ? pathFor(false) : path;
+ // Windows' parsing on any system (Node's path.win32 writes \; this one /, as raea's Windows does)
+ path.win32 = win ? path : pathFor(true);
+ path.posix.posix = path.win32.posix = path.posix;
+ path.posix.win32 = path.win32.win32 = path.win32;
+ /** a path a native gave, as path writes it: / on Windows */
+ const fwd = win ? (x) => String(x).replace(/\\/g, "/") : (x) => x;
// ---- fs ---------------------------------------------------------------------------------------------------------------
const stats = (s) => ({
@@ -171,8 +207,8 @@
rmdirSync(p, o) { call("rm", pathOf(p), !!(o && o.recursive), false); },
renameSync: (a, b) => call("rename", pathOf(a), pathOf(b)),
copyFileSync: (a, b) => call("copyFile", pathOf(a), pathOf(b)),
- realpathSync: (p) => call("realpath", pathOf(p)),
- mkdtempSync: (prefix) => call("mkdtemp", String(prefix)),
+ realpathSync: (p) => fwd(call("realpath", pathOf(p))),
+ mkdtempSync: (prefix) => fwd(call("mkdtemp", String(prefix))),
constants: { F_OK: 0, R_OK: 4, W_OK: 2, X_OK: 1 },
createWriteStream(p) { fs.writeFileSync(p, ""); return { write(d) { fs.appendFileSync(p, d); return true; }, end(d) { if (d) fs.appendFileSync(p, d); }, on() { return this; } }; },
};
@@ -186,9 +222,11 @@
fs.promises = promises;
// ---- os, crypto, child_process --------------------------------------------------------------------------------------
+ // the system's own words, as Node gives them (until 0.1.8 every system here was an arm64 Mac's)
const os = {
- tmpdir: () => call("tmpdir"), homedir: () => call("homedir"), platform: () => "darwin", arch: () => "arm64", EOL: "\n",
- cpus: () => Array.from({ length: 8 }, () => ({ model: "", speed: 0 })), type: () => "Darwin", release: () => "", hostname: () => "raea", endianness: () => "LE",
+ tmpdir: () => fwd(call("tmpdir")), homedir: () => fwd(call("homedir")), platform: () => proc.platform, arch: () => proc.arch, EOL: win ? "\r\n" : "\n",
+ cpus: () => Array.from({ length: 8 }, () => ({ model: "", speed: 0 })), type: () => ({ darwin: "Darwin", win32: "Windows_NT", linux: "Linux" })[proc.platform] || proc.platform,
+ release: () => "", hostname: () => "raea", endianness: () => "LE",
};
const crypto = {
createHash(alg) {
@@ -226,18 +264,23 @@
if (r.status !== 0) { const e = new Error(`Command failed: ${cmd} ${(args || []).join(" ")}\n${r.stderr}`); e.status = r.status; e.stdout = r.stdout; e.stderr = r.stderr; throw e; }
return r.stdout;
},
- execSync(command, o) { return childProcess.execFileSync("/bin/sh", ["-c", String(command)], o); },
+ // a command line through the system's shell, as Node's: sh, or on Windows cmd
+ execSync(command, o) { return win ? childProcess.execFileSync(g.process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", String(command)], o) : childProcess.execFileSync("/bin/sh", ["-c", String(command)], o); },
};
// ---- process, url, util, events, module ---------------------------------------------------------------------------
const proc = g.process;
- let cwd = call("cwd");
+ let cwd = fwd(call("cwd"));
proc.cwd = () => cwd;
proc.chdir = (d) => { cwd = path.resolve(d); };
proc.version = "v22.0.0";
proc.versions = { node: "22.0.0", raea: "1" };
- proc.arch = "arm64";
- proc.pid = 1;
+ // the process's own (until 0.1.8 a pid of 1 and no ppid, so `raea show` never found the harness that ran it)
+ const own = call("process");
+ proc.arch = own.arch;
+ proc.pid = own.pid;
+ let parent;
+ Object.defineProperty(proc, "ppid", { get: () => (parent === undefined ? (parent = call("ppid")) : parent), configurable: true });
proc.execPath = "raea";
proc.exitCode = undefined;
proc.nextTick = (fn, ...a) => queueMicrotask(() => fn(...a));
@@ -249,9 +292,19 @@
proc.memoryUsage = () => ({ rss: 0, heapTotal: 0, heapUsed: 0, external: 0, arrayBuffers: 0 });
proc.on = proc.once = proc.off = () => proc;
proc.emitWarning = () => {};
+ // file:///C:/x on Windows is C:/x, and file://server/share/x is //server/share/x
const url = {
- fileURLToPath: (u) => decodeURIComponent(new URL(String(u)).pathname),
- pathToFileURL: (p) => new URL("file://" + encodeURI(path.resolve(String(p)))),
+ fileURLToPath(u) {
+ const x = new URL(String(u));
+ const p = decodeURIComponent(x.pathname);
+ if (!win) return p;
+ return x.hostname ? "//" + x.hostname + p : /^\/[A-Za-z]:(\/|$)/.test(p) ? p.slice(1) : p;
+ },
+ pathToFileURL(p) {
+ const r = path.resolve(String(p));
+ const share = win && r.startsWith("//");
+ return new URL("file:" + (share ? "" : win ? "///" : "//") + encodeURI(r).replace(/[?#]/g, encodeURIComponent));
+ },
URL: g.URL, URLSearchParams: g.URLSearchParams,
};
const inspect = (x) => { try { return typeof x === "string" ? x : JSON.stringify(x); } catch { return String(x); } };
@@ -304,7 +357,7 @@
req.cache = cache;
return req;
};
- builtins.module = { createRequire: (from) => requireFrom(path.dirname(pathOf(from).replace(/^file:\/\//, ""))), builtinModules: Object.keys(builtins) };
+ builtins.module = { createRequire: (from) => { const f = String(from instanceof URL ? from.href : from); return requireFrom(path.dirname(f.startsWith("file:") ? url.fileURLToPath(f) : f)); }, builtinModules: Object.keys(builtins) };
g.__raea_node_builtins = builtins;
g.__raea_node_require = requireFrom;
g.Buffer = Buffer;
diff --git a/engine/native/src/node.rs b/engine/native/src/node.rs
index 56333d3c..91e7e477 100644
--- a/engine/native/src/node.rs
+++ b/engine/native/src/node.rs
@@ -10,7 +10,7 @@ use base64::Engine as _;
use serde_json::{json, Value};
mod os;
-use os::{mode_ctime, signal};
+use os::{mode_ctime, node_arch, parent_pid, signal};
/// The builtins node.js defines, by the names an import or require gives them (with or without `node:`)
@@ -181,7 +181,8 @@ fn js_string(s: &str) -> String {
/// looked for packages from "."
pub fn load(path: &Path, entry: bool) -> Result<String, String> {
let abs = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
- let url = js_string(&format!("file://{}", abs.display()));
+ // file:///C:/... on Windows (until 0.1.8 file://C:\..., a URL with no path a fileURLToPath could read)
+ let url = js_string(&url::Url::from_file_path(&abs).map(String::from).unwrap_or_else(|_| format!("file://{}", abs.display())));
load_module(path).map(|s| s.replace("import.meta.main", if entry { "true" } else { "false" }).replace("import.meta.url", &url))
}
@@ -358,7 +359,11 @@ pub fn call(op: &str, a: &[Value]) -> Value {
json!(b64(&v))
}
"spawn" => spawn(&s(0), a.get(1), a.get(2).unwrap_or(&Value::Null)),
- "tmpdir" => json!(std::env::temp_dir().display().to_string().trim_end_matches('/')),
+ // without its last separator, as Node's (Windows' TEMP ends in \\)
+ "tmpdir" => json!(std::env::temp_dir().display().to_string().trim_end_matches(['/', '\\'])),
+ // process.arch and process.pid, in Node's words (x64, arm64)
+ "process" => json!({"arch": node_arch(), "pid": std::process::id()}),
+ "ppid" => parent_pid().map(Value::from).unwrap_or(Value::Null),
"homedir" => json!(raea_io_home::user_home().unwrap_or_default().display().to_string()),
"cwd" => json!(std::env::current_dir().map(|p| p.display().to_string()).unwrap_or_default()),
"resolve" => resolve_file(&s(0), Path::new(&s(1)), false).map(|p| json!(p.display().to_string())).unwrap_or_else(|e| err("MODULE_NOT_FOUND", e)),
diff --git a/engine/native/src/node/os.rs b/engine/native/src/node/os.rs
index 137cd6dc..91788221 100644
--- a/engine/native/src/node/os.rs
+++ b/engine/native/src/node/os.rs
@@ -38,3 +38,33 @@ fn signal_name(n: i32) -> String {
n => format!("SIG{n}"),
}
}
+
+/// process.arch: Node's word for the CPU this was built for
+pub(super) fn node_arch() -> &'static str {
+ match std::env::consts::ARCH {
+ "x86_64" => "x64",
+ "aarch64" => "arm64",
+ "x86" => "ia32",
+ other => other,
+ }
+}
+
+/// process.ppid: the process that started this one. Windows keeps it in a process's own record, read here through
+/// PowerShell (once, when asked: the agent shell asks only to find the harness that ran `raea show`).
+pub(super) fn parent_pid() -> Option<u32> {
+ #[cfg(unix)]
+ {
+ // SAFETY: getppid takes nothing and can't fail
+ Some(unsafe { libc::getppid() } as u32)
+ }
+ #[cfg(windows)]
+ {
+ let q = format!("(Get-CimInstance Win32_Process -Filter 'ProcessId={}').ParentProcessId", std::process::id());
+ let o = std::process::Command::new("powershell").args(["-NoProfile", "-NonInteractive", "-Command", &q]).stdin(std::process::Stdio::null()).output().ok()?;
+ String::from_utf8_lossy(&o.stdout).trim().parse().ok()
+ }
+ #[cfg(not(any(unix, windows)))]
+ {
+ None
+ }
+}
diff --git a/engine/native/tests/node.rs b/engine/native/tests/node.rs
index 4f535ef1..3f023ad9 100644
--- a/engine/native/tests/node.rs
+++ b/engine/native/tests/node.rs
@@ -93,3 +93,55 @@ fn a_script_that_sets_exit_code_exits_with_it() {
assert_eq!((set.exit, set.stderr.as_str()), (3, "refused\n"));
assert_eq!((plain.exit, plain.stdout.as_str()), (0, "ok"));
}
+
+/// The system as Node names it, and Windows' paths parsed as Windows does (#169: on a Windows PC raea's Node core said
+/// it was an arm64 Mac, process.platform was Rust's "windows", resolve(".") named "/C:\Users\...", no folder at all, and
+/// there was no process.ppid on any system, so `raea show` never found the harness that ran it). path.win32 parses
+/// Windows' paths on any system, as the Windows path does there, writing them with /. Each answer is Node 22's, its \
+/// written as /.
+#[test]
+fn names_the_system_as_node_does_and_parses_windows_paths() {
+ let d = std::env::temp_dir().join(format!("raea-node-system-{}", std::process::id()));
+ std::fs::create_dir_all(&d).unwrap();
+ std::fs::write(d.join("system.ts"), r#"
+import { arch, platform, type, tmpdir, homedir } from "os";
+import path from "path";
+import { fileURLToPath, pathToFileURL } from "url";
+const w = path.win32;
+process.stdout.write(JSON.stringify({
+ system: [process.platform === platform(), process.arch === arch(), process.pid > 1, process.ppid > 1 && process.ppid !== process.pid, type()],
+ here: [path.isAbsolute(process.cwd()), path.resolve(".") === process.cwd(), path.isAbsolute(tmpdir()), !/[\\/]$/.test(tmpdir()), path.isAbsolute(homedir())],
+ resolve: [w.resolve("C:\\a", "b\\..\\c"), w.resolve("C:\\a", "D:\\x", "y"), w.resolve("\\\\nas\\clips\\", "a.mp4"), w.resolve("C:/a/", "..", "..")],
+ absolute: ["C:\\x", "c:/x", "\\\\nas\\clips", "\\x", "x", "C:x"].map((p) => w.isAbsolute(p)),
+ parts: [w.dirname("C:\\a\\b.txt"), w.dirname("C:\\a"), w.dirname("C:\\"), w.basename("C:\\a\\b.txt", ".txt"), w.extname("C:\\a.b\\c.mp4"), w.basename("C:\\")],
+ join: [w.join("C:\\Users\\me", ".raea", "app-host.json"), w.normalize("C:\\a\\.\\b\\..\\c\\"), w.parse("C:\\a\\b.txt").root],
+ relative: [w.relative("C:\\a\\b", "C:\\a\\c\\d"), w.relative("C:\\A\\b", "c:\\a\\B\\x"), w.relative("C:\\a", "D:\\b")],
+ delimiter: [w.delimiter, path.posix.delimiter, path.posix.resolve("/a", "b"), path.posix.isAbsolute("C:\\x")],
+ url: [fileURLToPath(pathToFileURL(path.resolve("a b#1.txt"))) === path.resolve("a b#1.txt"), pathToFileURL("/x y").href.startsWith("file:///")],
+}));
+"#).unwrap();
+ let r = raea_native::js::run_node(&d.join("system.ts"), &[], String::new(), Duration::from_secs(20));
+ let _ = std::fs::remove_dir_all(&d);
+ let got: serde_json::Value = serde_json::from_str(&r.stdout).unwrap_or_else(|e| panic!("{e}: {} / {}", r.stdout, r.stderr));
+ let kind = match std::env::consts::OS { "macos" => "Darwin", "windows" => "Windows_NT", "linux" => "Linux", os => os };
+ let want = serde_json::json!({
+ "system": [true, true, true, true, kind],
+ "here": [true, true, true, true, true],
+ "resolve": ["C:/a/c", "D:/x/y", "//nas/clips/a.mp4", "C:/"],
+ "absolute": [true, true, true, true, false, false],
+ "parts": ["C:/a", "C:/", "C:/", "b", ".mp4", ""],
+ "join": ["C:/Users/me/.raea/app-host.json", "C:/a/c/", "C:/"],
+ "relative": ["../c/d", "x", "D:/b"],
+ "delimiter": [";", ":", "/a/b", false],
+ "url": [true, true],
+ });
+ assert_eq!(got, want);
+ // and Node's own words for this system
+ let platform = match std::env::consts::OS { "macos" => "darwin", "windows" => "win32", os => os };
+ let probe = d.with_extension("platform.ts");
+ std::fs::write(&probe, "process.stdout.write(process.platform + ' ' + process.arch);\n").unwrap();
+ let r = raea_native::js::run_node(&probe, &[], String::new(), Duration::from_secs(20));
+ let _ = std::fs::remove_file(&probe);
+ let arch = match std::env::consts::ARCH { "x86_64" => "x64", "aarch64" => "arm64", a => a };
+ assert_eq!(r.stdout, format!("{platform} {arch}"));
+}