Files

181 lines
6.8 KiB
Python

"""
The hub editions' way to the ai-agent's tool proxy (stdlib only — it runs on
any machine with python3: a guest's run on the lab, a guest's computer, the
owner's Macs).
Where the hub is and the caller's token, in this order:
1. ``AIA_TOOLS_URL`` + ``AIA_TOOLS_TOKEN`` — set by the hub for a guest's run
on the lab;
2. ``hub.json`` beside ``SKILL.md`` — written by the hub's lab sync on a
paired machine (that machine's own token, 0600).
The conversation a call comes from (``CLAUDE_CODE_SESSION_ID``) rides as
``X-Claude-Code-Session-Id``: the hub adds the call's cost to that
conversation's tools chip.
A copy of the ai-agent's hub-edition client (cli/skills/*/scripts/), shipped
with the Meta Business live plugin; ``metalib.py`` builds the plugin's
``plugins/meta/...`` calls on top of it.
"""
from __future__ import annotations
import json
import os
import pathlib
import sys
import urllib.error
import urllib.parse
import urllib.request
import uuid
VERSION = "1"
class HubError(Exception):
def __init__(self, message: str, status: int = 0, kind: str = ""):
super().__init__(message)
self.status = status
self.kind = kind
def skill_dir() -> pathlib.Path:
"""The skill folder of the script that runs (scripts/ → its parent)."""
main = pathlib.Path(sys.argv[0]).resolve()
return main.parent.parent if main.parent.name == "scripts" else main.parent
def config() -> tuple[str, str]:
url = os.environ.get("AIA_TOOLS_URL", "").strip()
token = os.environ.get("AIA_TOOLS_TOKEN", "").strip()
if url and token:
return url.rstrip("/"), token
for d in (skill_dir(), pathlib.Path(__file__).resolve().parent.parent):
try:
hub = json.loads((d / "hub.json").read_text())
except (OSError, ValueError):
continue
if isinstance(hub, dict) and hub.get("url") and hub.get("token"):
return str(hub["url"]).rstrip("/"), str(hub["token"])
raise HubError("no tool proxy configured here — this skill runs through the ai-agent hub "
"(AIA_TOOLS_URL / AIA_TOOLS_TOKEN, or hub.json from the hub's lab sync); "
"ask the hub's owner to switch the tool on for you", 0, "config")
def _headers(token: str, extra: dict | None = None) -> dict:
h = {"Authorization": f"Bearer {token}", "User-Agent": f"ai-agent-tools/{VERSION}"}
sid = os.environ.get("CLAUDE_CODE_SESSION_ID") or os.environ.get("CLAUDE_SESSION_ID")
if sid:
h["X-Claude-Code-Session-Id"] = sid
h.update(extra or {})
return h
def _error(e: urllib.error.HTTPError) -> HubError:
raw = b""
try:
raw = e.read()
except OSError:
pass
msg, kind = "", ""
try:
d = json.loads(raw)
err = d.get("error") if isinstance(d, dict) else None
if isinstance(err, dict):
msg, kind = str(err.get("message") or ""), str(err.get("kind") or "")
elif isinstance(d, dict) and d.get("detail"):
msg = str(d["detail"])
except ValueError:
msg = raw.decode("utf-8", "replace")[:300]
return HubError(msg or f"HTTP {e.code}", e.code, kind)
def open_(method: str, path: str, *, params: dict | None = None, body=None,
headers: dict | None = None, timeout: float = 120.0):
"""The hub's raw response (caller closes it); HubError on an error."""
url, token = config()
full = f"{url}/{path.lstrip('/')}"
if params:
q = {k: ("1" if v is True else v) for k, v in params.items()
if v is not None and v is not False}
if q:
full += "?" + urllib.parse.urlencode(q)
req = urllib.request.Request(full, data=body, method=method, headers=_headers(token, headers))
try:
return urllib.request.urlopen(req, timeout=timeout)
except urllib.error.HTTPError as e:
raise _error(e) from None
except urllib.error.URLError as e:
raise HubError(f"couldn't reach the hub at {url}: {e.reason}", 0, "network") from None
def call(method: str, path: str, *, json_body=None, params: dict | None = None,
body: bytes | None = None, content_type: str | None = None,
timeout: float = 120.0):
"""A JSON call: the decoded reply."""
headers = {}
if json_body is not None:
body = json.dumps(json_body).encode()
headers["Content-Type"] = "application/json"
elif content_type:
headers["Content-Type"] = content_type
with open_(method, path, params=params, body=body, headers=headers, timeout=timeout) as r:
raw = r.read()
try:
return json.loads(raw) if raw else {}
except ValueError:
raise HubError("the hub answered without JSON") from None
def download(path: str, dest: pathlib.Path, *, params: dict | None = None,
timeout: float = 600.0) -> dict:
"""Stream a file to ``dest``; the reply's headers."""
dest = pathlib.Path(dest)
dest.parent.mkdir(parents=True, exist_ok=True)
tmp = dest.with_name(f".{dest.name}.part")
with open_("GET", path, params=params, timeout=timeout) as r, open(tmp, "wb") as f:
while chunk := r.read(1 << 16):
f.write(chunk)
headers = dict(r.headers.items())
os.replace(tmp, dest)
return headers
def upload(path: str, file: pathlib.Path, *, params: dict | None = None,
content_type: str = "application/octet-stream", timeout: float = 900.0):
"""POST a file as the raw body, streamed; the JSON reply."""
file = pathlib.Path(file)
size = file.stat().st_size
with open(file, "rb") as fh, open_("POST", path, params=params, body=fh, timeout=timeout,
headers={"Content-Type": content_type,
"Content-Length": str(size)}) as r:
raw = r.read()
return json.loads(raw) if raw else {}
def multipart(fields: dict, files: list[tuple[str, pathlib.Path, str]]) -> tuple[bytes, str]:
"""A multipart/form-data body: ``fields`` (name → str) and ``files``
(field name, path, mime type)."""
boundary = uuid.uuid4().hex
out = bytearray()
for k, v in fields.items():
out += (f"--{boundary}\r\nContent-Disposition: form-data; name=\"{k}\"\r\n\r\n"
f"{v}\r\n").encode()
for name, p, mime in files:
out += (f"--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"; "
f"filename=\"{pathlib.Path(p).name}\"\r\nContent-Type: {mime}\r\n\r\n").encode()
out += pathlib.Path(p).read_bytes() + b"\r\n"
out += f"--{boundary}--\r\n".encode()
return bytes(out), f"multipart/form-data; boundary={boundary}"
def mime_of(p: pathlib.Path) -> str:
import mimetypes
return mimetypes.guess_type(str(p))[0] or "application/octet-stream"
def die(msg: str, code: int = 1) -> None:
print(f"error: {msg}", file=sys.stderr)
sys.exit(code)