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
4 changes: 2 additions & 2 deletions .agents/skills/formext-harness/references/tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ Check, then build the deterministic .formpkg (sorted entries, fixed timestamps),
| --- | --- | --- | --- |
| `id` | string | yes | The project id (projects lists them). |
| `reproduce` | boolean | no | Also run the reproducibility check. |
| `out` | string | no | Save the .formpkg to this file or folder. |
| `out` | string | no | Save the .formpkg to this folder, or to this file name ending in .formpkg. |
| `anyway` | boolean | no | Package despite code errors (never despite contract errors). Say so to the person. |

## builds
Expand Down Expand Up @@ -349,6 +349,6 @@ Write the project into a folder in form.ext-registry's layout (extensions/[id]/
| Argument | Type | Required | Meaning |
| --- | --- | --- | --- |
| `id` | string | yes | The project id (projects lists them). |
| `checkout` | string | no | Your own clone of nodemode-dev/form.ext-registry to use instead of form.ext's copy (saved as the setting registry.checkout). |
| `checkout` | string | no | Your own clone of nodemode-dev/form.ext-registry to use for this submit instead of form.ext's copy (to keep one for every submit, set registry.checkout in the form.ext window's Settings). |
| `pull_request` | boolean | no | Also fork, push and open the pull request. Ask the person first: it posts publicly under their GitHub account. |
| `ready` | boolean | no | Only report whether git and gh are installed and signed in. |
4 changes: 2 additions & 2 deletions .claude/skills/formext-harness/references/tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ Check, then build the deterministic .formpkg (sorted entries, fixed timestamps),
| --- | --- | --- | --- |
| `id` | string | yes | The project id (projects lists them). |
| `reproduce` | boolean | no | Also run the reproducibility check. |
| `out` | string | no | Save the .formpkg to this file or folder. |
| `out` | string | no | Save the .formpkg to this folder, or to this file name ending in .formpkg. |
| `anyway` | boolean | no | Package despite code errors (never despite contract errors). Say so to the person. |

## builds
Expand Down Expand Up @@ -349,6 +349,6 @@ Write the project into a folder in form.ext-registry's layout (extensions/[id]/
| Argument | Type | Required | Meaning |
| --- | --- | --- | --- |
| `id` | string | yes | The project id (projects lists them). |
| `checkout` | string | no | Your own clone of nodemode-dev/form.ext-registry to use instead of form.ext's copy (saved as the setting registry.checkout). |
| `checkout` | string | no | Your own clone of nodemode-dev/form.ext-registry to use for this submit instead of form.ext's copy (to keep one for every submit, set registry.checkout in the form.ext window's Settings). |
| `pull_request` | boolean | no | Also fork, push and open the pull request. Ask the person first: it posts publicly under their GitHub account. |
| `ready` | boolean | no | Only report whether git and gh are installed and signed in. |
10 changes: 10 additions & 0 deletions backend/HASHOUT_LOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,16 @@

The living log of the form.ext engine. Read it before editing `backend/`. Core files belong to the engine module; module routers and services (`routers/<module>.py`, `services/<module>.py`) keep their own notes in their own HASHOUT logs.

## Unreleased: loopback requests, window-only checkout, plain launcher words {#loopback}

