Skip to content
Merged
26 changes: 2 additions & 24 deletions backend/app/authoring_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,10 @@
Annotations follow the MCP meaning: readOnlyHint false for anything that changes the site; destructiveHint only where
a call deletes or overwrites what a person may have made (removals, a preset applied over existing values);
idempotentHint where repeating the same call leaves the same result."""
import asyncio
import base64
import binascii
import json
import urllib.error
import urllib.request

from .config import AUTH_TOKEN, PORT
from .engine import EngineError
from .mcp_catalog import REVISION, tool
from .mcp_domains import compact
Expand Down Expand Up @@ -122,25 +118,6 @@ def matches(item):
return result


def _send(locale):
url = f'http://127.0.0.1:{PORT}/api/handoff/formpublisher' + (f'?locale={urllib.request.quote(locale)}' if locale else '')
headers = {'X-FormWeb-Channel': 'agent', 'Content-Type': 'application/json'}
if AUTH_TOKEN:
headers['Authorization'] = 'Bearer ' + AUTH_TOKEN
request = urllib.request.Request(url, data=b'{}', headers=headers, method='POST')
try:
with urllib.request.urlopen(request, timeout=60) as response:
return json.loads(response.read())
except urllib.error.HTTPError as error:
try:
detail = json.loads(error.read()).get('detail', error.reason)
except ValueError:
detail = error.reason
raise EngineError(str(detail), error.code)
except (urllib.error.URLError, OSError) as error:
raise EngineError(f'Could not reach the FormWeb hand-off route: {error}', 502)


async def dispatch(name, arguments):
from . import library, library_routes
from .code_components import build_component
Expand Down Expand Up @@ -213,8 +190,9 @@ async def dispatch(name, arguments):
hosts = [child for page in result.get('pages') or [] for child in site['nodes'].get(roots.get(page, ''), {}).get('children', [])]
return {**made, **(await _bring_in(hosts))}
if name == 'send_to_formpublisher':
from .handoff import send_to_formpublisher
studio.access.authorize('read')
return await asyncio.to_thread(_send, arguments.get('locale'))
return await send_to_formpublisher(arguments.get('locale'))
if name == 'copy_element':
from .fragment_routes import fragment_of
if arguments.get('clip') is True and arguments.get('embed_assets') is not True:
Expand Down
8 changes: 6 additions & 2 deletions backend/app/claude_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@
import json
import os
import secrets
import shutil
from dataclasses import replace
from pathlib import Path

from . import agent_lookup
from . import agent_lookup, windows_start
from .config import DATA_DIR, PORT
from .engine import EngineError

Expand Down Expand Up @@ -76,6 +78,8 @@ def workdir():

def located(kind, fresh=False):
found = agent_lookup.find(kind, setting=None, override_vars=OVERRIDES.get(kind, ()), shell_timeout=10.0, fresh=fresh)
if found.path and not windows_start.startable(found.path):
return replace(found, state='broken', error=windows_start.REFUSED)
return agent_lookup.check(found, child_env(path=found.path), 15.0, fresh)


Expand Down Expand Up @@ -132,7 +136,7 @@ def _base(binary, prompt, resume, headless, config):


def _wrap(argv):
return agent_lookup.start_argv(argv)
return windows_start.start_words(argv, node=lambda: shutil.which('node', path=child_env(path=argv[0]).get('PATH')))


def argv(prompt, resume, config):
Expand Down
20 changes: 16 additions & 4 deletions backend/app/clients.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@
reads one file for the whole account, ~/.gemini/config/mcp_config.json: its card adds the one entry named formweb there
when the person asks, keeps every other entry and key, and leaves alone an entry of that name it did not write. The
Claude Code card's Open button does not depend on its file: it starts Claude through POST /api/terminal/open with
FormWeb's own MCP config.
FormWeb's own MCP config. On Windows the Codex file names formweb.bat in this folder. The installed app ships no
launcher, so there it writes none of these files.
"""
import json
import os
from pathlib import Path

from . import claude_code
from .config import ROOT
from .config import FROZEN, ROOT
from .engine import EngineError

CLIENTS = {
Expand Down Expand Up @@ -40,6 +41,15 @@
}


