Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Fix portable Hermes launcher on Windows
Krishna Dobhal381d328d838d
diff --git a/server/env-path.test.ts b/server/env-path.test.tsindex 6f061d3c58..a7fff07c04 100644--- a/server/env-path.test.ts+++ b/server/env-path.test.ts@@ -574,6 +574,30 @@ winOnly("resolveCli (Windows)", () => {expect(resolved.args).toEqual(["--mcp-config", payload]);});+ it("resolves portable Hermes to embedded Python without interpreting arguments", () => {+ const root = join(dir, "portable Hermes & tools");+ mkdirSync(join(root, "hermes_cli"), { recursive: true });+ writeFileSync(join(root, "hermes_cli", "main.py"), "");+ const shim = join(root, "hermes.bat");+ writeFileSync(shim, '"%PYTHON_EXE%" -m hermes_cli.main %*\r\n');+ const args = ["acp", 'a b & c | %PATH% "quoted"', "你好"];+ const resolved = resolveCli(shim, args);+ expect(resolved.command).toBe(join(root, "python_embedded", "python.exe"));+ expect(resolved.args[0]).toBe("-c");+ expect(resolved.args.slice(2)).toEqual([root, ...args]);+ expect(resolveCli(`"${shim}"`, args)).toEqual(resolved);+ });++ it("does not treat unrelated batch files or incomplete layouts as portable Hermes", () => {+ const shim = join(dir, "hermes.bat");+ writeFileSync(shim, '"%PYTHON_EXE%" -m hermes_cli.main %*\r\n');+ expect(resolveCli(shim, ["acp"])).toEqual({ command: shim, args: ["acp"] });+ mkdirSync(join(dir, "hermes_cli"));+ writeFileSync(join(dir, "hermes_cli", "main.py"), "");+ writeFileSync(shim, "custom-launcher %*\r\n");+ expect(resolveCli(shim, ["acp"])).toEqual({ command: shim, args: ["acp"] });+ });+it("hands an unknown CLI back untouched so spawn reports its own ENOENT", () => {onPath();expect(resolveCli("definitely-not-installed", ["-p"])).toEqual({diff --git a/server/env-path.ts b/server/env-path.tsindex c89d980354..953d502cb7 100644--- a/server/env-path.ts+++ b/server/env-path.ts@@ -4,6 +4,7 @@ import { execFile } from "node:child_process";import { closeSync, existsSync, openSync, readFileSync, readSync, statSync, readdirSync } from "node:fs";import { homedir } from "node:os";import { basename, delimiter, dirname, extname, join } from "node:path";+import { resolvePortableHermes } from "./portable-hermes.ts";function nvmBinDirs(): string[] {try {@@ -325,6 +326,8 @@ function parseCmdShim(shim: string, env?: NodeJS.ProcessEnv): ResolvedSpawn | nureturn null;}const dir = dirname(shim);+ const portableHermes = resolvePortableHermes(shim, text);+ if (portableHermes) return portableHermes;// npm's own npm.cmd/npx.cmd name their entry as SET "NPX_CLI_JS=%~dp0\…"; a launcher switch to a global npm is not followed.const npmEntry = /^SET "NP[MX]_CLI_JS=%~dp0\\([^"]+)"/im.exec(text);const targets = [...(npmEntry ? [npmEntry] : []), ...text.matchAll(/"%~?dp0%?\\?([^"]+)"/g)]diff --git a/server/portable-hermes.e2e.test.ts b/server/portable-hermes.e2e.test.tsnew file mode 100644index 0000000000..9ef0e8bd0c--- /dev/null+++ b/server/portable-hermes.e2e.test.ts@@ -0,0 +1,101 @@+import { execFileSync } from "node:child_process";+import { existsSync, mkdirSync, readFileSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { expect, it } from "vitest";+import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";+import { resolveCli } from "./procs.ts";++function installedPython(): string | null {+ if (process.platform !== "win32") return null;+ try {+ return execFileSync("python.exe", ["-c", "import sys; print(sys.executable)"], { encoding: "utf8", timeout: 5000 }).trim();+ } catch {+ return null;+ }+}++const python = installedPython();++it.skipIf(!python)("saves a portable Hermes CLI and probes version and ACP models in an isolated server", async () => {+ const fixture = await launchVerificationServer({});+ const { dataDir, url, logPath } = fixture.info;+ const root = join(dataDir, "portable Hermes & 测试");+ const home = join(dataDir, ".hermes");+ const shim = join(root, "hermes.bat");+ const api = async (method: string, path: string, body?: unknown) => {+ const response = await fetch(url + path, {+ method, headers: { "content-type": "application/json", origin: url },+ body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(30_000),+ });+ const result = await response.json() as any;+ expect(response.ok, JSON.stringify(result)).toBe(true);+ return result;+ };+ try {+ mkdirSync(join(root, "hermes_cli"), { recursive: true });+ mkdirSync(home, { recursive: true });+ symlinkSync(dirname(python!), join(root, "python_embedded"), "junction");+ writeFileSync(shim, '@echo off\r\n"%PYTHON_EXE%" -m hermes_cli.main %*\r\n');+ writeFileSync(join(root, "hermes_cli", "__init__.py"), "");+ writeFileSync(join(root, "cli-config.yaml.example"), "model:\n default: fixture/model\n provider: openrouter\n");+ writeFileSync(join(root, ".env.example"), "OPENROUTER_API_KEY=fixture-only\n");+ writeFileSync(join(root, "hermes_cli", "main.py"), `import json, os, sys+from pathlib import Path+home = Path(os.environ["HERMES_HOME"])+with (home / "launches.jsonl").open("a", encoding="utf-8") as log:+ log.write(json.dumps({"args": sys.argv[1:], "root": os.environ["HERMES_ROOT"], "cwd": os.getcwd(), "home": str(home), "python": os.environ["HERMES_PYTHON"], "pip": os.environ["PIP_TARGET"], "terminal": os.environ["TERMINAL_CWD"], "foreign_key": os.environ.get("OPENAI_API_KEY")}) + "\\n")+if "--version" in sys.argv:+ print("Hermes 1.4.17")+ sys.exit(0)+if sys.argv[1:2] != ["acp"]:+ print(json.dumps(sys.argv[1:], ensure_ascii=False))+ sys.exit(0)+for line in sys.stdin:+ msg = json.loads(line)+ method = msg.get("method")+ if method == "initialize":+ result = {"protocolVersion": 1, "agentCapabilities": {}}+ elif method == "session/new":+ result = {"sessionId": "fixture-session", "models": {"currentModelId": "fixture/model", "availableModels": [{"modelId": "fixture/model", "name": "Fixture model"}]}}+ else:+ result = {"echo": msg.get("params")}+ if "id" in msg:+ print(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": result}), flush=True)+`);+ const payload = ["payload", 'spaces & pipes | %PATH% "quotes"', "你好"];+ const resolved = resolveCli(shim, payload);+ const env = { ...process.env, HERMES_HOME: home, OPENAI_API_KEY: "must-be-cleared", TERMINAL_CWD: dataDir };+ const output = execFileSync(resolved.command, resolved.args, { env, encoding: "utf8" });+ expect(JSON.parse(output)).toEqual(payload);+ const protocol = resolveCli(shim, ["acp"]);+ const echoed = execFileSync(protocol.command, protocol.args, {+ env, encoding: "utf8", input: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "echo", params: payload }) + "\n",+ });+ expect(JSON.parse(echoed).result.echo).toEqual(payload);+ expect(readFileSync(join(home, "config.yaml"), "utf8")).toContain("fixture/model");+ writeFileSync(join(home, ".env"), "OPENROUTER_API_KEY=preserve-fixture-key\n");+ await api("PATCH", "/api/instances/hermes", { cli: shim });+ const catalog = await api("GET", "/api/instances");+ const hermes = catalog.instances.find((instance: any) => instance.instanceId === "hermes");+ expect(hermes.cli).toBe(shim);+ expect(hermes.snapshot).toMatchObject({ state: "available", version: "Hermes 1.4.17" });+ const models = await runControlOmb(["models", "--url", url]);+ expect(JSON.stringify(models)).toContain("fixture/model");+ const launches = readFileSync(join(home, "launches.jsonl"), "utf8").trim().split("\n").map((line) => JSON.parse(line));+ expect(launches.some((launch) => launch.args[0] === "--version")).toBe(true);+ expect(launches.some((launch) => launch.args[0] === "acp")).toBe(true);+ expect(launches[0]).toMatchObject({ root, cwd: root, home, terminal: dataDir, foreign_key: null });+ expect(launches[0].pip).toBe(join(root, "python_embedded", "Lib", "site-packages"));+ expect(readFileSync(join(home, ".env"), "utf8")).toBe("OPENROUTER_API_KEY=preserve-fixture-key\n");+ const evidencePath = `${logPath}.portable-hermes.json`;+ writeFileSync(evidencePath, JSON.stringify({ url, logPath, commands: [+ { method: "PATCH", path: "/api/instances/hermes", body: { cli: shim } },+ { method: "GET", path: "/api/instances" },+ { command: ["models", "--url", url] },+ ], hermes: hermes.snapshot, models, launches }, null, 2));+ console.log(JSON.stringify({ logPath, evidencePath }));+ } finally {+ if (existsSync(join(root, "python_embedded"))) unlinkSync(join(root, "python_embedded"));+ await fixture.close();+ }+}, 120_000);diff --git a/server/portable-hermes.ts b/server/portable-hermes.tsnew file mode 100644index 0000000000..e1ae949412--- /dev/null+++ b/server/portable-hermes.ts@@ -0,0 +1,47 @@+import { existsSync } from "node:fs";+import { basename, dirname, join } from "node:path";+import type { ResolvedSpawn } from "./env-path.ts";++// Portable Hermes v1.4.17's hermes.bat initializes embedded Python before running+// hermes_cli.main. Windows cannot spawn the batch file directly; ACP also needs+// stdout reserved for protocol messages, without the launcher's banner.+const BOOTSTRAP = `import os, runpy, shutil, sys+root = sys.argv.pop(1)+python_dir = os.path.join(root, "python_embedded")+packages = os.path.join(python_dir, "Lib", "site-packages")+env = os.environ+home = env.get("HERMES_HOME") or os.path.join(env.get("USERPROFILE", os.path.expanduser("~")), ".hermes")+env["HERMES_HOME"] = home+os.makedirs(home, exist_ok=True)+for target, sources in [(".env", [".env", ".env.example"]), ("config.yaml", ["cli-config.yaml", "cli-config.yaml.example"]), ("SOUL.md", ["assets/SOUL.md"])]:+ destination = os.path.join(home, target)+ if not os.path.exists(destination):+ for source in sources:+ source = os.path.join(root, source)+ if os.path.isfile(source):+ shutil.copyfile(source, destination)+ break+for key in ["OPENAI_API_KEY", "OPENAI_BASE_URL", "ANTHROPIC_API_KEY", "ANTHROPIC_TOKEN"]:+ env.pop(key, None)+env["PATH"] = os.pathsep.join([python_dir, os.path.join(python_dir, "Scripts"), os.path.join(root, "node_modules", ".bin"), env.get("PATH", "")])+env["PIP_TARGET"] = packages+env["PYTHONPATH"] = packages+env["HERMES_PYTHON"] = sys.executable+env["HERMES_ROOT"] = root+env.setdefault("TERMINAL_CWD", root)+env["PYTHONIOENCODING"] = "utf-8"+sys.stdin.reconfigure(encoding="utf-8")+sys.stdout.reconfigure(encoding="utf-8")+sys.stderr.reconfigure(encoding="utf-8")+sys.path[:0] = [root, packages]+os.chdir(root)+runpy.run_module("hermes_cli.main", run_name="__main__")+`;++export function resolvePortableHermes(shim: string, text: string): ResolvedSpawn | null {+ if (basename(shim).toLowerCase() !== "hermes.bat") return null;+ const root = dirname(shim);+ if (!/^"%PYTHON_EXE%" -m hermes_cli\.main %\*\s*$/im.test(text)+ || !existsSync(join(root, "hermes_cli", "main.py"))) return null;+ return { command: join(root, "python_embedded", "python.exe"), args: ["-c", BOOTSTRAP, root] };+}