- refers-to: app/services/local_host.py; app/services/agent_start.py; app/services/settings.py; app/services/consent.py; app/cli.py; ../setup/agents.py
- `LoopbackHostGuard` (outermost middleware) refuses any HTTP request or WebSocket whose Host is not localhost, 127.0.0.1, ::1 or tauri.localhost; in-process calls pass. `/api/live` checks Origin and Host with the same `origin_ok` the terminal routes use. Test clients use `http://127.0.0.1:8640`, and WebSocket tests give the full `ws://127.0.0.1:8640/...` address because the test client ignores its base address for sockets.
- `registry.checkout` changes only with the window key, like `agent_access`. The `submit` tool's `checkout` goes in the body of `POST /api/publish/{pid}/registry` (and `/registry/pull-request`) and is used for that submit only.
- The consent request's `what` names the local path argument (`LOCAL_PATHS`), made absolute before the check. At most `MAX_WAITING` (8) requests wait at once. `run_op` asks `forwards()` once. `package` writes only to a folder or a `.formpkg` name, through a temporary file.
- `agent_lookup.py` stays the shared 1.0.1 copy. `agent_start.start_argv` wraps it: on Windows an npm `.cmd` launcher is followed to its script (with the `node.exe` beside it or `node` on PATH) or its `.exe`; any other `.cmd` or `.bat` goes through `cmd.exe /c` only when every word is plain. On Windows the MCP launcher is `formext.bat`.
- The consent `what` shows the resolved path, keeps a trailing separator, and writes control, format and line separator characters as `\uXXXX`. `package` writes its temporary file with `tempfile.mkstemp`. `POST /api/window/key` checks Origin and Host with `origin_ok`. Words given to `cmd.exe /c` may not hold any of `& | < > ^ ( ) !` even inside spaces, since `cmd /c` can strip the outer quotes. The refusal (`agent_start.RefusedWord`) says to pass long or special text through stdin or a file when the program accepts one.
- Not run: anything on Windows.

## v0.11.0: one runner for the tests, by layer {#test-runner}

- refers-to: ../setup/test; ../formext; ../formext.bat; ../tests/stand_ins.py; ../docs/TESTING.md; ../.github/workflows/ci.yml
Expand Down
40 changes: 28 additions & 12 deletions backend/app/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import re
import shutil
import sys
import tempfile
import threading
import time
import urllib.error
Expand Down Expand Up @@ -677,8 +678,17 @@ def op_package(eng: Engine, id: str, reproduce: bool = False, out: str | None =
if target.is_dir() or out.endswith(("/", os.sep)):
target.mkdir(parents=True, exist_ok=True)
target = target / (build.get("file") or f"{build['id']}-{build['version']}.formpkg")
if target.suffix.lower() != ".formpkg":
raise OpError(f"out must be a folder or a file name ending in .formpkg, not {target}")
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
handle, part = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".part", dir=target.parent)
try:
with os.fdopen(handle, "wb") as fh:
fh.write(data)
os.replace(part, target)
except BaseException:
Path(part).unlink(missing_ok=True)
raise
result["saved"] = str(target.resolve())
return result