INSTALLED = 'The installed app does not include the formweb launcher these files start, so nothing was written. Open in Agent Connect starts each program with FormWeb\'s tools.'


def content(client_id, system=None):
if client_id == 'codex' and (system or os.name) == 'nt':
return f'[mcp_servers.formweb]\ncommand = {json.dumps(str(ROOT / "formweb.bat"), ensure_ascii=False)}\nargs = ["mcp"]\nstartup_timeout_sec = 30\ntool_timeout_sec = 120\n'
return CLIENTS[client_id]['content']


ANTIGRAVITY = {'name': 'Antigravity', 'path': '~/.gemini/config/mcp_config.json', 'cli': 'agy', 'start': 'agy'}
ANTIGRAVITY_ENTRY = 'formweb'
OLDER_FILE = '~/.gemini/antigravity-cli/mcp_config.json'
Expand Down Expand Up @@ -94,7 +104,7 @@ def card(client_id):
spec = CLIENTS[client_id]
path = ROOT / spec['path']
current = path.read_text(encoding='utf-8') if path.is_file() else None
status = 'missing' if current is None else 'ready' if current == spec['content'] else 'changed'
status = 'missing' if current is None else 'ready' if current == content(client_id) else 'changed'
found = claude_code.located('claude' if client_id == 'claude-code' else client_id).path is not None
return {'id': client_id, 'name': spec['name'], 'file': spec['path'], 'status': status, 'cliFound': found, 'cli': spec['cli'], 'start': spec['start'], 'launch': '/api/terminal/open' if client_id == 'claude-code' else None}

Expand All @@ -104,6 +114,8 @@ def cards():


def write(client_id):
if FROZEN:
raise EngineError(INSTALLED, 409)
if client_id == 'antigravity':
return antigravity_write()
if client_id not in CLIENTS:
Expand All @@ -113,5 +125,5 @@ def write(client_id):
if not path.is_relative_to(ROOT.resolve()):
raise EngineError('Client file must stay inside the FormWeb folder.', 400)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(spec['content'], encoding='utf-8')
path.write_text(content(client_id), encoding='utf-8')
return card(client_id)
10 changes: 9 additions & 1 deletion backend/app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,15 @@
DATA_DIR = Path(os.getenv('FORMWEB_DATA_DIR', str(ROOT / 'Data' if FROZEN else ROOT / 'backend/data'))).resolve()
FRONTEND_DIST = Path(os.getenv('FORMWEB_FRONTEND_DIST', str(BUNDLE / 'frontend_dist' if FROZEN else ROOT / 'frontend/dist'))).resolve()
AUTH_TOKEN = os.getenv('FORMWEB_AUTH_TOKEN', '')
ORIGINS = tuple(x.strip() for x in os.getenv('FORMWEB_ORIGINS', f'http://localhost:5240,http://127.0.0.1:5240,http://localhost:5241,http://127.0.0.1:5241,http://localhost:{PORT},http://127.0.0.1:{PORT}').split(',') if x.strip())
DEV_PORTS = (5240, 5241)


def default_origins(frozen: bool, port: int) -> tuple[str, ...]:
ports = (port,) if frozen else (*DEV_PORTS, port)
return tuple(f'http://{host}:{item}' for item in ports for host in ('localhost', '127.0.0.1'))


ORIGINS = tuple(x.strip() for x in os.getenv('FORMWEB_ORIGINS', ','.join(default_origins(FROZEN, PORT))).split(',') if x.strip())
PUBLIC_BASE = f'http://127.0.0.1:{PORT}'
CLIP_SECONDS_DEFAULT = 15 * 60

Expand Down
6 changes: 5 additions & 1 deletion backend/app/mcp_domains.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,12 +113,16 @@
}


def removing(command) -> bool:
return str(command).endswith(('.remove', '.delete')) or command == 'site.replace'


