Generic hooks the plugin builds on: the conversations.drawer, composer.send and app.modal slot places (openModal / modal.setResult / modal.close, ?modal= links), runs.start taking the composer's whole payload (auto routing, account, projects, cwd, meta.scheduled) and hub/runs/resolve, a turn's knobs on conversations.send, push buttons answered as the notify.action event, hub/changed (SSE plugin-data), hub/title (conversations.title), the runs.schedule provider behind /api/scheduled, the week's budget and the stopped-run card, providers in /api/plugins/ui, carryover.scheduled. backend/scheduled/ and frontend/src/business/scheduled/ are gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
276 lines
10 KiB
Python
276 lines
10 KiB
Python
"""Sandboxed subprocess runner for plugin scheduled jobs (v1) and backend
|
|
actions (v3).
|
|
|
|
Plugin scripts run in a strictly stripped environment:
|
|
* NO host secrets (``ANTHROPIC_API_KEY``, ``SIDECAR_TOKEN``, ``INTERNAL_API_TOKEN``,
|
|
``GEMINI_API_KEY``, ``SEERR_API_KEY``, ``MATOMO_TOKEN``… are all absent).
|
|
* NO raw user secrets — the script calls ``AIA_TOOLS_URL/plugins/<id>/proxy/…``
|
|
with a short-lived ``AIA_TOOLS_TOKEN`` minted for that user.
|
|
* Read-only user context (``AIA_USER_CONTEXT``: ``{uid, isOwner, domains,
|
|
name, lang, sessionId, grant?}``), non-secret config (``AIA_PLUGIN_CONFIG``),
|
|
a writable per-user data dir (``AIA_PLUGIN_DATA_DIR``) and the plugin's
|
|
hub-scoped dir shared by every user's runs (``AIA_PLUGIN_SHARED_DIR``).
|
|
* ``AIA_TOOLS_TOKEN`` is a *handler token* (``aiah1``): it names the user and
|
|
this plugin, reaches only this plugin's routes, and is what handler-only
|
|
proxy rules require — the guest's own run token can't pass for it.
|
|
* A handler may answer an error with a status of its own:
|
|
``{"_error": {"status": 404, "kind": "...", "message": "..."}}`` on stdout.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import subprocess
|
|
import sys
|
|
from typing import Any
|
|
|
|
from plugins.store import OWNER_UID, PluginStore
|
|
|
|
_SAFE_ENV_KEYS = ("PATH", "LANG", "LC_ALL", "TZ", "HOME", "TMPDIR", "PYTHONUNBUFFERED")
|
|
|
|
|
|
class ActionError(Exception):
|
|
def __init__(self, status: int, message: str, kind: str = "action_failed"):
|
|
super().__init__(message)
|
|
self.status = status
|
|
self.message = message
|
|
self.kind = kind
|
|
|
|
|
|
def _tools_url_local() -> str:
|
|
port = os.environ.get("PORT", "8080")
|
|
return f"http://127.0.0.1:{port}/proxy/tools"
|
|
|
|
|
|
def _user_domains(deps, uid: str) -> str:
|
|
if uid == OWNER_UID:
|
|
return ""
|
|
try:
|
|
from users import domains as user_domains
|
|
u = deps.users.get(uid) or {"id": uid}
|
|
bucket, domain = user_domains.address_of(u, user_domains.default_domain(deps))
|
|
return user_domains.base_of(bucket, domain)
|
|
except Exception:
|
|
return ""
|
|
|
|
|
|
def _active_plugin_ids(store: PluginStore, uid: str) -> list[str]:
|
|
"""Every enabled, approved plugin id active for ``uid`` (own + managed)."""
|
|
out: set[str] = set()
|
|
try:
|
|
out.update(store.active_ids(uid))
|
|
if uid != OWNER_UID:
|
|
for rec in store.managed_plugins():
|
|
pid = rec["id"]
|
|
if store.effective_grant(uid, pid, rec["manifest"]).get("enabled"):
|
|
out.add(pid)
|
|
except Exception:
|
|
pass
|
|
return sorted(out)
|
|
|
|
|
|
def _user_name_lang(deps, uid: str) -> tuple[str, str]:
|
|
if uid == OWNER_UID:
|
|
from users.caller import OWNER
|
|
return OWNER.name, "en"
|
|
try:
|
|
from users.caller import guest_from_record
|
|
u = deps.users.get(uid) or {"id": uid}
|
|
c = guest_from_record({"id": uid, **u})
|
|
return c.name, c.lang or "en"
|
|
except Exception:
|
|
return uid, "en"
|
|
|
|
|
|
def requester_context(deps, uid: str, grant: dict[str, Any] | None = None,
|
|
session_id: str | None = None) -> dict[str, Any]:
|
|
"""Who started a guest's ``runAs: "owner"`` action — handed to the
|
|
handler as ``AIA_USER_CONTEXT.requester`` (``uid``, ``isOwner``, ``name``,
|
|
``lang``, ``domains``, ``sessionId``, ``grant``) while it runs with the
|
|
owner's hub context. A plugin checks ``requester`` before ``uid``."""
|
|
r_name, r_lang = _user_name_lang(deps, uid)
|
|
ctx: dict[str, Any] = {
|
|
"uid": uid,
|
|
"isOwner": uid == OWNER_UID,
|
|
"name": r_name,
|
|
"lang": r_lang,
|
|
"domains": _user_domains(deps, uid),
|
|
"sessionId": session_id,
|
|
}
|
|
if grant is not None:
|
|
ctx["grant"] = dict(grant.get("config") or {})
|
|
return ctx
|
|
|
|
|
|
def _structured_error(stdout: str) -> ActionError | None:
|
|
"""A handler's own ``{"_error": {status, kind, message}}``."""
|
|
try:
|
|
parsed = json.loads(stdout) if stdout else None
|
|
except ValueError:
|
|
return None
|
|
err = parsed.get("_error") if isinstance(parsed, dict) else None
|
|
if not isinstance(err, dict):
|
|
return None
|
|
try:
|
|
status = int(err.get("status") or 422)
|
|
except (TypeError, ValueError):
|
|
status = 422
|
|
status = min(599, max(400, status))
|
|
e = ActionError(status, str(err.get("message") or f"plugin error {status}")[:1000])
|
|
e.kind = str(err.get("kind") or "action_failed")[:40]
|
|
return e
|
|
|
|
|
|
def _script_cmd(path: pathlib.Path) -> list[str]:
|
|
if path.suffix == ".py":
|
|
return [sys.executable, str(path)]
|
|
if os.access(path, os.X_OK):
|
|
return [str(path)]
|
|
if path.suffix == ".sh":
|
|
return ["/bin/sh", str(path)]
|
|
return [sys.executable, str(path)]
|
|
|
|
|
|
def run_script(
|
|
deps,
|
|
store: PluginStore,
|
|
uid: str,
|
|
rec: dict[str, Any],
|
|
rel_script: str,
|
|
*,
|
|
payload: dict[str, Any] | None = None,
|
|
timeout_sec: int = 30,
|
|
grant: dict[str, Any] | None = None,
|
|
using_own_secret: bool = False,
|
|
session_id: str | None = None,
|
|
call_depth: int = 0,
|
|
caller_plugin: str | None = None,
|
|
requester: dict[str, Any] | None = None,
|
|
candidate_secret: str | None = None,
|
|
context: dict[str, Any] | None = None,
|
|
) -> dict[str, Any]:
|
|
"""Run ``rel_script`` inside ``rec['dir']`` with a stripped environment and
|
|
JSON stdin/stdout contract. ``candidate_secret``: this run's proxy calls
|
|
use it instead of the stored secret (a key checked before it is saved).
|
|
``context``: more ``AIA_USER_CONTEXT`` keys the host vouches for — a
|
|
worker-bound caller's ``viaWorker`` / ``viaWorkerName`` / ``workerMode``
|
|
(plugins/schedule_bridge.py); never ``uid`` / ``isOwner``."""
|
|
mf = rec.get("manifest") or {}
|
|
pid = mf["id"]
|
|
plugin_root = pathlib.Path(rec["dir"]).resolve()
|
|
script_path = (plugin_root / rel_script).resolve()
|
|
try:
|
|
script_path.relative_to(plugin_root)
|
|
except ValueError:
|
|
raise ActionError(400, "script escapes plugin directory") from None
|
|
if not script_path.is_file():
|
|
raise ActionError(404, f"plugin script not found: {rel_script}")
|
|
|
|
from toolproxy import access
|
|
token = access.mint_handler(uid, pid, ttl=max(timeout_sec + 60, 300))
|
|
data_dir = store.user_data_dir(uid, pid)
|
|
shared_dir = store.shared_data_dir(pid)
|
|
name, lang = _user_name_lang(deps, uid)
|
|
|
|
user_ctx: dict[str, Any] = {
|
|
"uid": uid,
|
|
"isOwner": uid == OWNER_UID,
|
|
"domains": _user_domains(deps, uid),
|
|
"name": name,
|
|
"lang": lang,
|
|
"sessionId": session_id,
|
|
}
|
|
if caller_plugin:
|
|
user_ctx["callerPlugin"] = caller_plugin
|
|
if requester is not None:
|
|
user_ctx["requester"] = requester
|
|
for k, v in (context or {}).items():
|
|
if k not in user_ctx and v is not None:
|
|
user_ctx[k] = v
|
|
if grant is not None:
|
|
user_ctx["grant"] = {
|
|
**dict(grant.get("config") or {}),
|
|
"monthlyBudgetUsd": grant.get("monthlyBudgetUsd"),
|
|
"usingOwnSecret": bool(using_own_secret),
|
|
}
|
|
|
|
env = {k: os.environ[k] for k in _SAFE_ENV_KEYS if k in os.environ}
|
|
env.update({
|
|
"AIA_TOOLS_URL": _tools_url_local(),
|
|
"AIA_TOOLS_TOKEN": token,
|
|
"AIA_PLUGIN_ID": pid,
|
|
"AIA_PLUGIN_DIR": str(plugin_root),
|
|
"AIA_PLUGIN_DATA_DIR": str(data_dir),
|
|
"AIA_PLUGIN_SHARED_DIR": str(shared_dir),
|
|
"AIA_PLUGIN_CONFIG": json.dumps(rec.get("config") or {}),
|
|
"AIA_USER_CONTEXT": json.dumps(user_ctx),
|
|
"AIA_PLUGIN_CALL_DEPTH": str(int(call_depth)),
|
|
"AIA_ACTIVE_PLUGINS": json.dumps(_active_plugin_ids(
|
|
store, (requester or {}).get("uid") or uid)),
|
|
})
|
|
caps = set(mf.get("capabilities") or [])
|
|
# ``services.read``: the host's services dir (the Services catalogue
|
|
# plugin reads its compose / Traefik files) — the owner's runs only.
|
|
if uid == OWNER_UID and "services.read" in caps:
|
|
from services.catalog import SERVICES_DIR
|
|
if SERVICES_DIR.is_dir():
|
|
env["AIA_SERVICES_DIR"] = str(SERVICES_DIR)
|
|
# ``plans.read`` / ``plans.write``: the host's data/plans dir (owner only).
|
|
if uid == OWNER_UID and ("plans.read" in caps or "plans.write" in caps):
|
|
plans_dir = pathlib.Path(os.environ.get("PLANS_DIR", "/workspace/data/plans")).resolve()
|
|
env["AIA_PLANS_DIR"] = str(plans_dir)
|
|
# Batch 1 owner-only host dirs — same rule as services/plans: the owner's
|
|
# runs only. A guest's own run never sees them; a guest's call to a
|
|
# managed ``runAs: "owner"`` action runs as the owner and does, so such a
|
|
# plugin must check ``AIA_USER_CONTEXT.requester`` before touching them.
|
|
if uid == OWNER_UID and "templates.read" in caps:
|
|
env["AIA_TEMPLATES_DIR"] = str(pathlib.Path(
|
|
os.environ.get("TEMPLATES_DIR", "/workspace/projects/templates")).resolve())
|
|
if uid == OWNER_UID and "memories.read" in caps:
|
|
env["AIA_MEMORIES_DIR"] = str(pathlib.Path(
|
|
os.environ.get("MEMORIES_DIR", "/memories")).resolve())
|
|
if uid == OWNER_UID and "projects.env" in caps:
|
|
from projects.catalog import PROJECTS_DIR
|
|
env["AIA_PROJECTS_DIR"] = str(PROJECTS_DIR)
|
|
|
|
stdin_bytes = json.dumps(payload if payload is not None else {}).encode("utf-8")
|
|
if candidate_secret:
|
|
from plugins.proxy import register_candidate
|
|
register_candidate(token, candidate_secret)
|
|
try:
|
|
p = subprocess.run(
|
|
_script_cmd(script_path),
|
|
input=stdin_bytes,
|
|
capture_output=True,
|
|
env=env,
|
|
cwd=str(plugin_root),
|
|
timeout=timeout_sec,
|
|
)
|
|
except subprocess.TimeoutExpired:
|
|
raise ActionError(504, f"plugin script timed out after {timeout_sec}s") from None
|
|
except OSError as e:
|
|
raise ActionError(500, f"failed to run plugin script: {e}") from None
|
|
finally:
|
|
if candidate_secret:
|
|
from plugins.proxy import drop_candidate
|
|
drop_candidate(token)
|
|
|
|
stdout = (p.stdout or b"").decode("utf-8", "replace").strip()
|
|
stderr = (p.stderr or b"").decode("utf-8", "replace").strip()
|
|
se = _structured_error(stdout)
|
|
if se is not None:
|
|
raise se
|
|
if p.returncode != 0:
|
|
msg = stderr.splitlines()[-1] if stderr else (stdout[:300] or f"exit {p.returncode}")
|
|
raise ActionError(422 if p.returncode in (1, 2) else 500, msg)
|
|
|
|
if not stdout:
|
|
return {"ok": True}
|
|
try:
|
|
parsed = json.loads(stdout)
|
|
return parsed if isinstance(parsed, dict) else {"ok": True, "result": parsed}
|
|
except ValueError:
|
|
return {"ok": True, "output": stdout[:16384]}
|