Expand Down Expand Up @@ -804,20 +814,21 @@ def op_submit(eng: Engine, id: str, checkout: str | None = None, pull_request: b
_need(eng, "publish", "Submit to Registry", route)
if ready:
return eng.get(f"/api/publish/{q(id)}/registry/pull-request")
body = {}
if checkout:
folder = Path(checkout).expanduser().resolve()
if not (folder / "tools" / "check.py").is_file():
raise OpError(f"{folder} is not a form.ext-registry checkout (it has no tools/check.py)")
eng.call("PUT", "/api/settings", {"registry": {"checkout": str(folder)}})
body = {"checkout": str(folder)}
if pull_request:
try:
return eng.call("POST", f"/api/publish/{q(id)}/registry/pull-request", {})
return eng.call("POST", f"/api/publish/{q(id)}/registry/pull-request", body)
except EngineError as err:
needs = err.data.get("needs") if isinstance(err.data, dict) else None
if needs:
raise OpError(err.message, {"needs": needs}) from err
raise
return eng.call(route[0], route[1], {})
return eng.call(route[0], route[1], body)


def _sources(eng: Engine) -> None:
Expand Down Expand Up @@ -1096,7 +1107,7 @@ def op_agents_sync(eng: Engine) -> dict:
Op("package", "Package", "Check, then build the deterministic .formpkg (sorted entries, fixed timestamps), with SHA-256 and size. Refused on contract errors (every host would refuse the package) and, unless anyway, on code errors. reproduce also rebuilds it with the kit's own formpkg command and compares the SHA-256; out saves a copy.", op_package, [
P_ID,
Param("reproduce", "boolean", "Also run the reproducibility check."),
Param("out", help="Save the .formpkg to this file or folder."),
Param("out", help="Save the .formpkg to this folder, or to this file name ending in .formpkg."),
Param("anyway", "boolean", "Package despite code errors (never despite contract errors). Say so to the person."),
], read_only=False, say=_say_package),
Op("builds", "Builds", "Every build of a project, newest first, with SHA-256, size and signatures.", op_builds, [P_ID], say=lambda d: "\n".join(f"{b['sha256'][:16]} {b.get('version')} {b.get('bytes')} bytes {len(b.get('signatures') or [])} signatures" for b in d["builds"]) or "no builds yet"),
Expand Down Expand Up @@ -1127,7 +1138,7 @@ def op_agents_sync(eng: Engine) -> dict:
], read_only=False, asks=True, say=_say_publish),
Op("submit", "Submit to Registry", "Write the project into a folder in form.ext-registry's layout (extensions/[id]/ with package/, the source, package.json when there is one, README.md, LICENSE, CHANGELOG.md and a screenshot slot), and run the registry's own tools/check.py on it from the copy of the registry form.ext keeps (it fetches it; when that fails form.ext's own Check runs, and it says which ran). With pull_request it then forks nodemode-dev/form.ext-registry into the person's GitHub account, pushes the folder on a branch and opens the pull request, through GitHub's gh command line; it refuses while the checks fail or a placeholder text is left. ready reports what the one-step pull request still needs on this computer. Without pull_request it pushes nothing and gives the commands to do it by hand.", op_submit, [
P_ID,
Param("checkout", help="Your own clone of nodemode-dev/form.ext-registry to use instead of form.ext's copy (saved as the setting registry.checkout)."),
Param("checkout", help="Your own clone of nodemode-dev/form.ext-registry to use for this submit instead of form.ext's copy (to keep one for every submit, set registry.checkout in the form.ext window's Settings)."),
Param("pull_request", "boolean", "Also fork, push and open the pull request. Ask the person first: it posts publicly under their GitHub account.", flag="--pull-request"),
Param("ready", "boolean", "Only report whether git and gh are installed and signed in."),
], read_only=False, asks=True, say=_say_submit),
Expand Down Expand Up @@ -1156,16 +1167,21 @@ def run_op(eng: Engine, name: str, args: dict) -> Any:
for p in op.params:
if p.enum and p.name in clean and clean[p.name] not in p.enum:
raise OpError(f"{p.name} is one of {', '.join(p.enum)}")
if op.mcp and not op.read_only and not eng.forwards():
local = LOCAL_PATHS.get(name)
named = None
if local and isinstance(clean.get(local), str) and clean[local]:
given = clean[local]
folder = os.sep if given.endswith(("/", os.sep)) else ""
clean[local] = str(Path(given).expanduser().absolute()) + folder
named = {local: str(Path(clean[local]).resolve()) + folder}
forwards = op.mcp and eng.forwards()
if op.mcp and not op.read_only and not forwards:
from app.services import consent

refused = consent.check(name, op.title, clean)
refused = consent.check(name, op.title, clean, named)
if refused:
raise OpError(refused, {"agentAccess": consent.access()})
if op.mcp and eng.forwards():
local = LOCAL_PATHS.get(name)
if local and isinstance(clean.get(local), str) and clean[local]:
clean[local] = str(Path(clean[local]).expanduser().absolute())
if forwards:
return eng.tool(name, clean)
return op.run(eng, **clean)

Expand Down
2 changes: 2 additions & 0 deletions backend/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from app import __version__, routers
from app.services import consent, paths
from app.services.bus import bus
from app.services.local_host import LoopbackHostGuard
from app.services.window_key import WindowKeyGuard
from app.services.workspace import WorkspaceError, watcher

Expand Down Expand Up @@ -51,6 +52,7 @@ async def lifespan(app: FastAPI):
allow_methods=["*"],
allow_headers=["*"],
)
app.add_middleware(LoopbackHostGuard)


@app.exception_handler(WorkspaceError)
Expand Down
4 changes: 2 additions & 2 deletions backend/app/routers/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ def _window(request: Request) -> None:


