Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions backend/HASHOUT_LOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ Decisions, reasons and anything left out, newest first. Code carries no comments
## Unreleased (2026-11-19): four agent programs, found by the family's finder, and tests that start none of them

- `app/services/agent_lookup.py` (new) is the family's finder, version 1.0.1, copied unchanged from FormVis and never edited here; `setup/agents.py` holds the hash for each version. It looks, in order, at the development override variable, the engine's PATH, the known install folders and the person's shell PATH, and answers three ways: runs, found but does not start, not found. The reason: an app started from the Dock, the Start menu or a desktop launcher gets the system's short PATH, and a bare PATH search called installed programs missing.
- `app/services/consent.py` :: `details`, `declared`, `unknown`, `unknown_refusal`, `check` · The lines in a request to allow an outside agent's call are built only from the arguments the tool's schema declares; a call that names any other argument is refused before anyone is asked, with a message that names the extra arguments. Path, folder and target arguments come first, then the rest in schema order. Text values are quoted and kept printable; a long path shows its end and any other long value its start, each marked with its full length; a list shows five items and how many more; past eight lines the last says how many arguments are not shown. The first line says the arguments are as sent by the named agent and not checked by formtools. The reason: the person decides from these lines, so they show only what the tool will act on and say where it came from.
- `agent_lookup.py` 1.0.2 · On Windows a `.cmd` or `.bat` program is started as the program its npm-style shim names (`node` with the script, or the `.exe`), so the words reach it unchanged. A batch file it cannot read that way still goes through the command interpreter, and `start_argv` raises `StartRefused` (an `OSError`) for any word with a control character (0x00 to 0x1f, 0x7f) or one of `& | < > ^ ( ) ! %` and the double quote, whether or not the word has spaces; the message says to pass long text through standard input or a file. The reason: the interpreter and the shim's `%*` read the whole line again, quotes do not protect a word there, and backslash escaping does not hold. When the program's own path needs quotes, `cmd /c` keeps the line only with no other word that needs quotes, so that is refused too. A `node` found on PATH that is itself a `.cmd` or `.bat` is not used for a direct start.
- `app/services/claude_code.py` :: `child_env`, `located`, `usable`, `said`, `cli`, `_signed_in`, `info`, `start`, `program`, `terminal_argv`, `open_terminal`. Every look for Claude Code and every start goes through the finder. `_from_login_shell`, `CANDIDATES` and `SYSTEM_PATHS` are gone; the finder holds that list. `child_env` takes the program's path so its own folder is first on PATH (a node script finds the node beside it). formtools has no path setting, so `setting()` answers `None`. Override variables: `FORMTOOLS_CLAUDE_BIN`, `FORMTOOLS_CODEX_BIN`, `FORMTOOLS_CURSOR_BIN`, `FORMTOOLS_ANTIGRAVITY_BIN`.
- `app/services/agent_programs.py` :: `PROGRAMS`, `find`, `status`, `_describe`, `open_terminal`. Antigravity (`agy`) is the fourth program. `status` and `programs` keep their names and add the finder's fields per program: `finding` (`runs`, `broken`, `missing`), `how`, `looked`, `error`, `said`. `installed` is true only when `--version` ran with exit code 0. Antigravity's `signedIn` stays `None`: it has no status command. `_version` is gone; the finder reads the version.
- The Antigravity tab: `tab_folder`, `write_tab_entry`, `remove_tab_entry`. Antigravity reads its MCP servers from a file in its workspace, so its tab runs in a folder of formtools's own, `<data>/AgentTabs/antigravity`, and gets the entry `formtools_tab` (the address and the tab's token) in `.agents/mcp_config.json` there, mode 0600, written whole, every other entry and key kept. The entry is taken out when the tab closes, only while it still carries that tab's token. Decision: not the shared `<data>/Agent` folder the other tabs use, because `FORMTOOLS_AGENT_DIR` can point that at a folder of the person's, and a token does not belong there. Two Antigravity tabs share the one entry; the newer tab's token wins. The Codex and Cursor tabs are unchanged (token in the environment, the per-tab file named by `FORMTOOLS_MCP_CONFIG`).
Expand Down
2 changes: 2 additions & 0 deletions backend/app/core/filetypes.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import mimetypes

INERT_HEADERS = {"X-Content-Type-Options": "nosniff", "Content-Security-Policy": "sandbox"}

FAMILY = frozenset("fvd fmv formvis fc fmw fsc fequeue fldb".split())

RAW = frozenset(
Expand Down
4 changes: 2 additions & 2 deletions backend/app/routers/fs.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from fastapi.responses import FileResponse

from app.core.errors import ApiError
from app.core.filetypes import classify, content_type, ext_of
from app.core.filetypes import INERT_HEADERS, classify, content_type, ext_of

router = APIRouter(prefix="/api")

Expand Down Expand Up @@ -212,4 +212,4 @@ def file_raw(path: str) -> FileResponse:
pass
except OSError:
raise ApiError(400, "formtools is not allowed to read that file")
return FileResponse(target, media_type=content_type(target.name), content_disposition_type="inline")
return FileResponse(target, media_type=content_type(target.name), content_disposition_type="inline", headers=INERT_HEADERS)
68 changes: 65 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 Down Expand Up @@ -359,13 +359,75 @@ def _quote(word: str, fish: bool) -> str:
return "'" + word.replace("'", "'\"'\"'") + "'"


class StartRefused(OSError):
pass


SHIM_TARGET = re.compile(r'"%~?dp0%?\\([^"%*?<>|\r\n]+)"\s*%\*')
SHIM_BYTES = 65536
CMD_SPECIAL = frozenset('&|<>^()!%"')
CMD_REFUSED = ("this program is started through the Windows command interpreter, which reads {what} as commands even inside quotes, "
"so the start was refused; remove them, or pass long text through standard input or a file if the program supports it")


def shim_target(path: str, env: dict) -> list[str] | None:
"""The program an npm-style .cmd shim starts, so it can be started directly: [node, script] for a script, [program] for
an .exe beside the shim. None when the shim is not one this recognises or its target is missing."""
try:
with open(path, "rb") as f:
text = f.read(SHIM_BYTES).decode("utf-8", "replace")
except OSError:
return None
found = SHIM_TARGET.search(text)
if not found:
return None
folder = Path(path).parent
target = folder.joinpath(*found.group(1).split("\\"))
if not target.is_file():
return None
if target.suffix.lower() == ".exe":
return [str(target)]
if target.suffix.lower() not in (".js", ".cjs", ".mjs"):
return None
beside = folder / "node.exe"
node = str(beside) if beside.is_file() else shutil.which("node", path=env.get("PATH") or None)
return [node, str(target)] if node and not node.lower().endswith((".cmd", ".bat")) else None


def _quoted(word: str) -> bool:
return " " in word or "\t" in word or not word


def cmd_safe(words: list[str]) -> None:
"""Refuses any word the command interpreter could read as more than text, quoted or not: a control character or one of
& | < > ^ ( ) ! % and the double quote. When the program itself is quoted, cmd /c keeps the line only when no other
word needs quotes, so that is refused too."""
for word in words:
if any(ord(ch) < 32 or ord(ch) == 127 for ch in word):
raise StartRefused(CMD_REFUSED.format(what="line breaks and control characters"))
if CMD_SPECIAL.intersection(word):
raise StartRefused(CMD_REFUSED.format(what='the characters & | < > ^ ( ) ! % "'))
if _quoted(words[0]) and any(_quoted(word) for word in words[1:]):
raise StartRefused("this program is in a folder with spaces and is started through the Windows command interpreter, which "
"drops the quotes when another word has spaces, so the start was refused; remove the spaces from the other "
"words, move the program to a folder without spaces, or pass long text through standard input or a file "
"if the program supports it")


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 is started as the program its shim names when
it can be read, otherwise through the command interpreter with every word checked by cmd_safe."""
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
direct = shim_target(words[0], env)
if direct:
return [*direct, *words[1:]]
cmd_safe(words)
return [env.get("COMSPEC") or "cmd.exe", "/c", *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
97 changes: 95 additions & 2 deletions backend/app/services/consent.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@
WHERE = "formtools, Settings, Integration, Outside agents"
BLOCKED = f"Outside agents are blocked in {WHERE}, so this call was refused. Tell the person where to change it and stop; do not retry."
BLOCKED_INSIDE = f"Agents are blocked in {WHERE}, and that includes this tab, so this call was refused. Tell the person where to change it and stop; do not retry."
PUBLIC = ("id", "tool", "title", "effect", "at", "agent", "agentNamed", "what", "answers", "alwaysScope", "expires")
PUBLIC = ("id", "tool", "title", "effect", "at", "agent", "agentNamed", "what", "details", "answers", "alwaysScope", "expires")
DETAIL_LINES = 8
VALUE_CHARS = 160
ITEM_CHARS = 60
LIST_SHOWN = 5
PATH_WORDS = ("path", "folder", "dir", "dest", "target", "out", "input")
DENIED = "The person did not allow this in the formtools window, so it was refused. Do not retry unless they ask you to."
NO_WINDOW = f"formtools asks the person before an outside agent changes anything, and no formtools window is open to ask. Ask them to open formtools, or to choose Allowed in {WHERE}."
TIMED_OUT = "Nobody answered in the formtools window in time, so this call was refused. Ask the person to look at the formtools window, then retry."
Expand Down Expand Up @@ -88,6 +93,91 @@ def what(tool, arguments) -> str:
return f"run {tool.name}"


def _plain(text: str) -> str:
return "".join(ch if ch.isprintable() else f"\\u{ord(ch):04x}" for ch in text)


def _resolved(value: str) -> str:
parts = value.replace(os.altsep or os.sep, os.sep).split(os.sep)
if ".." not in parts or not os.path.isabs(value):
return value
head, name = os.path.split(value.rstrip(os.sep))
return os.path.realpath(value) if name == ".." else os.path.join(os.path.realpath(head), name)


def _text(value) -> tuple[str, bool]:
if isinstance(value, str):
return _resolved(value), True
try:
return json.dumps(value, ensure_ascii=False, sort_keys=True, default=str), False
except ValueError:
return str(value), False


def _quote(text: str) -> str:
return '"' + text.replace('"', '\\"') + '"'


def _value(value, pathy: bool, limit: int) -> str:
text, string = _text(value)
text = _plain(text)
if len(text) <= limit:
return _quote(text) if string else text
cut = "..." + text[-limit:] if pathy else text[:limit] + "..."
shown = _quote(cut) if string else cut
return f"{shown} (shortened from {len(text)} characters)"


def _shown(value, pathy: bool) -> str:
if not isinstance(value, list):
return _value(value, pathy, VALUE_CHARS)
items = [_value(v, pathy, ITEM_CHARS) for v in value[:LIST_SHOWN]]
more = len(value) - LIST_SHOWN
return ", ".join(items) + (f", and {more} more" if more > 0 else "") if items else "[]"


def _pathy(name: str) -> bool:
low = name.lower()
return any(word in low for word in PATH_WORDS)


def declared(tool) -> list[str]:
schema = tool.schema.get("properties") if isinstance(tool.schema, dict) else None
return list(schema) if isinstance(schema, dict) else []


def unknown(tool, arguments) -> list[str]:
if not isinstance(arguments, dict):
return []
known = set(declared(tool))
return [str(name) for name in arguments if name not in known]


def _names(tool, arguments: dict) -> list[str]:
skip = {"id"} if tool.name == "run_command" else set()
known = [name for name in declared(tool) if name in arguments and name not in skip]
return [*(n for n in known if _pathy(n)), *(n for n in known if not _pathy(n))]


def details(tool, arguments, agent: str = "") -> list[str]:
if not isinstance(arguments, dict):
return []
lines = [f"{_plain(name)}: {_shown(arguments[name], _pathy(name))}" for name in _names(tool, arguments)]
if not lines:
return []
if len(lines) > DETAIL_LINES:
lines = [*lines[:DETAIL_LINES - 1], f"and {len(lines) - DETAIL_LINES + 1} more arguments not shown"]
who = _plain(agent or agents.UNNAMED)[:80]
return [f"Arguments as sent by {who}, not checked by formtools:", *lines]


def unknown_refusal(tool, names: list[str]) -> str:
listed = ", ".join(_quote(_plain(n)[:40]) for n in names[:LIST_SHOWN])
more = f" and {len(names) - LIST_SHOWN} more" if len(names) > LIST_SHOWN else ""
return (f"This call gave {tool.name} arguments it does not take ({listed}{more}), so it was refused before asking the person. "
"Send only the arguments the tool lists, then retry.")


def _tell(kind: str, **fields) -> None:
try:
from_thread.run(bridge.notify, {"t": kind, **fields})
Expand Down Expand Up @@ -121,11 +211,14 @@ def check(tool, inapp: bool, agent: str = "", arguments: dict | None = None) ->
return BLOCKED_INSIDE if inapp else BLOCKED
if inapp or mode == "allowed":
return None
extra = unknown(tool, arguments)
if extra:
return unknown_refusal(tool, extra)
if not bridge.connected():
return NO_WINDOW
now = time.time()
item = {"id": secrets.token_urlsafe(12), "tool": tool.name, "title": tool.description, "effect": tool.effect, "at": now, "answer": None, "done": threading.Event(),
"agent": agent or agents.UNNAMED, "agentNamed": bool(agent) and agent != agents.UNNAMED, "what": what(tool, arguments),
"agent": agent or agents.UNNAMED, "agentNamed": bool(agent) and agent != agents.UNNAMED, "what": what(tool, arguments), "details": details(tool, arguments, agent),
"answers": ["deny", "once", "always"] if seal.available() else ["deny", "once"], "alwaysScope": "all", "expires": now + WAIT}
with _lock:
_pending[item["id"]] = item
Expand Down
4 changes: 2 additions & 2 deletions backend/app/tools/desktop/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def hosts_read_tool(_: dict) -> dict:

def env_read_tool(args: dict) -> dict:
scope = args.get("scope")
return envvars.scopes(str(scope) if scope else None)
return envvars.for_agents(envvars.scopes(str(scope) if scope else None))


registry.register(
Expand All @@ -33,7 +33,7 @@ def env_read_tool(args: dict) -> dict:
),
McpTool(
"env_read",
"Read environment variables by scope: process (this engine), user and system where the system has them. Each scope says whether the window can edit it and where it is stored. Read only; edits are made in the formtools window.",
"Read environment variables by scope: process (this engine), user and system where the system has them. Each scope says whether the window can edit it and where it is stored. Read only; edits are made in the formtools window. A variable whose name or value looks like a key, token, password or signed-in address comes back with an empty value and hidden true; the window shows it.",
ENV_SCHEMA,
env_read_tool,
effect=READS,
Expand Down
20 changes: 20 additions & 0 deletions backend/app/tools/desktop/envvars.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@
POSIX_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
PLAIN_VALUE = re.compile(r"^[A-Za-z0-9_@%+=:,./~-]+$")
LINE_NAME = re.compile(r"^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=")
SECRET_NAME = re.compile(r"KEY|TOKEN|SECRET|PASS|CREDENTIAL|CREDS|AUTH|COOKIE|SESSION|PRIVATE|SIGNATURE|DSN|CERT|_PWD$|(^|_)PAT($|_)", re.I)
SECRET_VALUE = re.compile(
r"://[^/\s@]+@|[?&][^=&]*(token|key|secret|sig|password|auth)[^=&]*=|-----BEGIN|^(sk|pk|rk)[-_]"
r"|^(gh[pousr]_|github_pat_|glpat-|xox[abpsr]-|hf_|npm_[A-Za-z0-9]{20})|^(AKIA|ASIA)[A-Z0-9]{12}|^AIza|^ya29\.|^eyJ[A-Za-z0-9_-]{8,}\.",
re.I,
)
MANAGED_FILE = "60-formtools.conf"
MANAGED_HEADER = "# Variables set from formtools. Other environment.d files are left alone.\n"
USER_KEY = "Environment"
Expand Down Expand Up @@ -44,6 +50,20 @@ def sorted_vars(items: dict[str, str]) -> list[dict]:
return [{"name": name, "value": items[name]} for name in sorted(items, key=lambda key: (key.casefold(), key))]


def secret_like(name: str, value: str) -> bool:
return bool(SECRET_NAME.search(name) or SECRET_VALUE.search(value))


def for_agents(found: dict) -> dict:
return {
**found,
"scopes": [
{**scope, "vars": [{**row, "value": "", "hidden": True} if secret_like(row["name"], row["value"]) else row for row in scope["vars"]]}
for scope in found["scopes"]
],
}


def process_scope() -> dict:
return {
"id": "process",
Expand Down
3 changes: 2 additions & 1 deletion backend/app/tools/model/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@
from fastapi.responses import FileResponse
from pydantic import BaseModel

from app.core.filetypes import INERT_HEADERS
from app.routers.fs import absolute
from app.tools.model import assets, service

router = APIRouter(prefix="/api/model")

CACHE_HEADER = {"Cache-Control": "private, max-age=300"}
ASSET_HEADERS = {"Cache-Control": "private, max-age=300", "X-Content-Type-Options": "nosniff"}
ASSET_HEADERS = {"Cache-Control": "private, max-age=300", **INERT_HEADERS}


class ConvertRequest(BaseModel):
Expand Down
Loading
Loading