def domain_tools():
tools = []
for name, title, intro, commands in DOMAINS:
lines = '\n'.join(f'- {command} {COMMAND_DOCS[command]}' for command in commands)
description = f'{intro} One command per call, applied as one undo step.\n{lines}'
removes = any(command.endswith('.remove') or command == 'site.replace' for command in commands)
removes = any(removing(command) for command in commands)
tools.append({
'name': name,
'title': title,
Expand Down
6 changes: 3 additions & 3 deletions backend/app/mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from .config import ORIGINS, PORT, VERSION
from .engine import EngineError
from .mcp_catalog import TOOLS as BASE_TOOLS
from .mcp_domains import COMMAND_DOCS, DOMAIN_BY_NAME, DOMAIN_TOOLS, INSTRUCTIONS, PROMPTS, compact, tokens, tree
from .mcp_domains import COMMAND_DOCS, DOMAIN_BY_NAME, DOMAIN_TOOLS, INSTRUCTIONS, PROMPTS, compact, removing, tokens, tree
from .providers.catalog import PROVIDER_BY_NAME, PROVIDER_TOOLS
from .providers.service import dispatch_tool as provider_dispatch
from .service import studio
Expand Down Expand Up @@ -75,9 +75,9 @@ async def call_tool(context, params):
errors = list(Draft202012Validator(BY_NAME[params.name]['inputSchema']).iter_errors(arguments))
if errors:
raise EngineError(errors[0].message[:400], 422)
removes = params.name == 'apply_commands' and any(str(item.get('command', '')).endswith(('.remove', '.delete')) for item in arguments.get('commands', []) if isinstance(item, dict))
removes = params.name == 'apply_commands' and any(removing(item.get('command', '')) for item in arguments.get('commands', []) if isinstance(item, dict))
if params.name in DOMAIN_BY_NAME: # domain tools: judge the one command, not the tool's worst case
removes = arguments['command'].endswith('.remove') or arguments['command'] == 'site.replace'
removes = removing(arguments['command'])
if params.name == 'motion_track': # judged per call like the domain tools: only a null track deletes
removes = arguments['track'] is None
if params.name == 'library_import_site': # only an import that replaces matching routes swaps content away
Expand Down
103 changes: 103 additions & 0 deletions backend/app/windows_start.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
"""How FormWeb starts an agent program on Windows. A program installed by npm is a .cmd file that only starts node with
its script, so FormWeb starts node with that script itself and no command interpreter reads the words. Any other .cmd or
.bat is run by cmd.exe, which reads the whole line again and treats some characters as its own syntax even inside quotes.
Such a start is refused when any word holds a control character or one of & | < > ^ ( ) ! % ", and when a program path
that needs quotes is followed by a word that needs quotes, so every word reaches the program as it was given."""
import re
import shutil
from pathlib import Path

from . import agent_lookup
from .engine import EngineError

BATCH = ('.cmd', '.bat')
CONTROL = re.compile(r'[\x00-\x1f\x7f]')
RESERVED = frozenset('&|<>^()!%"')
SHIM = re.compile(r'("%_prog%"\s+)?"%dp0%\\([^"%\r\n]+)"\s+%\*')
PROG = re.compile(r'SET\s+"_prog=%dp0%\\([^"%\r\n]+)"', re.IGNORECASE)
NATIVE = ('.exe', '.com')
STREAM = re.compile(r'(::\$data)?[ .]*$', re.IGNORECASE)
REFUSED = ('This program is started through cmd.exe on Windows, which reads some characters as its own syntax even inside quotes, '
'so it was not started. A word given to it may not hold line breaks or other control characters, or any of '
'& | < > ^ ( ) ! % ", and a program path with spaces or @ may not be followed by a word with spaces. Pass long text '
'through standard input or a file if the program supports it, or give the path to a program that is not a .cmd or .bat file.')


def _node(folder: Path, node) -> str | None:
beside = folder / 'node.exe'
if beside.is_file():
return str(beside)
found = node() if node else shutil.which('node')
return found if found and _suffix(found) in NATIVE else None


def _suffix(path) -> str:
return Path(STREAM.sub('', str(path))).suffix.lower()


def shim_target(path, node=None) -> list[str] | None:
"""What an npm .cmd shim starts, when its target is inside the shim's folder: [node, script] for a node script,
[program] for a native program, else None. Node is used only as node.exe, never through another batch file."""
shim = Path(path)
if _suffix(shim) != '.cmd':
return None
try:
text = shim.read_text(encoding='utf-8', errors='replace')[:16384]
except OSError:
return None
hit = SHIM.search(text)
parts = [part for part in re.split(r'[\\/]', hit.group(2)) if part] if hit else []
if not parts or any(part in ('.', '..') or ':' in part for part in parts):
return None
script = shim.parent.joinpath(*parts)
if not script.is_file():
return None
if not hit.group(1):
return [str(script)] if _suffix(script) in NATIVE else None
prog = PROG.search(text)
if not prog or prog.group(1).lower() != 'node.exe':
return None
program = _node(shim.parent, node)
return [program, str(script)] if program else None


def _plain(word: str) -> bool:
return not CONTROL.search(word) and not RESERVED.intersection(word)


def _needs_quotes(word: str) -> bool:
return word == '' or ' ' in word


def cmd_safe(words) -> bool:
"""Whether cmd.exe /c would pass every word to the batch file unchanged. No word may hold a control character or a
reserved character, quoted or not. A quoted program path keeps its quotes only when it is the line's one quoted
word and holds no @, so a path that needs quotes may not be followed by another word that needs them."""
words = [str(word) for word in words]
if not words or not all(_plain(word) for word in words):
return False
program, rest = words[0], words[1:]
if _needs_quotes(program):
return '@' not in program and not any(_needs_quotes(word) for word in rest)
return True


def _batch(words, platform) -> bool:
return agent_lookup.windows(platform) and _suffix(words[0]) in BATCH


def start_words(cmd, platform=None, node=None) -> list[str]:
words = [str(word) for word in cmd]
if not _batch(words, platform):
return agent_lookup.start_argv(words, platform=platform)
direct = shim_target(words[0], node)
if direct:
return [*direct, *words[1:]]
if not cmd_safe(words):
raise EngineError(REFUSED, 400)
return agent_lookup.start_argv(words, platform=platform)


def startable(path, platform=None) -> bool:
"""Whether the finder's own check (path --version) can run this program safely."""
return not _batch([path], platform) or cmd_safe([path, '--version'])
60 changes: 60 additions & 0 deletions backend/tests/test_agent_asks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import pytest

from test_f2_f3_mcp import agents_on, call, payload # noqa: F401


@pytest.fixture()
def agents_asking(client):
assert client.post("/api/agents", json={"enabled": True}).status_code == 200
previous = client.post("/api/approvals/settings", json={}).json()["agentDestructive"]
client.post("/api/approvals/settings", json={"agentDestructive": True})
yield
client.post("/api/approvals/settings", json={"agentDestructive": previous})
client.post("/api/agents", json={"enabled": False})


@pytest.fixture()
def asked(monkeypatch):
from app.engine import EngineError
from app.service import studio

seen = []

async def refuse(kind, subject, *args, **kwargs):
seen.append(subject["tool"])
raise EngineError("Declined.", 403)

monkeypatch.setattr(studio.approvals, "wait", refuse)
return seen


def test_replacing_the_whole_site_through_apply_commands_asks_first_like_edit_site(client, agents_asking, asked):
state = client.get("/api/state").json()
before = state["site"]
replacement = {**before, "name": "Replaced by a batch"}
result = call(client, "apply_commands", {"commands": [{"command": "site.replace", "params": {"site": replacement}}]})
assert result.get("isError") and asked == ["apply_commands"]
assert client.get("/api/state").json()["site"]["name"] == before["name"]
result = call(client, "edit_site", {"command": "site.replace", "params": {"site": replacement}})
assert result.get("isError") and asked == ["apply_commands", "edit_site"]


def test_an_ordinary_batch_does_not_ask(client, agents_asking, asked):
result = call(client, "apply_commands", {"commands": [{"command": "token.set", "params": {"name": "asks-none", "value": "#123456"}}]})
assert not result.get("isError") and asked == []


def test_the_formpublisher_tool_delivers_without_the_window_key(client, agents_on, monkeypatch):
from app import handoff

sent = []

def receive(url, data, headers):
sent.append(headers["Content-Type"])
return {"site": "site-1", "revision": "rev-1"}

monkeypatch.setattr(handoff, "_post", receive)
result = call(client, "send_to_formpublisher", {})
assert not result.get("isError"), result
assert payload(result)["delivered"] == "live" and payload(result)["site"] == "site-1"
assert sent == ["application/zip"]
Loading
Loading