@router.get("/requests")
def list_requests(request: Request) -> dict:
async def list_requests(request: Request) -> dict:
_window(request)
return {"access": consent.access(), "requests": consent.pending(), "sealReset": bool(settings.get().get("agentAccessReset"))}


@router.post("/requests/{request_id}")
def answer_request(request: Request, request_id: str, body: dict = Body(...)) -> dict:
async def answer_request(request: Request, request_id: str, body: dict = Body(...)) -> dict:
_window(request)
if not consent.answer(request_id, str(body.get("answer") or "")):
raise HTTPException(404, "That request was already answered or has expired")
Expand Down
2 changes: 1 addition & 1 deletion backend/app/routers/health.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@


@router.get("/api/health")
def health(request: Request):
async def health(request: Request):
state = request.app.state
return {
"ok": True,
Expand Down
4 changes: 4 additions & 0 deletions backend/app/routers/live.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from fastapi import APIRouter, WebSocket, WebSocketDisconnect

from app import __version__
from app.services.local_host import origin_ok
from app.services import consent, window_key
from app.services.bus import bus

Expand All @@ -13,6 +14,9 @@

@router.websocket("/api/live")
async def live(ws: WebSocket):
if not origin_ok(ws.headers.get("origin"), ws.headers.get("host")):
await ws.close(code=4403)
return
await ws.accept()
bus.attach(asyncio.get_running_loop())
queue = bus.subscribe()
Expand Down
15 changes: 11 additions & 4 deletions backend/app/routers/publish.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,16 @@ def send(pid: str):
return publish.send(pid)


def _checkout(body: dict | None) -> str | None:
chosen = (body or {}).get("checkout")
if chosen is not None and not isinstance(chosen, str):
raise ValueError("checkout is the path of a form.ext-registry checkout")
return chosen or None


@router.post("/{pid}/registry")
def submit(pid: str):
return publish.submit(pid)
def submit(pid: str, body: dict | None = Body(None)):
return publish.submit(pid, _checkout(body))


@router.get("/{pid}/registry/pull-request")
Expand All @@ -33,9 +40,9 @@ def pull_request_ready(pid: str):


@router.post("/{pid}/registry/pull-request")
def pull_request(pid: str):
def pull_request(pid: str, body: dict | None = Body(None)):
try:
return registry_pr.open_pull_request(pid)
return registry_pr.open_pull_request(pid, _checkout(body))
except registry_pr.Needs as exc:
return JSONResponse({"detail": exc.message, "needs": exc.needs}, status_code=exc.status)

Expand Down
16 changes: 1 addition & 15 deletions backend/app/routers/terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,30 +7,16 @@
import json
import os
from typing import Literal
from urllib.parse import urlparse

from fastapi import APIRouter, Depends, HTTPException, Request, WebSocket, WebSocketDisconnect
from pydantic import BaseModel, Field

from app.services import agent_programs, claude_code, terminal, window_key
from app.services.local_host import origin_ok

LOOPBACK = {"localhost", "127.0.0.1", "::1", "tauri.localhost"}
MAX_SOCKETS = 24


def _loopback(netloc: str | None) -> bool:
return bool(netloc) and (urlparse(f"//{netloc}").hostname or "") in LOOPBACK


def origin_ok(origin: str | None, host: str | None) -> bool:
if not _loopback(host):
return False
if not origin:
return True
parsed = urlparse(origin)
return parsed.scheme in ("http", "https", "tauri") and (parsed.hostname or "") in LOOPBACK


def require_local(request: Request) -> None:
if not origin_ok(request.headers.get("origin"), request.headers.get("host")):
raise HTTPException(status_code=403, detail="Only the form.ext window on this computer may use the terminals.")
Expand Down
7 changes: 5 additions & 2 deletions backend/app/routers/window.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
from fastapi import APIRouter, HTTPException
from fastapi import APIRouter, HTTPException, Request

from app.services import window_key
from app.services.local_host import origin_ok

router = APIRouter(prefix="/api/window", tags=["window"])


@router.post("/key")
def claim_window_key() -> dict:
def claim_window_key(request: Request) -> dict:
if window_key.stdout_mode():
raise HTTPException(404, "Not Found")
if not origin_ok(request.headers.get("origin"), request.headers.get("host")):
raise HTTPException(403, "Only the form.ext window on this computer may claim the window key")
key = window_key.claim()
if key is None:
raise HTTPException(409, "Another window already holds this engine's window key; use that window, or restart form.ext")
Expand Down
4 changes: 2 additions & 2 deletions backend/app/services/agent_programs.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import time
from pathlib import Path

from app.services import agent_lookup, claude_code, consent, paths, terminal
from app.services import agent_lookup, agent_start, claude_code, consent, paths, terminal

TOKEN_VAR = "FORMEXT_INAPP_TOKEN"
PROGRAMS = {
Expand Down Expand Up @@ -99,7 +99,7 @@ def open_terminal(kind: str, port: int, cols: int = 100, rows: int = 30, project
path = found.path
own = tab_folder(kind) if kind == "antigravity" else None
folder = str(own) if own else claude_code.project_folder(project)
argv = agent_lookup.start_argv([path])
argv = agent_start.start_argv([path])
token = secrets.token_urlsafe(32)
env = claude_code.terminal_env(port, path, {TOKEN_VAR: token, "FORMEXT_MCP_URL": terminal.engine_url(port) + "/mcp"})
consent.open_tab(token, "")
Expand Down
62 changes: 62 additions & 0 deletions backend/app/services/agent_start.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""How form.ext starts an agent program. On Windows a .cmd or .bat launcher would go through the command interpreter, which reads
its own special characters in the words, so an npm launcher is followed to the node script or program it runs and that is started
directly; any other launcher is started through the interpreter only when every word is plain."""

from __future__ import annotations

import os
import re
import shutil
import subprocess
from pathlib import Path

from app.services import agent_lookup

SHIM_TARGET = re.compile(r'"%dp0%\\([^"%]+)"\s+%\*')
CONTROL = re.compile(r"[\x00-\x1f\x7f]")
SPECIAL = set('&|<>^()!')


class RefusedWord(OSError):
pass


def _shim(path: str, env: dict) -> list[str] | None:
try:
text = Path(path).read_text(encoding="utf-8", errors="replace")
except OSError:
return None
found = SHIM_TARGET.findall(text)
if not found:
return None
folder = Path(path).parent
target = folder / found[-1].replace("\\", os.sep)
if not target.is_file():
return None
if target.suffix.lower() == ".exe":
return [str(target)]
beside = folder / "node.exe"
node = str(beside) if beside.is_file() else shutil.which("node", path=env.get("PATH"))
return [node, str(target)] if node else None


def plain(word: str) -> bool:
return not (CONTROL.search(word) or "%" in word or '"' in word or SPECIAL & set(word))


def start_argv(cmd: list, env: dict | None = None, platform: str | None = None) -> list[str]:
words = [str(c) for c in cmd]
env = os.environ if env is None else env
if not (agent_lookup.windows(platform) and words and words[0].lower().endswith((".cmd", ".bat"))):
return agent_lookup.start_argv(words, env, platform)
direct = _shim(words[0], env)
if direct:
return [*direct, *words[1:]]
bad = next((w for w in words if not plain(w)), None)
if bad is not None:
raise RefusedWord(f"{Path(words[0]).name} is a command script, and one of its words cannot be passed to it safely (a control character, %, a double quote, or one of & | < > ^ ( ) !). Pass long or special text through stdin or a file if the program accepts one.")
return agent_lookup.start_argv(words, env, platform)


def run(cmd: list, env: dict, timeout: float = 15.0, platform: str | None = None) -> subprocess.CompletedProcess:
return subprocess.run(start_argv(cmd, env, platform), capture_output=True, text=True, errors="replace", timeout=timeout, env=env, stdin=subprocess.DEVNULL)
Loading
Loading