Skip to content
Merged
2 changes: 1 addition & 1 deletion .docs/wiki/GoF.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<data>/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 `<data>/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

Expand Down
12 changes: 12 additions & 0 deletions backend/HASHOUT_LOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,18 @@

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.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 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.
- `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)

- `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.
Expand Down
4 changes: 4 additions & 0 deletions backend/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
11 changes: 2 additions & 9 deletions backend/app/mcp_stdio.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
15 changes: 12 additions & 3 deletions backend/app/routers/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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")
Expand All @@ -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 {}
Expand All @@ -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()
Expand All @@ -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)}
37 changes: 2 additions & 35 deletions backend/app/routers/library.py
Original file line number Diff line number Diff line change
@@ -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()}
56 changes: 53 additions & 3 deletions backend/app/services/agent_lookup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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 = {}
Expand Down Expand Up @@ -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
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


def _cmd_words(words: list[str]) -> list[str]:
name = Path(words[0]).name
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{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


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().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)
fish = Path(shell).name == "fish"
return [shell, "-l", "-c", "exec " + " ".join(_quote(w, fish) for w in words)]
Expand Down
3 changes: 2 additions & 1 deletion backend/app/services/agent_programs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
7 changes: 4 additions & 3 deletions backend/app/services/claude_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
Expand Down
40 changes: 40 additions & 0 deletions backend/app/services/clip_library.py
Original file line number Diff line number Diff line change
@@ -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
27 changes: 19 additions & 8 deletions backend/formrig_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading