Files
ai-agent/sidecar/askform.py

430 lines
18 KiB
Python

"""
/ask-form: this machine's forms from the standalone `ask-form` tool
(github.com/GabrielVidal1/ask-form), proxied for the hub.
`ask-form serve` runs once per machine and keeps the forms an agent created
here (`ask-form create`), answered by the user on its own pages
(https://ask-form.xyz/f/<id>). Its admin API listens on loopback only, behind
an admin secret the CLI reads from ~/.config/ask-form/admin-token — so the hub
(a container, or a hub across the tailnet) can't reach it. This router is the
hub's way in: a thin, read-mostly proxy under the hub's bearer.
GET /ask-form/health is ask-form installed here? version, relay, open forms
GET /ask-form/forms[?status=] every form (no field specs; answers once submitted)
GET /ask-form/forms/{id}[?fields=1] one form, with its field spec on request
POST /ask-form/forms/{id}/revoke withdraw an open form
POST /ask-form/forms/{id}/close a multi form stops taking answers
POST /ask-form/embed {origins}: let the hub frame this machine's forms
(wire_embed — its serve.env, then a restart)
POST /ask-form/events `ask-form serve`'s events webhook (this machine only —
loopback or the sidecar's bind address; no bearer):
queued in the outbox for the hub to pull
The form's link (its token) is only ever printed by `ask-form create`; the
admin API never returns it, and neither does this proxy. The hub learns it
from the events webhook, or reads it off the create call in the transcript.
Nothing here runs a shell: every call is one HTTP request to the admin API,
with the id checked against ask-form's own id shape.
A guest's computer (a link worker) runs an ask-form its owner installed by
hand, with no idea the hub exists: ``wire_events`` points its events at this
sidecar (see below), so the link of every form it creates reaches the hub.
"""
from __future__ import annotations
import json
import logging
import os
import pathlib
import re
import subprocess
import threading
import time
import urllib.error
import urllib.request
from typing import Callable
from fastapi import APIRouter, Header, HTTPException, Query, Request
# `<kebab-name>_<6 chars>` — ask-form's ids (internal/store: ValidID).
ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,60}_[a-z0-9]{6}$")
log = logging.getLogger("askform")
DEFAULT_ADMIN_URL = "http://127.0.0.1:7461"
# The launchd label / systemd unit `ask-form setup` installs (cmd/ask-form/setup.go).
LAUNCHD_LABEL = "xyz.gabvdl.ask-form"
SYSTEMD_UNIT = "ask-form.service"
WIRE_EVERY_S = 300
# What `ask-form serve` posts (internal/server/events.go): one of these per
# status change, plus `created`.
EVENTS = ("created", "submitted", "answered", "declined", "revoked", "expired",
"closed")
def config_dir() -> pathlib.Path:
"""Where the CLI keeps its secrets — the same rules as the Go `configDir`."""
if d := os.environ.get("ASK_FORM_CONFIG"):
return pathlib.Path(d)
if d := os.environ.get("XDG_CONFIG_HOME"):
return pathlib.Path(d) / "ask-form"
return pathlib.Path.home() / ".config" / "ask-form"
def admin_token() -> str:
"""The admin secret, as the CLI resolves it: ASK_FORM_ADMIN_TOKEN, else
<config>/admin-token (written by `serve`). "" when ask-form isn't set up."""
if t := os.environ.get("ASK_FORM_ADMIN_TOKEN"):
return t.strip()
try:
return (config_dir() / "admin-token").read_text().strip()
except OSError:
return ""
def admin_url() -> str:
return os.environ.get("ASK_FORM_ADMIN_URL", DEFAULT_ADMIN_URL).rstrip("/")
def installed() -> bool:
return bool(admin_token())
def call(method: str, path: str, body: dict | None = None, *,
timeout: float = 10, token: str | None = None,
base: str | None = None) -> tuple[int, dict]:
"""One admin-API call → (status, json). 503 (as HTTPException) when
ask-form isn't set up here or its server is down — the hub shows that,
the viewer never sees a half-rendered card."""
tok = token if token is not None else admin_token()
if not tok:
raise HTTPException(503, {"message": "ask-form is not set up on this machine "
"(no admin token — run `ask-form setup`)",
"kind": "askform_missing"})
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(
f"{base or admin_url()}{path}", data=data, method=method,
headers={"Authorization": f"Bearer {tok}",
"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.status, json.loads(r.read().decode() or "{}")
except urllib.error.HTTPError as e:
try:
out = json.loads(e.read().decode() or "{}")
except ValueError:
out = {}
return e.code, out if isinstance(out, dict) else {}
except (urllib.error.URLError, OSError, ValueError) as e:
raise HTTPException(503, {"message": f"ask-form server unreachable at "
f"{base or admin_url()} ({e}) — is "
"`ask-form serve` running?",
"kind": "askform_down"})
def _passthrough(code: int, out: dict) -> dict:
"""An admin-API error becomes the same status here, with its message."""
if code >= 400:
raise HTTPException(code, {"message": out.get("error") or f"ask-form: HTTP {code}",
"kind": "askform"})
return out
def _valid_id(fid: str) -> str:
if not ID_RE.match(fid or ""):
raise HTTPException(400, {"message": f"not an ask-form id: {fid!r}",
"kind": "askform"})
return fid
def health() -> dict:
"""Never raises: ``{installed: false}`` when there's nothing here."""
if not installed():
return {"installed": False, "ok": False}
try:
code, out = call("GET", "/v1/health", timeout=4)
except HTTPException as e:
return {"installed": True, "ok": False,
"error": e.detail.get("message") if isinstance(e.detail, dict) else str(e.detail)}
if code >= 400:
return {"installed": True, "ok": False, "error": out.get("error") or f"HTTP {code}"}
return {"installed": True, **out}
def is_local(request: Request) -> bool:
"""From this machine: loopback, or the address this sidecar binds (a
worker listens on its Tailscale address, and its own `ask-form serve`
reaches it there)."""
host = request.client.host if request.client else ""
bind = os.environ.get("SIDECAR_BIND", "").strip()
return host in ("127.0.0.1", "::1", "localhost") or (bool(bind) and host == bind)
def make_router(hub_auth: Callable[[str | None], None],
queue_event: Callable[[dict], dict] | None = None) -> APIRouter:
"""``hub_auth`` is the hub's bearer check; ``queue_event`` takes a webhook
event and queues it for the hub (the outbox) — None: events are refused."""
router = APIRouter()
@router.get("/ask-form/health")
def get_health(authorization: str | None = Header(default=None)) -> dict:
hub_auth(authorization)
return health()
@router.post("/ask-form/forms")
def create_form(body: dict, authorization: str | None = Header(default=None)) -> dict:
"""Create a form on this machine's ``ask-form serve`` (hub-managed
plugins like approvals, new-project and plans)."""
hub_auth(authorization)
if not isinstance(body, dict):
raise HTTPException(400, {"message": "JSON object required", "kind": "askform"})
return _passthrough(*call("POST", "/v1/forms", body))
@router.get("/ask-form/forms")
def list_forms(status: str = Query(""),
authorization: str | None = Header(default=None)) -> dict:
hub_auth(authorization)
qs = f"?status={status}" if status else ""
return _passthrough(*call("GET", f"/v1/forms{qs}"))
@router.get("/ask-form/forms/{fid}")
def get_form(fid: str, fields: int = Query(0),
authorization: str | None = Header(default=None)) -> dict:
hub_auth(authorization)
qs = "?fields=1" if fields else ""
return _passthrough(*call("GET", f"/v1/forms/{_valid_id(fid)}{qs}"))
@router.post("/ask-form/forms/{fid}/revoke")
def revoke(fid: str, authorization: str | None = Header(default=None)) -> dict:
hub_auth(authorization)
code, out = call("POST", f"/v1/forms/{_valid_id(fid)}/revoke", {})
# 409 = already closed: the form as it is, not an error for the hub.
return out if code == 409 else _passthrough(code, out)
@router.post("/ask-form/forms/{fid}/close")
def close(fid: str, authorization: str | None = Header(default=None)) -> dict:
hub_auth(authorization)
code, out = call("POST", f"/v1/forms/{_valid_id(fid)}/close", {})
return out if code == 409 else _passthrough(code, out)
@router.post("/ask-form/embed")
def embed(body: dict, authorization: str | None = Header(default=None)) -> dict:
"""Let the hub show this machine's forms in its own frame: its
origins go into ask-form's ``ASK_FORM_EMBED_ORIGINS`` (wire_embed)."""
hub_auth(authorization)
origins = body.get("origins") if isinstance(body, dict) else None
if not isinstance(origins, list) or not origins or not all(
isinstance(o, str) and _ORIGIN_RE.match(o) for o in origins):
raise HTTPException(400, "want {origins: [https://host, …]}")
return {"state": wire_embed(origins)}
@router.post("/ask-form/events")
async def events(request: Request) -> dict:
"""`ask-form serve`'s webhook (ASK_FORM_EVENTS_URL on a worker points
here). Loopback only and no bearer: the same trust as the admin API
it mirrors — anything on this machine could run `ask-form` anyway."""
if not is_local(request):
raise HTTPException(403, "this machine only")
if queue_event is None:
raise HTTPException(501, "no outbox here")
try:
body = json.loads((await request.body()).decode() or "{}")
except ValueError:
raise HTTPException(400, "bad JSON")
ev = str(body.get("event") or "")
form = body.get("form")
if ev not in EVENTS or not isinstance(form, dict) or not ID_RE.match(str(form.get("id") or "")):
raise HTTPException(400, "want {event, form: {id, …}}")
return queue_event({"event": ev, "form": form})
return router
# ── wiring a guest's ask-form to this sidecar ────────────────────────────────
_EVENTS_RE = re.compile(r"^\s*(?:export\s+)?ASK_FORM_EVENTS_URL\s*=\s*(.*?)\s*$")
def events_url() -> str:
"""Where this machine's `ask-form serve` should post its events: this
sidecar, on the address it listens on (loopback in link mode)."""
port = os.environ.get("SIDECAR_PORT", "8790")
return f"http://127.0.0.1:{port}/ask-form/events"
def _serve_env() -> pathlib.Path:
return config_dir() / "serve.env"
def _env_events(text: str) -> str:
"""The ASK_FORM_EVENTS_URL a serve.env sets ("" when none / empty)."""
cur = ""
for line in text.splitlines():
m = _EVENTS_RE.match(line)
if m:
cur = m.group(1).strip("'\"")
return cur
def _restart_serve() -> bool:
"""Restart `ask-form serve` through the service manager `ask-form setup`
installed it under. False: no manager knows it (run by hand)."""
try:
if os.uname().sysname == "Darwin":
r = subprocess.run(["launchctl", "kickstart", "-k",
f"gui/{os.getuid()}/{LAUNCHD_LABEL}"],
capture_output=True, timeout=20)
return r.returncode == 0
if subprocess.run(["systemctl", "--user", "is-active", "--quiet", SYSTEMD_UNIT],
capture_output=True, timeout=20).returncode != 0:
return False
return subprocess.run(["systemctl", "--user", "restart", SYSTEMD_UNIT],
capture_output=True, timeout=30).returncode == 0
except (OSError, subprocess.SubprocessError):
return False
def wire_events(restart: Callable[[], bool] | None = None) -> str:
"""Make this machine's `ask-form serve` post its events (the `created`
one carries the form's link) to this sidecar. Idempotent, and only ever
touches ``ASK_FORM_EVENTS_URL`` in ask-form's own ``serve.env`` — never
``ask-form setup``, which would also re-pick its relay and mode. Returns
what happened:
off ask-form isn't installed here (nothing to wire)
wired done — serve restarted so it takes
already it was wired (and has been restarted since)
own the owner set an events URL of their own: left alone
busy written, but a form is open: serve is restarted later (a
restart would cut an agent's `ask-form wait`)
"""
if not installed():
return "off"
want = events_url()
envf = _serve_env()
try:
text = envf.read_text()
except OSError:
text = ""
cur = _env_events(text)
if cur and cur != want:
return "own"
marker = envf.with_name("ai-agent-events")
try:
if cur == want and marker.read_text().strip() == want:
return "already"
except OSError:
pass
if cur != want:
lines = [ln for ln in text.splitlines() if not _EVENTS_RE.match(ln)]
lines.append(f"ASK_FORM_EVENTS_URL={want}")
tmp = envf.with_suffix(".tmp")
envf.parent.mkdir(parents=True, exist_ok=True)
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as fh:
fh.write("\n".join(lines) + "\n")
os.replace(tmp, envf)
try:
code, out = call("GET", "/v1/forms?status=pending", timeout=6)
if code < 400 and (out.get("count") or out.get("forms")):
return "busy"
except HTTPException:
pass # serve isn't up: nothing to interrupt
(restart or _restart_serve)()
marker.write_text(want + "\n")
return "wired"
# ── letting the hub frame this machine's forms ───────────────────────────────
# An origin as ask-form takes one (server.ParseOrigins): https, or http on a
# loopback host; no path, no wildcard.
_ORIGIN_RE = re.compile(r"^(?:https://[a-z0-9.-]+|http://(?:localhost|127\.0\.0\.1))(?::\d{1,5})?$")
_EMBED_RE = re.compile(r"^\s*(?:export\s+)?ASK_FORM_EMBED_ORIGINS\s*=\s*(.*?)\s*$")
# The first ask-form whose `serve` reads ASK_FORM_EMBED_ORIGINS.
EMBED_SINCE = (0, 16, 0)
def _version(v: str) -> tuple[int, ...] | None:
m = re.match(r"^v?(\d+)\.(\d+)\.(\d+)", v or "")
return tuple(int(x) for x in m.groups()) if m else None
def _env_embed(text: str) -> list[str]:
"""The origins a serve.env's ASK_FORM_EMBED_ORIGINS lists."""
cur = ""
for line in text.splitlines():
m = _EMBED_RE.match(line)
if m:
cur = m.group(1).strip("'\"")
return [o for o in re.split(r"[\s,]+", cur) if o]
def wire_embed(origins: list[str], restart: Callable[[], bool] | None = None) -> str:
"""Add the hub's ``origins`` to the sites this machine's `ask-form serve`
lets frame its pages (``ASK_FORM_EMBED_ORIGINS`` in its ``serve.env``,
the owner's own entries kept), so the hub opens a form over its
conversation instead of in a new tab. Idempotent; restarts serve only
with no form open (a restart cuts an agent's `ask-form wait`) — the hub
asks again on a later pass. Returns:
off ask-form isn't installed here
old its serve predates embedding (it updates itself; later)
already serve already lets them frame its pages
busy written, but a form is open: restarted on a later call
wired written and serve restarted
"""
if not installed():
return "off"
h = health()
v = _version(str(h.get("version") or ""))
if h.get("version") != "dev" and (v is None or v < EMBED_SINCE):
return "old"
live = h.get("embedOrigins") if isinstance(h.get("embedOrigins"), list) else []
if all(o in live for o in origins):
return "already"
envf = _serve_env()
try:
text = envf.read_text()
except OSError:
text = ""
cur = _env_embed(text)
want = cur + [o for o in origins if o not in cur]
if want != cur:
lines = [ln for ln in text.splitlines() if not _EMBED_RE.match(ln)]
lines.append("ASK_FORM_EMBED_ORIGINS='" + " ".join(want) + "'")
tmp = envf.with_suffix(".tmp")
envf.parent.mkdir(parents=True, exist_ok=True)
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as fh:
fh.write("\n".join(lines) + "\n")
os.replace(tmp, envf)
try:
code, out = call("GET", "/v1/forms?status=pending", timeout=6)
if code < 400 and (out.get("count") or out.get("forms")):
return "busy"
except HTTPException:
pass # serve isn't up: nothing to interrupt
(restart or _restart_serve)()
return "wired"
def _wire_loop(every: float = WIRE_EVERY_S) -> None:
import link
done = ("off", "already", "own", "wired")
while True:
try:
if link.config(): # a guest's computer, and only that
st = wire_events()
if st in ("wired", "own"):
log.info("ask-form events: %s", st)
if st in done and st != "off":
return
except Exception:
log.exception("ask-form events wiring")
time.sleep(every)
def start() -> None:
"""The sidecar's startup hook: wire a guest's ask-form (retried every
few minutes until it is — the tool may be installed later, or busy)."""
threading.Thread(target=_wire_loop, daemon=True, name="askform-wire").start()