From a6505220e106f809d52e4769dc4f69fa8f3e35cc Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 08:47:05 -0500 Subject: [PATCH 1/8] fix(agents): start npm shims on Windows without the command interpreter A .cmd or .bat that only starts a program is replaced by that program, run directly. Other scripts still go through cmd /c, and words the command interpreter would read as part of the command are refused. The shared finder is 1.0.2 with its hash recorded. --- backend/HASHOUT_LOG.md | 8 +++ backend/app/services/agent_lookup.py | 56 ++++++++++++++- backend/app/services/agent_programs.py | 3 +- backend/app/services/claude_code.py | 7 +- .../tests/rb02/test_services_agent_lookup.py | 72 +++++++++++++++++++ .../tests/rb05/test_routers_terminal_dock.py | 2 +- setup/agents.py | 2 +- 7 files changed, 141 insertions(+), 9 deletions(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index fdf1e1d..81c2d0a 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2,6 +2,14 @@ Living context for the FastAPI engine service. What would be comments in `backend/` lives here, newest first. Read before editing. +## 2026-11-29 · unreleased (services/agent_lookup.py 1.0.2, services/claude_code.py, services/agent_programs.py, setup/agents.py) + +- Windows start of a `.cmd` or `.bat` program: `start_argv` reads the script (64 KiB at most) and, when its last `%*` line names a file under `%dp0%` or `%~dp0`, runs that file directly: an `.exe` as itself, a `.js`, `.cjs` or `.mjs` with the `node.exe` beside the script or the first `node` on the child PATH. This is the npm shim case and needs no command interpreter, so prompt words reach the program unchanged. +- Any other script still goes through `COMSPEC /c`, and `_cmd_words` raises `Unsafe` (an `OSError`, so `check` reports broken and the open routes answer 500 with the text) for a word with a control character, `%` or `"`; for `&|<>^()!` in a word `list2cmdline` leaves unquoted; and for a script path that gets quoted while another word is quoted too or while the path holds one of those characters, because `cmd /c` then drops the first and last quote of the line. +- `claude_code.tab_argv` and `agent_programs.open_tab` hand the child environment to `start_argv`, so the node lookup sees the same PATH the tab runs with. +- The finder is 1.0.2 with its hash in `setup/agents.py`; other Form engines carrying 1.0.1 need the same file and hash. +- Removed code: none. + ## 2026-11-28 · v0.14.3 (routers/gof.py, services/engine.py) - `routers/gof.py` sends `overwrite: True` to `export.run`: a second send to the same sister app writes over the file the first send left in the send folder, which the engine now refuses without the argument. diff --git a/backend/app/services/agent_lookup.py b/backend/app/services/agent_lookup.py index ea34eba..8335219 100644 --- a/backend/app/services/agent_lookup.py +++ b/backend/app/services/agent_lookup.py @@ -26,7 +26,7 @@ from dataclasses import dataclass, field from pathlib import Path -VERSION = "1.0.1" +VERSION = "1.0.2" PROGRAMS: dict = { "claude": {"title": "Claude Code", "names": ("claude",), "setting": "claudeBin", "install": "curl -fsSL https://claude.ai/install.sh | bash", "install_windows": "irm https://claude.ai/install.ps1 | iex", @@ -45,6 +45,9 @@ MARK = "__FORM_AGENT_LOOKUP__" HOW = {"setting": "your setting", "override": "the development override", "path": "the engine's PATH", "folder": "a known install folder", "shell": "your shell's PATH"} RETRY_SECONDS = 60.0 +CMD_SPECIAL = frozenset("&|<>^()!") +SHIM_WORD = re.compile(r'"%(?:~dp0|dp0%)\\?([^"%]+)"') +SHIM_LIMIT = 65536 _lock = threading.RLock() _shell: dict = {} @@ -359,13 +362,60 @@ def _quote(word: str, fish: bool) -> str: return "'" + word.replace("'", "'\"'\"'") + "'" +class Unsafe(OSError): + """A word that the Windows command interpreter would read as part of a command instead of passing it on.""" + + +def _shim_target(words: list[str], env: dict) -> list[str] | None: + shim = Path(words[0]) + try: + if shim.stat().st_size > SHIM_LIMIT: + return None + text = shim.read_text(encoding="utf-8", errors="replace") + except OSError: + return None + line = next((one for one in reversed(text.splitlines()) if "%*" in one), "") + named = SHIM_WORD.findall(line) + if not named: + return None + target = Path(os.path.normpath(shim.parent.joinpath(*[p for p in re.split(r"[\\/]", named[-1]) if p]))) + if not target.is_file(): + return None + if target.suffix.lower() == ".exe": + return [str(target), *words[1:]] + if target.suffix.lower() not in (".js", ".cjs", ".mjs"): + return None + beside = shim.parent / "node.exe" + node = str(beside) if beside.is_file() else shutil.which("node", path=env.get("PATH", "")) + return [node, str(target), *words[1:]] if node else None + + +def _cmd_words(words: list[str]) -> list[str]: + name = Path(words[0]).name + quoted = [not w or " " in w or "\t" in w for w in words] + for word, inside in zip(words, quoted): + if re.search(r"[\x00-\x1f\x7f]", word): + raise Unsafe(f"{name} is a command script and a word for it holds a control character, such as a line break") + if "%" in word or '"' in word: + raise Unsafe(f"{name} is a command script and a word for it holds % or a double quote, which the command interpreter would change") + if not inside and CMD_SPECIAL & set(word): + raise Unsafe(f"{name} is a command script and a word for it holds one of {''.join(sorted(CMD_SPECIAL))} outside quotes") + if quoted[0] and (any(quoted[1:]) or CMD_SPECIAL & set(words[0])): + raise Unsafe(f"{name} is a command script in a folder whose path the command interpreter cannot keep quoted together with these words") + return words + + def start_argv(cmd: list, env: dict | None = None, platform: str | None = None) -> list[str]: """How a program is started, the same for a tab, Chat and a check: through the person's login shell on macOS and Linux - (exec, so the process is the program), directly on Windows with the command interpreter in front of a .cmd or .bat.""" + (exec, so the process is the program), directly on Windows. A .cmd or .bat that only starts a program (an npm shim) is + replaced by that program; any other goes through the command interpreter, and words it would read as commands are + refused with Unsafe.""" words = [str(c) for c in cmd] env = os.environ if env is None else env if windows(platform): - return [env.get("COMSPEC") or "cmd.exe", "/c", *words] if words[0].lower().endswith((".cmd", ".bat")) else words + if not words[0].lower().endswith((".cmd", ".bat")): + return words + return _shim_target(words, env) or [env.get("COMSPEC") or "cmd.exe", "/c", *_cmd_words(words)] shell = login_shell(env, platform) fish = Path(shell).name == "fish" return [shell, "-l", "-c", "exec " + " ".join(_quote(w, fish) for w in words)] diff --git a/backend/app/services/agent_programs.py b/backend/app/services/agent_programs.py index 49f7c9f..319407f 100644 --- a/backend/app/services/agent_programs.py +++ b/backend/app/services/agent_programs.py @@ -142,7 +142,8 @@ def open_tab(kind: str, cols: int = 100, rows: int = 30) -> dict: if own: write_tab_entry(own, mark) wrote = True if own else write_config(kind, folder) - session = terminal.open_session(str(folder), cols, rows, program["title"], agent_lookup.start_argv([found.path]), claude_code.child_env(found.path), kind) + env = claude_code.child_env(found.path) + session = terminal.open_session(str(folder), cols, rows, program["title"], agent_lookup.start_argv([found.path], env), env, kind) except BaseException: if own: remove_tab_entry(own, mark) diff --git a/backend/app/services/claude_code.py b/backend/app/services/claude_code.py index 8e3cfce..bc7ec32 100644 --- a/backend/app/services/claude_code.py +++ b/backend/app/services/claude_code.py @@ -110,13 +110,13 @@ def workdir() -> Path: return folder -def tab_argv(path: str, mcp_file: str, prompt: str | None, resume: str | None = None) -> list[str]: +def tab_argv(path: str, mcp_file: str, prompt: str | None, resume: str | None = None, env: dict | None = None) -> list[str]: cmd = [path, "--mcp-config", mcp_file, "--allowedTools", f"mcp__{TAB_ENTRY}", "--append-system-prompt", NOTE] if resume: cmd += ["--resume", resume] if prompt: cmd.append(prompt) - return agent_lookup.start_argv(cmd) + return agent_lookup.start_argv(cmd, env) def status() -> dict: @@ -140,7 +140,8 @@ def open_tab(prompt: str | None = None, cols: int = 100, rows: int = 30, fresh: raise LookupError(said(found)) mcp_file = issue() try: - session = terminal.open_session(str(workdir()), cols, rows, "Claude Code",tab_argv(found.path, mcp_file, prompt, resume), child_env(found.path), "claude") + env = child_env(found.path) + session = terminal.open_session(str(workdir()), cols, rows, "Claude Code", tab_argv(found.path, mcp_file, prompt, resume, env), env, "claude") except BaseException: revoke(mcp_file) raise diff --git a/backend/tests/rb02/test_services_agent_lookup.py b/backend/tests/rb02/test_services_agent_lookup.py index 1267e49..4e2c973 100644 --- a/backend/tests/rb02/test_services_agent_lookup.py +++ b/backend/tests/rb02/test_services_agent_lookup.py @@ -110,6 +110,78 @@ def test_start_argv_on_windows_wraps_only_cmd_and_bat_files(): assert al.start_argv(["C:/x/claude.exe", "-v"], {}, "win32") == ["C:/x/claude.exe", "-v"] +NPM_SHIM = ('@ECHO off\r\nGOTO start\r\n:find_dp0\r\nSET dp0=%~dp0\r\nEXIT /b\r\n:start\r\nSETLOCAL\r\nCALL :find_dp0\r\n\r\n' + 'IF EXIST "%dp0%\\node.exe" (\r\n SET "_prog=%dp0%\\node.exe"\r\n) ELSE (\r\n SET "_prog=node"\r\n SET PATHEXT=%PATHEXT:;.JS;=;%\r\n)\r\n\r\n' + 'endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\node_modules\\@anthropic-ai\\claude-code\\cli.js" %*\r\n') + + +def npm_install(folder: Path, node_beside: bool = True) -> tuple[Path, Path]: + script = folder / "node_modules" / "@anthropic-ai" / "claude-code" / "cli.js" + script.parent.mkdir(parents=True) + script.write_text("") + if node_beside: + (folder / "node.exe").write_text("") + shim = folder / "claude.cmd" + shim.write_text(NPM_SHIM) + return shim, script + + +def test_start_argv_on_windows_runs_an_npm_shim_through_node_without_the_command_interpreter(tmp_path): + shim, script = npm_install(tmp_path) + name = 'x & calc & y' + argv = al.start_argv([str(shim), "-p", f'rig it (FormRig window: character "{name}")'], {"COMSPEC": "C:/cmd.exe", "PATH": ""}, "win32") + assert argv == [str(tmp_path / "node.exe"), str(script), "-p", f'rig it (FormRig window: character "{name}")'] + + +def test_start_argv_on_windows_finds_node_on_path_for_an_npm_shim(tmp_path): + shim, script = npm_install(tmp_path / "npm", node_beside=False) + node = program(tmp_path / "nodejs", "node") + argv = al.start_argv([str(shim), "--version"], {"PATH": str(node.parent)}, "win32") + assert argv[1:] == [str(script), "--version"] + assert Path(argv[0]).parent == node.parent + + +def test_start_argv_on_windows_runs_the_program_a_shim_names_directly(tmp_path): + exe = tmp_path / "bin" / "agent.exe" + exe.parent.mkdir() + exe.write_text("") + shim = tmp_path / "agent.cmd" + shim.write_text('@ECHO off\r\n"%~dp0\\bin\\agent.exe" %*\r\n') + assert al.start_argv([str(shim), "a & b"], {}, "win32") == [str(exe), "a & b"] + + +@pytest.mark.parametrize("word", ["a&b", "x|y", "out>f", "in Date: Sun, 29 Nov 2026 08:48:42 -0500 Subject: [PATCH 2/8] fix(agent): keep unsaved work when a linked caller opens a project load_rig of a .frig without the window token is refused with 409 while the open project has unsaved changes, since opening a project clears the undo history. Imports stay undoable and are unchanged. --- .docs/wiki/GoF.md | 2 +- backend/HASHOUT_LOG.md | 1 + backend/app/routers/agent.py | 15 ++++- backend/tests/rb02/test_routers_agent.py | 72 ++++++++++++++++++++++++ 4 files changed, 86 insertions(+), 4 deletions(-) create mode 100644 backend/tests/rb02/test_routers_agent.py diff --git a/.docs/wiki/GoF.md b/.docs/wiki/GoF.md index 0e94e1e..5bb4f64 100644 --- a/.docs/wiki/GoF.md +++ b/.docs/wiki/GoF.md @@ -67,7 +67,7 @@ An agent can do the same with `POST /api/agent {"command":"apply_return","path": ## Agent link -Another app can push a file into an open FormRig with `POST /api/agent {"command":"load_rig","path":...}`. It is accepted when the request carries the window token, or when Agent link is on (a switch stored in `/agent_link.json`). Only `load_rig` exists; a `.frig` opens as a project and anything else imports. +Another app can push a file into an open FormRig with `POST /api/agent {"command":"load_rig","path":...}`. It is accepted when the request carries the window token, or when Agent link is on (a switch stored in `/agent_link.json`). Only `load_rig` exists; a `.frig` opens as a project and anything else imports. Without the window token, a `.frig` is refused with 409 while the open project has unsaved changes, because opening a project clears the undo history; an import is kept in undo and is not refused. ## Limits diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 81c2d0a..494e7b7 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -8,6 +8,7 @@ Living context for the FastAPI engine service. What would be comments in `backen - Any other script still goes through `COMSPEC /c`, and `_cmd_words` raises `Unsafe` (an `OSError`, so `check` reports broken and the open routes answer 500 with the text) for a word with a control character, `%` or `"`; for `&|<>^()!` in a word `list2cmdline` leaves unquoted; and for a script path that gets quoted while another word is quoted too or while the path holds one of those characters, because `cmd /c` then drops the first and last quote of the line. - `claude_code.tab_argv` and `agent_programs.open_tab` hand the child environment to `start_argv`, so the node lookup sees the same PATH the tab runs with. - The finder is 1.0.2 with its hash in `setup/agents.py`; other Form engines carrying 1.0.1 need the same file and hash. +- `routers/agent.py`: a `load_rig` of a `.frig` without the window token asks `doc.summary` first and answers 409 `UNSAVED` while `dirty` is true (or the summary fails), since `file.open` runs `Session::reset` and clears history. The window keeps its own `mayReplace()` prompt and is not checked here. `file.import` goes through `Session::replace`, which records an undo step, so it is left as it was. - Removed code: none. ## 2026-11-28 · v0.14.3 (routers/gof.py, services/engine.py) diff --git a/backend/app/routers/agent.py b/backend/app/routers/agent.py index 8835945..58fc101 100644 --- a/backend/app/routers/agent.py +++ b/backend/app/routers/agent.py @@ -13,6 +13,7 @@ RIGS = {".glb", ".gltf", ".fbx", ".vrm", ".frig"} REFUSAL = "turn on Agent link in FormRig, or send the window token, to push a file to an open FormRig" +UNSAVED = "FormRig has unsaved changes; save or close the open project in the window before opening another .frig" def _link_path() -> Path: @@ -44,7 +45,12 @@ def link_set(body: Link) -> dict: return {"link": body.on} -def _load_rig(args: dict) -> dict: +def _unsaved() -> bool: + reply = engine.dispatch("doc.summary", {}, notify=False) + return not reply.get("ok") or bool((reply.get("result") or {}).get("dirty")) + + +def _load_rig(args: dict, window: bool = False) -> dict: raw = args.get("path") if not isinstance(raw, str) or not raw: raise HTTPException(status_code=400, detail="load_rig needs a path") @@ -58,6 +64,8 @@ def _load_rig(args: dict) -> dict: if not engine.available(): raise HTTPException(status_code=503, detail=engine.UNAVAILABLE) command = "file.open" if path.suffix.lower() == ".frig" else "file.import" + if command == "file.open" and not window and _unsaved(): + raise HTTPException(status_code=409, detail=UNSAVED) reply = engine.dispatch(command, {"path": str(path)}) if not reply.get("ok"): error = reply.get("error") or {} @@ -76,7 +84,8 @@ def _apply_return(args: dict) -> dict: @router.post("/agent") async def agent(request: Request) -> dict: - if not (from_window(request.headers) or link_on()): + window = from_window(request.headers) + if not (window or link_on()): raise HTTPException(status_code=403, detail=REFUSAL) try: body = await request.json() @@ -90,4 +99,4 @@ async def agent(request: Request) -> dict: return {"command": command, "result": await run_in_threadpool(_apply_return, args)} if command != "load_rig": raise HTTPException(status_code=400, detail="the command must be load_rig or apply_return") - return {"command": command, "result": await run_in_threadpool(_load_rig, args)} + return {"command": command, "result": await run_in_threadpool(_load_rig, args, window)} diff --git a/backend/tests/rb02/test_routers_agent.py b/backend/tests/rb02/test_routers_agent.py new file mode 100644 index 0000000..f2aeecb --- /dev/null +++ b/backend/tests/rb02/test_routers_agent.py @@ -0,0 +1,72 @@ +import json + +import pytest + +from app.routers import agent +from app.services import engine + + +@pytest.fixture +def fake_engine(monkeypatch): + state = {"dirty": False, "calls": []} + + def dispatch(name, args, notify=True): + state["calls"].append(name) + if name == "doc.summary": + return {"ok": True, "result": {"dirty": state["dirty"]}} + return {"ok": True, "result": {"name": "other"}} + + monkeypatch.setattr(engine, "available", lambda: True) + monkeypatch.setattr(engine, "dispatch", dispatch) + return state + + +@pytest.fixture +def rig(tmp_path): + path = tmp_path / "other.frig" + path.write_bytes(b"x") + return path + + +def link(data_dir, on=True): + (data_dir / "agent_link.json").write_text(json.dumps({"link": on})) + + +def test_linked_caller_cannot_open_a_project_over_unsaved_work(anon_client, data_dir, fake_engine, rig): + link(data_dir) + fake_engine["dirty"] = True + reply = anon_client.post("/api/agent", json={"command": "load_rig", "path": str(rig)}) + assert reply.status_code == 409 + assert reply.json()["detail"] == agent.UNSAVED + assert "file.open" not in fake_engine["calls"] + + +def test_linked_caller_opens_a_project_when_nothing_is_unsaved(anon_client, data_dir, fake_engine, rig): + link(data_dir) + reply = anon_client.post("/api/agent", json={"command": "load_rig", "path": str(rig)}) + assert reply.status_code == 200 + assert fake_engine["calls"][-1] == "file.open" + + +def test_linked_caller_still_imports_a_model_over_unsaved_work(anon_client, data_dir, fake_engine, tmp_path): + link(data_dir) + fake_engine["dirty"] = True + model = tmp_path / "hero.glb" + model.write_bytes(b"x") + reply = anon_client.post("/api/agent", json={"command": "load_rig", "path": str(model)}) + assert reply.status_code == 200 + assert fake_engine["calls"][-1] == "file.import" + + +def test_the_window_opens_a_project_after_its_own_prompt(client, fake_engine, rig): + fake_engine["dirty"] = True + reply = client.post("/api/agent", json={"command": "load_rig", "path": str(rig)}) + assert reply.status_code == 200 + assert fake_engine["calls"] == ["file.open"] + + +def test_without_link_or_window_key_the_route_refuses(anon_client, data_dir, fake_engine, rig): + link(data_dir, on=False) + reply = anon_client.post("/api/agent", json={"command": "load_rig", "path": str(rig)}) + assert reply.status_code == 403 + assert fake_engine["calls"] == [] From 6996f5412bd41698e40476f91478d1ed0dcdece7 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 08:50:27 -0500 Subject: [PATCH 3/8] fix(mcp): list the bundled clips in a packaged engine The MCP clip resource and the window's clip route share one lookup, which finds the clips bundled into a frozen engine and skips entries that are missing or outside the clips folder. --- backend/HASHOUT_LOG.md | 3 +- backend/app/mcp_stdio.py | 11 +---- backend/app/routers/library.py | 37 +---------------- backend/app/services/clip_library.py | 40 ++++++++++++++++++ backend/tests/rb02/test_mcp_stdio_clips.py | 48 ++++++++++++++++++++++ 5 files changed, 94 insertions(+), 45 deletions(-) create mode 100644 backend/app/services/clip_library.py create mode 100644 backend/tests/rb02/test_mcp_stdio_clips.py diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 494e7b7..295205d 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -9,7 +9,8 @@ Living context for the FastAPI engine service. What would be comments in `backen - `claude_code.tab_argv` and `agent_programs.open_tab` hand the child environment to `start_argv`, so the node lookup sees the same PATH the tab runs with. - The finder is 1.0.2 with its hash in `setup/agents.py`; other Form engines carrying 1.0.1 need the same file and hash. - `routers/agent.py`: a `load_rig` of a `.frig` without the window token asks `doc.summary` first and answers 409 `UNSAVED` while `dirty` is true (or the summary fails), since `file.open` runs `Session::reset` and clears history. The window keeps its own `mayReplace()` prompt and is not checked here. `file.import` goes through `Session::replace`, which records an undo step, so it is left as it was. -- Removed code: none. +- `services/clip_library.py` holds the clip folder lookup (`FORMRIG_CLIPS`, then `_MEIPASS/clips` in a frozen engine, then `assets/clips`) and the checked listing that `/api/library/clips` used. The MCP resource `formrig://library/clips` now returns that same listing (`name`, `path`, `licence`, `credit`, `skeleton` for a paired `.amc`), so the installed app's MCP server finds the bundled clips. The resource no longer carries the raw `file` field. +- Removed code: `routers/library.py` `_clips_dir` and its loop, moved whole into `services/clip_library.py`; the MCP resource's own read of `config.REPO/assets/clips/index.json`. ## 2026-11-28 · v0.14.3 (routers/gof.py, services/engine.py) diff --git a/backend/app/mcp_stdio.py b/backend/app/mcp_stdio.py index 428e29f..4b12d69 100644 --- a/backend/app/mcp_stdio.py +++ b/backend/app/mcp_stdio.py @@ -11,7 +11,7 @@ from app import __version__ from app.core import config -from app.services import engine +from app.services import clip_library, engine PROTOCOLS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05") TEXT_LIMIT = 60000 @@ -262,14 +262,7 @@ def read_resource(req_id, uri) -> dict: return failure(req_id, -32603, reply.get("error", {}).get("message", "doc_summary failed")) body, mime = json.dumps(slim(reply["result"]), separators=(",", ":")), "application/json" elif uri == "formrig://library/clips": - folder = config.REPO / "assets" / "clips" - try: - entries = json.loads((folder / "index.json").read_text(encoding="utf-8")) - except (OSError, ValueError): - entries = [] - for entry in entries: - entry["path"] = str(folder / entry.get("file", "")) - body, mime = json.dumps(entries, separators=(",", ":")), "application/json" + body, mime = json.dumps(clip_library.listing(), separators=(",", ":")), "application/json" elif uri == "formrig://guide/rigging": body, mime = GUIDE, "text/markdown" else: diff --git a/backend/app/routers/library.py b/backend/app/routers/library.py index 3912c22..c2cefc8 100644 --- a/backend/app/routers/library.py +++ b/backend/app/routers/library.py @@ -1,44 +1,11 @@ -import json -import os -import sys -from pathlib import Path - from fastapi import APIRouter, Depends -from app.core import config from app.core.window_guard import require_window_read +from app.services import clip_library router = APIRouter() -def _clips_dir() -> Path | None: - configured = os.environ.get("FORMRIG_CLIPS") - candidates = [Path(configured)] if configured else [] - bundle = getattr(sys, "_MEIPASS", None) - if bundle: - candidates.append(Path(bundle) / "clips") - candidates.append(config.REPO / "assets" / "clips") - return next((c for c in candidates if (c / "index.json").is_file()), None) - - @router.get("/clips", dependencies=[Depends(require_window_read)]) def clips() -> dict: - folder = _clips_dir() - if folder is None: - return {"clips": []} - try: - entries = json.loads((folder / "index.json").read_text(encoding="utf-8")) - except (OSError, ValueError): - return {"clips": []} - out = [] - for entry in entries if isinstance(entries, list) else []: - file = folder / str(entry.get("file", "")) - skeleton = folder / str(entry["skeleton"]) if entry.get("skeleton") else None - root = folder.resolve() - paired = file.suffix == ".amc" and skeleton is not None and skeleton.suffix == ".asf" and skeleton.is_file() and skeleton.resolve().is_relative_to(root) - if file.resolve().is_relative_to(root) and file.is_file() and (file.suffix == ".bvh" or paired): - item = {"name": entry.get("name", file.stem), "path": str(file.resolve()), "licence": entry.get("licence", ""), "credit": entry.get("credit", "")} - if paired: - item["skeleton"] = str(skeleton.resolve()) - out.append(item) - return {"clips": out} + return {"clips": clip_library.listing()} diff --git a/backend/app/services/clip_library.py b/backend/app/services/clip_library.py new file mode 100644 index 0000000..79ca383 --- /dev/null +++ b/backend/app/services/clip_library.py @@ -0,0 +1,40 @@ +import json +import os +import sys +from pathlib import Path + +from app.core import config + + +def folder() -> Path | None: + configured = os.environ.get("FORMRIG_CLIPS") + candidates = [Path(configured)] if configured else [] + bundle = getattr(sys, "_MEIPASS", None) + if bundle: + candidates.append(Path(bundle) / "clips") + candidates.append(config.REPO / "assets" / "clips") + return next((c for c in candidates if (c / "index.json").is_file()), None) + + +def listing() -> list[dict]: + base = folder() + if base is None: + return [] + try: + entries = json.loads((base / "index.json").read_text(encoding="utf-8")) + except (OSError, ValueError): + return [] + root = base.resolve() + out = [] + for entry in entries if isinstance(entries, list) else []: + if not isinstance(entry, dict): + continue + file = base / str(entry.get("file", "")) + skeleton = base / str(entry["skeleton"]) if entry.get("skeleton") else None + paired = file.suffix == ".amc" and skeleton is not None and skeleton.suffix == ".asf" and skeleton.is_file() and skeleton.resolve().is_relative_to(root) + if file.resolve().is_relative_to(root) and file.is_file() and (file.suffix == ".bvh" or paired): + item = {"name": entry.get("name", file.stem), "path": str(file.resolve()), "licence": entry.get("licence", ""), "credit": entry.get("credit", "")} + if paired: + item["skeleton"] = str(skeleton.resolve()) + out.append(item) + return out diff --git a/backend/tests/rb02/test_mcp_stdio_clips.py b/backend/tests/rb02/test_mcp_stdio_clips.py new file mode 100644 index 0000000..0a0ccac --- /dev/null +++ b/backend/tests/rb02/test_mcp_stdio_clips.py @@ -0,0 +1,48 @@ +import json +import sys + +import pytest + +from app import mcp_stdio +from app.core import config + + +def clips_of(reply): + return json.loads(reply["result"]["contents"][0]["text"]) + + +@pytest.fixture +def no_override(monkeypatch): + monkeypatch.delenv("FORMRIG_CLIPS", raising=False) + + +def bundle(root): + folder = root / "clips" + folder.mkdir(parents=True) + (folder / "walk.bvh").write_text("x") + (folder / "index.json").write_text(json.dumps([{"file": "walk.bvh", "name": "Walk", "licence": "CC0", "credit": "me"}])) + return folder + + +def test_clip_resource_reads_the_clips_bundled_into_a_frozen_engine(tmp_path, monkeypatch, no_override): + folder = bundle(tmp_path / "meipass") + monkeypatch.setattr(sys, "_MEIPASS", str(tmp_path / "meipass"), raising=False) + monkeypatch.setattr(config, "REPO", tmp_path / "nowhere") + out = clips_of(mcp_stdio.read_resource(1, "formrig://library/clips")) + assert out == [{"name": "Walk", "path": str((folder / "walk.bvh").resolve()), "licence": "CC0", "credit": "me"}] + + +def test_clip_resource_matches_the_window_listing(tmp_path, monkeypatch): + folder = bundle(tmp_path) + (folder / "index.json").write_text(json.dumps([{"file": "walk.bvh"}, {"file": "../outside.bvh"}, {"file": "missing.bvh"}])) + (tmp_path / "outside.bvh").write_text("x") + monkeypatch.setenv("FORMRIG_CLIPS", str(folder)) + out = clips_of(mcp_stdio.read_resource(1, "formrig://library/clips")) + assert [c["path"] for c in out] == [str((folder / "walk.bvh").resolve())] + + +def test_clip_resource_survives_a_damaged_index(tmp_path, monkeypatch): + folder = bundle(tmp_path) + (folder / "index.json").write_text('{"file": "walk.bvh"}') + monkeypatch.setenv("FORMRIG_CLIPS", str(folder)) + assert clips_of(mcp_stdio.read_resource(1, "formrig://library/clips")) == [] From fd30efa873174c2dd53ad50adc4ecc9b0f180a90 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 08:52:43 -0500 Subject: [PATCH 4/8] fix(engine): tidy up before exiting when the app is gone The parent watch runs the service shutdown, which removes engine.json and closes terminals, before the engine exits. --- backend/HASHOUT_LOG.md | 2 + backend/app/main.py | 4 ++ backend/formrig_engine.py | 27 +++++++--- .../tests/rb02/test_engine_parent_watch.py | 53 +++++++++++++++++++ 4 files changed, 78 insertions(+), 8 deletions(-) create mode 100644 backend/tests/rb02/test_engine_parent_watch.py diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 295205d..f23dea7 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -10,6 +10,8 @@ Living context for the FastAPI engine service. What would be comments in `backen - The finder is 1.0.2 with its hash in `setup/agents.py`; other Form engines carrying 1.0.1 need the same file and hash. - `routers/agent.py`: a `load_rig` of a `.frig` without the window token asks `doc.summary` first and answers 409 `UNSAVED` while `dirty` is true (or the summary fails), since `file.open` runs `Session::reset` and clears history. The window keeps its own `mayReplace()` prompt and is not checked here. `file.import` goes through `Session::replace`, which records an undo step, so it is left as it was. - `services/clip_library.py` holds the clip folder lookup (`FORMRIG_CLIPS`, then `_MEIPASS/clips` in a frozen engine, then `assets/clips`) and the checked listing that `/api/library/clips` used. The MCP resource `formrig://library/clips` now returns that same listing (`name`, `path`, `licence`, `credit`, `skeleton` for a paired `.amc`), so the installed app's MCP server finds the bundled clips. The resource no longer carries the raw `file` field. +- `formrig_engine.py`: the parent watch (`wait_for_parent`) calls `tidy()` before `os._exit(0)`, which runs `app.main.shutdown()` (the lifespan teardown: GoF watcher stop and `engine.json` retract, terminals, agent config files) when the service module is loaded, and ignores any error so the exit still happens. The Windows quit in `src-tauri/src/main.rs` is still a hard kill; nothing in the engine runs after it, so `engine.json` can still be left behind there. +- Integrations: with a left-over `engine.json`, Unreal `_hop` and Unity `Hop` read a refused connection (`ConnectionRefusedError`, `WebExceptionStatus.ConnectFailure`) as FormRig not running and go on to start the configured app or say it is not open. Any other failure (a refusal by the engine, a timeout) keeps the "will show the return in a moment" message. The Unity change was not compiled here. - Removed code: `routers/library.py` `_clips_dir` and its loop, moved whole into `services/clip_library.py`; the MCP resource's own read of `config.REPO/assets/clips/index.json`. ## 2026-11-28 · v0.14.3 (routers/gof.py, services/engine.py) diff --git a/backend/app/main.py b/backend/app/main.py index 00afe11..f28d6b5 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -30,6 +30,10 @@ async def lifespan(_: FastAPI): claude_code.sweep() terminals.bind(asyncio.get_running_loop()) yield + shutdown() + + +def shutdown() -> None: gof_return.stop() terminals.close_all() claude_code.revoke_all() diff --git a/backend/formrig_engine.py b/backend/formrig_engine.py index 9d2714e..93108b4 100644 --- a/backend/formrig_engine.py +++ b/backend/formrig_engine.py @@ -59,20 +59,31 @@ def parent_alive(pid: int) -> bool: return True +def tidy() -> None: + service = sys.modules.get("app.main") + try: + if service is not None: + service.shutdown() + except Exception: + pass + + +def wait_for_parent(pid: int) -> None: + import time + + while parent_alive(pid): + time.sleep(1.5) + tidy() + os._exit(0) + + def watch_parent() -> None: raw = os.environ.get("FORMRIG_PARENT_PID", "") if not raw.isdigit(): return - pid = int(raw) import threading - import time - - def loop() -> None: - while parent_alive(pid): - time.sleep(1.5) - os._exit(0) - threading.Thread(target=loop, name="parent-watch", daemon=True).start() + threading.Thread(target=wait_for_parent, args=(int(raw),), name="parent-watch", daemon=True).start() def free_port() -> int: diff --git a/backend/tests/rb02/test_engine_parent_watch.py b/backend/tests/rb02/test_engine_parent_watch.py new file mode 100644 index 0000000..5475ab9 --- /dev/null +++ b/backend/tests/rb02/test_engine_parent_watch.py @@ -0,0 +1,53 @@ +import json +import os +import sys +import types + +import formrig_engine +from app.core import config +from app.services import gof_return + + +class Exited(Exception): + pass + + +def test_engine_tidies_up_before_it_exits_when_the_app_is_gone(monkeypatch): + order = [] + monkeypatch.setattr(formrig_engine, "parent_alive", lambda pid: False) + monkeypatch.setitem(sys.modules, "app.main", types.SimpleNamespace(shutdown=lambda: order.append("shutdown"))) + + def leave(code): + order.append(("exit", code)) + raise Exited + + monkeypatch.setattr(formrig_engine.os, "_exit", leave) + try: + formrig_engine.wait_for_parent(1234) + except Exited: + pass + assert order == ["shutdown", ("exit", 0)] + + +def test_engine_still_exits_when_tidying_up_fails(monkeypatch): + def broken(): + raise RuntimeError("busy") + + monkeypatch.setitem(sys.modules, "app.main", types.SimpleNamespace(shutdown=broken)) + formrig_engine.tidy() + + +def test_engine_exits_without_tidying_when_the_service_never_started(monkeypatch): + monkeypatch.delitem(sys.modules, "app.main", raising=False) + formrig_engine.tidy() + + +def test_shutdown_removes_the_engine_file(data_dir, monkeypatch): + from app import main + + gof_return.publish_engine() + path = data_dir / "engine.json" + assert json.loads(path.read_text())["pid"] == os.getpid() + main.shutdown() + assert not path.exists() + assert config.data_dir() == data_dir From 708bd3362dde65ff8d8be9f2cc8be49726930825 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 08:52:43 -0500 Subject: [PATCH 5/8] fix(integrations): start FormRig when a left-over engine file names a closed port Unreal and Unity treat a refused connection as FormRig not running and go on to start the configured app instead of waiting. --- .../test_integrations_unreal_formrig_gof.py | 20 +++++++++++++++++++ integrations/unity/Editor/FormRigReturn.cs | 10 +++++++--- .../unreal/Content/Python/formrig_gof.py | 8 +++++--- 3 files changed, 32 insertions(+), 6 deletions(-) diff --git a/backend/tests/rb04/test_integrations_unreal_formrig_gof.py b/backend/tests/rb04/test_integrations_unreal_formrig_gof.py index d166b4f..85e70e8 100644 --- a/backend/tests/rb04/test_integrations_unreal_formrig_gof.py +++ b/backend/tests/rb04/test_integrations_unreal_formrig_gof.py @@ -570,6 +570,26 @@ def refuse(request, timeout): assert any("turn on Agent link" in line for line in sender.fake.logs) +@pytest.mark.parametrize("closed", [lambda e: e.URLError(ConnectionRefusedError(61, "refused")), lambda e: ConnectionRefusedError(61, "refused")]) +def test_send_back_starts_the_app_when_a_left_over_engine_file_names_a_closed_port(sender, tmp_path, monkeypatch, closed): + data = tmp_path / "data" + data.mkdir() + (data / "engine.json").write_text(json.dumps({"port": 8270, "pid": 999999}), encoding="utf-8") + app = tmp_path / "formrig-app" + app.write_text("x", encoding="utf-8") + monkeypatch.setenv("FORMRIG_APP", str(app)) + + def refuse(request, timeout): + raise closed(sender.urllib.error) + + launched = [] + monkeypatch.setattr(sender.urllib.request, "urlopen", refuse) + monkeypatch.setattr(subprocess, "Popen", lambda argv: launched.append(argv)) + manifest = sender.send_back("/Game/hero_unreal") + assert launched == [[str(app), manifest]] + assert not any("FormRig is open" in line for line in sender.fake.logs) + + def test_send_back_says_formrig_is_closed_when_no_engine_and_no_app(sender): sender.send_back("/Game/hero_unreal") assert any("FormRig is not open" in line for line in sender.fake.logs) diff --git a/integrations/unity/Editor/FormRigReturn.cs b/integrations/unity/Editor/FormRigReturn.cs index decb44d..c5b0994 100644 --- a/integrations/unity/Editor/FormRigReturn.cs +++ b/integrations/unity/Editor/FormRigReturn.cs @@ -580,12 +580,16 @@ static void Hop(string manifestPath, Running running) using (Stream s = request.GetRequestStream()) s.Write(body, 0, body.Length); using (request.GetResponse()) { } Debug.Log("FormRig return: FormRig is open and has the return"); + return; } - catch (WebException) + catch (WebException e) { - Debug.Log("FormRig return: FormRig is open and will show the return in a moment (turn on Agent link in FormRig to hand it over at once)"); + if (e.Status != WebExceptionStatus.ConnectFailure) + { + Debug.Log("FormRig return: FormRig is open and will show the return in a moment (turn on Agent link in FormRig to hand it over at once)"); + return; + } } - return; } string app = EditorPrefs.GetString(AppKey, ""); if (!string.IsNullOrEmpty(app) && File.Exists(app)) diff --git a/integrations/unreal/Content/Python/formrig_gof.py b/integrations/unreal/Content/Python/formrig_gof.py index a0c142c..f682f0a 100644 --- a/integrations/unreal/Content/Python/formrig_gof.py +++ b/integrations/unreal/Content/Python/formrig_gof.py @@ -212,9 +212,11 @@ def _hop(manifest, info): try: urllib.request.urlopen(request, timeout=2).close() unreal.log("FormRig return: FormRig is open and has the return") - except (urllib.error.URLError, OSError): - unreal.log("FormRig return: FormRig is open and will show the return in a moment (turn on Agent link in FormRig to hand it over at once)") - return + return + except (urllib.error.URLError, OSError) as exc: + if not isinstance(getattr(exc, "reason", exc), ConnectionRefusedError): + unreal.log("FormRig return: FormRig is open and will show the return in a moment (turn on Agent link in FormRig to hand it over at once)") + return app = os.environ.get("FORMRIG_APP", "").strip() if app and os.path.isfile(app): import subprocess From 9e8061b6562b14e4a7e75a3b32906e5a0d7ba8a3 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:55:40 -0500 Subject: [PATCH 6/8] fix(agents): start node for an npm shim only from a full-path node.exe The node found on the child PATH for an npm shim must be node.exe in a full-path folder; a node.cmd or node.bat, a relative entry or the current folder are skipped. A script ending is matched with trailing dots and spaces dropped. The finder 1.0.2 hash is updated. --- backend/HASHOUT_LOG.md | 2 +- backend/app/services/agent_lookup.py | 7 +++--- .../tests/rb02/test_services_agent_lookup.py | 25 ++++++++++++++++--- setup/agents.py | 2 +- 4 files changed, 27 insertions(+), 9 deletions(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index f23dea7..7c59418 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -4,7 +4,7 @@ Living context for the FastAPI engine service. What would be comments in `backen ## 2026-11-29 · unreleased (services/agent_lookup.py 1.0.2, services/claude_code.py, services/agent_programs.py, setup/agents.py) -- Windows start of a `.cmd` or `.bat` program: `start_argv` reads the script (64 KiB at most) and, when its last `%*` line names a file under `%dp0%` or `%~dp0`, runs that file directly: an `.exe` as itself, a `.js`, `.cjs` or `.mjs` with the `node.exe` beside the script or the first `node` on the child PATH. This is the npm shim case and needs no command interpreter, so prompt words reach the program unchanged. +- Windows start of a `.cmd` or `.bat` program: `start_argv` reads the script (64 KiB at most) and, when its last `%*` line names a file under `%dp0%` or `%~dp0`, runs that file directly: an `.exe` as itself, a `.js`, `.cjs` or `.mjs` with the `node.exe` beside the script or the first `node.exe` in a full-path folder of the child PATH (quotes around an entry are dropped, relative entries and the current folder are skipped, and a `node.cmd` or `node.bat` is never used, since Windows would start it through the command interpreter). This is the npm shim case and needs no command interpreter, so prompt words reach the program unchanged. A script ending is matched without case and with trailing dots and spaces dropped, as Windows does when it opens the file. - Any other script still goes through `COMSPEC /c`, and `_cmd_words` raises `Unsafe` (an `OSError`, so `check` reports broken and the open routes answer 500 with the text) for a word with a control character, `%` or `"`; for `&|<>^()!` in a word `list2cmdline` leaves unquoted; and for a script path that gets quoted while another word is quoted too or while the path holds one of those characters, because `cmd /c` then drops the first and last quote of the line. - `claude_code.tab_argv` and `agent_programs.open_tab` hand the child environment to `start_argv`, so the node lookup sees the same PATH the tab runs with. - The finder is 1.0.2 with its hash in `setup/agents.py`; other Form engines carrying 1.0.1 need the same file and hash. diff --git a/backend/app/services/agent_lookup.py b/backend/app/services/agent_lookup.py index 8335219..b04786b 100644 --- a/backend/app/services/agent_lookup.py +++ b/backend/app/services/agent_lookup.py @@ -385,8 +385,9 @@ def _shim_target(words: list[str], env: dict) -> list[str] | None: return [str(target), *words[1:]] if target.suffix.lower() not in (".js", ".cjs", ".mjs"): return None - beside = shim.parent / "node.exe" - node = str(beside) if beside.is_file() else shutil.which("node", path=env.get("PATH", "")) + entries = [p.strip().strip('"') for p in env.get("PATH", "").split(";")] + places = [shim.parent, *(Path(p) for p in entries if p and Path(p).is_absolute())] + node = next((str(p / "node.exe") for p in places if (p / "node.exe").is_file()), None) return [node, str(target), *words[1:]] if node else None @@ -413,7 +414,7 @@ def start_argv(cmd: list, env: dict | None = None, platform: str | None = None) words = [str(c) for c in cmd] env = os.environ if env is None else env if windows(platform): - if not words[0].lower().endswith((".cmd", ".bat")): + if not words[0].lower().rstrip(" .").endswith((".cmd", ".bat")): return words return _shim_target(words, env) or [env.get("COMSPEC") or "cmd.exe", "/c", *_cmd_words(words)] shell = login_shell(env, platform) diff --git a/backend/tests/rb02/test_services_agent_lookup.py b/backend/tests/rb02/test_services_agent_lookup.py index 4e2c973..fd77ee7 100644 --- a/backend/tests/rb02/test_services_agent_lookup.py +++ b/backend/tests/rb02/test_services_agent_lookup.py @@ -135,10 +135,27 @@ def test_start_argv_on_windows_runs_an_npm_shim_through_node_without_the_command def test_start_argv_on_windows_finds_node_on_path_for_an_npm_shim(tmp_path): shim, script = npm_install(tmp_path / "npm", node_beside=False) - node = program(tmp_path / "nodejs", "node") - argv = al.start_argv([str(shim), "--version"], {"PATH": str(node.parent)}, "win32") - assert argv[1:] == [str(script), "--version"] - assert Path(argv[0]).parent == node.parent + node = program(tmp_path / "nodejs", "node.exe") + argv = al.start_argv([str(shim), "--version"], {"PATH": f'"{node.parent}";{tmp_path / "other"}'}, "win32") + assert argv == [str(node), str(script), "--version"] + + +def test_start_argv_on_windows_runs_node_only_as_a_program_from_a_full_path_folder(tmp_path, monkeypatch): + shim, _ = npm_install(tmp_path / "npm", node_beside=False) + program(tmp_path / "scripts", "node.cmd") + program(tmp_path / "scripts", "node.bat") + program(tmp_path / "here", "node.exe") + monkeypatch.chdir(tmp_path) + env = {"PATH": f"{tmp_path / 'scripts'};here"} + assert al.start_argv([str(shim), "--version"], env, "win32") == ["cmd.exe", "/c", str(shim), "--version"] + with pytest.raises(al.Unsafe): + al.start_argv([str(shim), "-p", "a&b"], env, "win32") + + +@pytest.mark.parametrize("ending", [".cmd.", ".CMD ", ".Bat"]) +def test_start_argv_on_windows_treats_any_spelling_of_a_script_ending_as_a_script(ending): + with pytest.raises(al.Unsafe): + al.start_argv([f"C:/x/claude{ending}", "-p", "a&b"], {}, "win32") def test_start_argv_on_windows_runs_the_program_a_shim_names_directly(tmp_path): diff --git a/setup/agents.py b/setup/agents.py index 3ee758f..8626734 100644 --- a/setup/agents.py +++ b/setup/agents.py @@ -17,7 +17,7 @@ DOCK = {"present": True, "positions": ["right", "bottom"], "tabs": ["terminal", "claude", "codex", "cursor", "antigravity"]} DOCK_MODULE = ROOT / "frontend" / "src" / "dock" LOOKUP = ROOT / "backend" / "app" / "services" / "agent_lookup.py" -LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", "1.0.2": "1ee96d61ef47474af1551a5ce08d75c435e6249bafca586f7701ebbbce7394ec"} +LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", "1.0.2": "85bd04a26dfc01410d67aee0c27399edc00605946ce68c6526932f3c918515e4"} PORT = int(os.environ.get("FORMRIG_PORT") or 8270) USAGE = """usage: ./formrig agents install [--dry-run] set up Claude Code, Codex, Cursor and Antigravity here and in the folder you ran it from ./formrig agents sync [--check] mirror .claude/skills to .agents/skills and write agents/manifest.json""" From ad49d726c700389c2f807cdc29571c694ced534d Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:55:53 -0500 Subject: [PATCH 7/8] test(agents): use an ordinary character name in the npm shim test --- backend/tests/rb02/test_services_agent_lookup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/tests/rb02/test_services_agent_lookup.py b/backend/tests/rb02/test_services_agent_lookup.py index fd77ee7..c62da10 100644 --- a/backend/tests/rb02/test_services_agent_lookup.py +++ b/backend/tests/rb02/test_services_agent_lookup.py @@ -128,7 +128,7 @@ def npm_install(folder: Path, node_beside: bool = True) -> tuple[Path, Path]: def test_start_argv_on_windows_runs_an_npm_shim_through_node_without_the_command_interpreter(tmp_path): shim, script = npm_install(tmp_path) - name = 'x & calc & y' + name = 'hero & sidekick (copy)' argv = al.start_argv([str(shim), "-p", f'rig it (FormRig window: character "{name}")'], {"COMSPEC": "C:/cmd.exe", "PATH": ""}, "win32") assert argv == [str(tmp_path / "node.exe"), str(script), "-p", f'rig it (FormRig window: character "{name}")'] From 93e0c7b1c856cf1622b5b1d3cf4193f9d2efdf0e Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 11:29:14 -0500 Subject: [PATCH 8/8] fix(agents): refuse command interpreter special characters in every script word When a .cmd or .bat still has to go through the command interpreter, any word, the script path included, that holds one of & | < > ^ ( ) ! % or a double quote, or a control character, is refused whether or not it holds spaces. The message points to standard input or a file for long text. The finder 1.0.2 hash is updated. --- backend/HASHOUT_LOG.md | 2 +- backend/app/services/agent_lookup.py | 17 +++++++-------- .../tests/rb02/test_services_agent_lookup.py | 21 ++++++++++++++++--- setup/agents.py | 2 +- 4 files changed, 28 insertions(+), 14 deletions(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 7c59418..8ea3c86 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -5,7 +5,7 @@ Living context for the FastAPI engine service. What would be comments in `backen ## 2026-11-29 · unreleased (services/agent_lookup.py 1.0.2, services/claude_code.py, services/agent_programs.py, setup/agents.py) - Windows start of a `.cmd` or `.bat` program: `start_argv` reads the script (64 KiB at most) and, when its last `%*` line names a file under `%dp0%` or `%~dp0`, runs that file directly: an `.exe` as itself, a `.js`, `.cjs` or `.mjs` with the `node.exe` beside the script or the first `node.exe` in a full-path folder of the child PATH (quotes around an entry are dropped, relative entries and the current folder are skipped, and a `node.cmd` or `node.bat` is never used, since Windows would start it through the command interpreter). This is the npm shim case and needs no command interpreter, so prompt words reach the program unchanged. A script ending is matched without case and with trailing dots and spaces dropped, as Windows does when it opens the file. -- Any other script still goes through `COMSPEC /c`, and `_cmd_words` raises `Unsafe` (an `OSError`, so `check` reports broken and the open routes answer 500 with the text) for a word with a control character, `%` or `"`; for `&|<>^()!` in a word `list2cmdline` leaves unquoted; and for a script path that gets quoted while another word is quoted too or while the path holds one of those characters, because `cmd /c` then drops the first and last quote of the line. +- Any other script still goes through `COMSPEC /c`, and `_cmd_words` raises `Unsafe` (an `OSError`, so `check` reports broken and the open routes answer 500 with the text) for any word, the script path included, holding a control character (`\x00`-`\x1f`, `\x7f`) or any of `&|<>^()!%"`, with or without spaces, since the script re-reads `%*` and the command interpreter acts on these even inside quotes. The message tells the caller to pass long text through standard input or a file. It also refuses a script path that gets quoted while another word is quoted too, because `cmd /c` then drops the first and last quote of the line. The earlier exemption for special characters inside a quoted word is removed. - `claude_code.tab_argv` and `agent_programs.open_tab` hand the child environment to `start_argv`, so the node lookup sees the same PATH the tab runs with. - The finder is 1.0.2 with its hash in `setup/agents.py`; other Form engines carrying 1.0.1 need the same file and hash. - `routers/agent.py`: a `load_rig` of a `.frig` without the window token asks `doc.summary` first and answers 409 `UNSAVED` while `dirty` is true (or the summary fails), since `file.open` runs `Session::reset` and clears history. The window keeps its own `mayReplace()` prompt and is not checked here. `file.import` goes through `Session::replace`, which records an undo step, so it is left as it was. diff --git a/backend/app/services/agent_lookup.py b/backend/app/services/agent_lookup.py index b04786b..c2e2671 100644 --- a/backend/app/services/agent_lookup.py +++ b/backend/app/services/agent_lookup.py @@ -45,7 +45,7 @@ MARK = "__FORM_AGENT_LOOKUP__" HOW = {"setting": "your setting", "override": "the development override", "path": "the engine's PATH", "folder": "a known install folder", "shell": "your shell's PATH"} RETRY_SECONDS = 60.0 -CMD_SPECIAL = frozenset("&|<>^()!") +CMD_SPECIAL = frozenset('&|<>^()!%"') SHIM_WORD = re.compile(r'"%(?:~dp0|dp0%)\\?([^"%]+)"') SHIM_LIMIT = 65536 @@ -393,15 +393,14 @@ def _shim_target(words: list[str], env: dict) -> list[str] | None: def _cmd_words(words: list[str]) -> list[str]: name = Path(words[0]).name - quoted = [not w or " " in w or "\t" in w for w in words] - for word, inside in zip(words, quoted): + hint = "; pass long text through standard input or a file if the program supports it" + for word in words: if re.search(r"[\x00-\x1f\x7f]", word): - raise Unsafe(f"{name} is a command script and a word for it holds a control character, such as a line break") - if "%" in word or '"' in word: - raise Unsafe(f"{name} is a command script and a word for it holds % or a double quote, which the command interpreter would change") - if not inside and CMD_SPECIAL & set(word): - raise Unsafe(f"{name} is a command script and a word for it holds one of {''.join(sorted(CMD_SPECIAL))} outside quotes") - if quoted[0] and (any(quoted[1:]) or CMD_SPECIAL & set(words[0])): + raise Unsafe(f"{name} is a command script and a word for it holds a control character, such as a line break{hint}") + if CMD_SPECIAL & set(word): + raise Unsafe(f"{name} is a command script and a word for it holds one of {''.join(sorted(CMD_SPECIAL))}, which the command interpreter reads even inside quotes{hint}") + quoted = [not w or " " in w for w in words] + if quoted[0] and any(quoted[1:]): raise Unsafe(f"{name} is a command script in a folder whose path the command interpreter cannot keep quoted together with these words") return words diff --git a/backend/tests/rb02/test_services_agent_lookup.py b/backend/tests/rb02/test_services_agent_lookup.py index c62da10..3d89438 100644 --- a/backend/tests/rb02/test_services_agent_lookup.py +++ b/backend/tests/rb02/test_services_agent_lookup.py @@ -173,9 +173,24 @@ def test_start_argv_on_windows_refuses_words_the_command_interpreter_would_read( al.start_argv(["C:/x/claude.cmd", "-p", word], {}, "win32") -def test_start_argv_on_windows_passes_quoted_special_characters_to_a_script(): - argv = al.start_argv(["C:/x/claude.cmd", "-p", "rig a & b (now)"], {}, "win32") - assert argv == ["cmd.exe", "/c", "C:/x/claude.cmd", "-p", "rig a & b (now)"] +@pytest.mark.parametrize("word", ["rig a & b (now)", "a | b", "say ^ this", "keep 50 %", 'the "hero" rig', "wow !", "x < y"]) +def test_start_argv_on_windows_refuses_special_characters_for_a_script_even_with_spaces(word): + with pytest.raises(al.Unsafe, match="standard input or a file"): + al.start_argv(["C:/x/claude.cmd", "-p", word], {}, "win32") + + +@pytest.mark.parametrize("path", ["C:/a&b/claude.cmd", "C:/100%/claude.cmd", "C:/x!/claude.cmd"]) +def test_start_argv_on_windows_refuses_special_characters_in_the_script_path(path): + with pytest.raises(al.Unsafe): + al.start_argv([path, "--version"], {}, "win32") + + +def test_start_argv_on_windows_refuses_special_characters_when_an_npm_shim_has_no_node(tmp_path): + shim, _ = npm_install(tmp_path / "npm", node_beside=False) + env = {"COMSPEC": "C:/cmd.exe", "PATH": ""} + assert al.start_argv([str(shim), "-p", "plain"], env, "win32") == ["C:/cmd.exe", "/c", str(shim), "-p", "plain"] + with pytest.raises(al.Unsafe): + al.start_argv([str(shim), "-p", "a (b)"], env, "win32") def test_start_argv_on_windows_refuses_a_quoted_script_path_with_more_quoted_words(): diff --git a/setup/agents.py b/setup/agents.py index 8626734..0bff33d 100644 --- a/setup/agents.py +++ b/setup/agents.py @@ -17,7 +17,7 @@ DOCK = {"present": True, "positions": ["right", "bottom"], "tabs": ["terminal", "claude", "codex", "cursor", "antigravity"]} DOCK_MODULE = ROOT / "frontend" / "src" / "dock" LOOKUP = ROOT / "backend" / "app" / "services" / "agent_lookup.py" -LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", "1.0.2": "85bd04a26dfc01410d67aee0c27399edc00605946ce68c6526932f3c918515e4"} +LOOKUP_HASHES = {"1.0.0": "252ea9bb9419d4990f174f91914f09800497bc69e98f849f5643bbf4217cc3f3", "1.0.1": "62667f9b68b7d101e1896ce617240424e33b7e498c560bc79d45f0ab26c77d51", "1.0.2": "040401c31053eb1a71c7545b047776af5b61b28f3e671221bd8300989bf1f01e"} PORT = int(os.environ.get("FORMRIG_PORT") or 8270) USAGE = """usage: ./formrig agents install [--dry-run] set up Claude Code, Codex, Cursor and Antigravity here and in the folder you ran it from ./formrig agents sync [--check] mirror .claude/skills to .agents/skills and write agents/manifest.json"""