EnergyVenom's picture
Astra: PO/GL actions, usage coverage, assisted sign-in, self-healing, recorder, new top navigation and theme (172a4e22a2bf)
fb62a97 verified
Raw History Blame Contribute Delete
42.4 kB
"""/a2a: Astra as an A2A (Agent2Agent protocol v0.3) agent, JSON-RPC 2.0 over HTTP, with SSE streaming.
Another agent (for example one that crawls a pod's modules and versions and Oracle's patch updates) finds Astra at
/.well-known/agent-card.json and calls POST /a2a with a personal access token (`Authorization: Bearer pwt_...`, the same
tokens, scopes, rate limit and code paths as /mcp, see api/mcp.py). Skills:
- assess-readiness, get-report (scope "read")
- design-tests, run-tests (scope "read,act" and run.start): a proposal first (task input-required); a follow-up message
{"confirm": true} on the same task starts it through the same confirm path as Ask and MCP (role, gate and the
emergency stop re-checked; a proposal is single use).
- test-these-cases (scope "read,act" and run.start): parse + script + dry run (custom_cases.py). The task waits until a
PERSON approves the cases in Astra; the caller can never approve. Then {"confirm": true} runs the approved ones.
A task that leads to a test run follows it (working, input-required while a person reviews, completed with the report,
failed). Never through A2A: approving custom cases, sign-off, failure verdicts, waivers, the emergency stop, admin.
What the caller sends about its pod and patch is untrusted data: stored on the task and shown back, never given to an
LLM as instructions and never fetched (URLs are only displayed). Text is routed with the deterministic Ask intent rules.
Why not the a2a-sdk: its server app brings its own request handler, task store and auth model; binding tasks to our
tokens, RBAC and audit would mean adapters around all three. The subset below (message/send, message/stream,
tasks/get, tasks/cancel, tasks/resubscribe) is the JSON-RPC binding of the spec, without push notifications.
"""
from __future__ import annotations
import asyncio
import json
import logging
import re
import secrets
import time
import uuid
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse, Response, StreamingResponse
from pydantic import BaseModel, ConfigDict, Field, ValidationError
from starlette.concurrency import run_in_threadpool
from ..config import VERSION
from ..platform import custom_cases as C
from ..platform.api_tokens import TokenStore
from ..platform.pods import PodRegistry
from . import mcp
from .errors import ApiError
from .mcp import Toolbox, ToolFailure, _module, _now
log = logging.getLogger("fpt.a2a")
router = APIRouter()
PROTOCOL_VERSION = "0.3.0"
MAX_BODY = 256 * 1024
MAX_PARTS = 20
MAX_TEXT = 8000
MAX_HISTORY = 50
STREAM_POLL_SECONDS = 1.0
STREAM_MAX_SECONDS = 600
TERMINAL = {"completed", "canceled", "failed", "rejected"}
STOP = TERMINAL | {"input-required", "auth-required"} # a stream ends here (final: true)
ACT_SKILLS = {"design-tests", "run-tests", "test-these-cases"}
PATCH_RE = re.compile(r"^\d{2}[A-D]$", re.I) # the release names Astra's research knows (e.g. 26C)
# JSON-RPC / A2A error codes
TASK_NOT_FOUND, NOT_CANCELABLE, PUSH_UNSUPPORTED, UNSUPPORTED, CONTENT_TYPE, EXT_CARD = -32001, -32002, -32003, -32004, -32005, -32007
IO = ["text/plain", "application/json"]
SKILLS = [
{"id": "assess-readiness", "name": "Assess patch readiness",
"description": "Readiness of each business area for the latest (or a given) Oracle patch: Ready / Not ready / Held / "
"Not tested yet, with scenario counts. Input (optional): DataPart {area, patch}. Scope: read.",
"tags": ["oracle-fusion", "patch", "readiness"], "examples": ["Is Procure-to-Pay ready for 26C?"],
"inputModes": IO, "outputModes": IO},
{"id": "design-tests", "name": "Design tests for a patch",
"description": "Send what your agent found: DataPart {pod: {...}, patch: {id, changes: [{area, description, source_url?}]}, "
"mode?: quick|browser, environment?}. Astra proposes a test run of the affected areas (its own "
"generator chooses the scenarios; your facts are recorded as data). Reply {confirm: true} on the same "
"task to start it. Scope: read,act.",
"tags": ["oracle-fusion", "patch", "test-design"], "inputModes": ["application/json"], "outputModes": IO},
{"id": "test-these-cases", "name": "Test these cases",
"description": "Your own test cases: DataPart {cases: [{title, area, priority?, steps: [{action, expected?}], data?, "
"preconditions?}], environment?} (at most 50). Astra writes the scripts and dry-runs them; a PERSON "
"approves them in Astra (never the caller). Then reply {confirm: true} to run the approved ones. "
"Scope: read,act.",
"tags": ["oracle-fusion", "custom-test-cases"], "inputModes": ["application/json"], "outputModes": IO},
{"id": "run-tests", "name": "Run tests",
"description": "Propose a test run: DataPart {area or areas, mode?: quick|browser, environment?, patch?} or text "
"('run a quick simulation of Procure-to-Pay'). Reply {confirm: true} on the same task to start it. "
"The task then follows the run. Scope: read,act.",
"tags": ["oracle-fusion", "test-run"], "examples": ["Run a quick simulation of Procure-to-Pay"], "inputModes": IO, "outputModes": IO},
{"id": "get-report", "name": "Get a test report",
"description": "A finished run's report: verdict and QA rule result per area, counts, exit criteria, links, and the "
"PDF (opens for a signed-in person). Input: DataPart {run_id}. Scope: read.",
"tags": ["oracle-fusion", "report"], "inputModes": IO, "outputModes": IO + ["application/pdf"]},
]
SKILL_IDS = {s["id"] for s in SKILLS}
HELP = ("I am Astra: I test Oracle Fusion patches. Skills: " + "; ".join(f"{s['id']} ({s['name']})" for s in SKILLS)
+ ". Choose one with message.metadata.skill or a DataPart {\"skill\": ...}. Starting anything needs a confirm, and "
"custom test cases need a person's approval in Astra.")
class RpcError(Exception):
def __init__(self, code: int, message: str):
super().__init__(message)
self.code = code
# ------------------------------------------------------------------------------------------------ caller input
class Change(BaseModel):
model_config = ConfigDict(extra="forbid")
area: str = Field(min_length=1, max_length=60)
description: str = Field(min_length=1, max_length=2000)
source_url: str | None = Field(default=None, max_length=500) # displayed only, never fetched
class PatchFacts(BaseModel):
model_config = ConfigDict(extra="forbid")
id: str | None = Field(default=None, max_length=40)
changes: list[Change] = Field(default_factory=list, max_length=200)
class DesignIn(BaseModel):
model_config = ConfigDict(extra="forbid")
skill: str | None = None
pod: dict = Field(default_factory=dict)
patch: PatchFacts = Field(default_factory=PatchFacts)
areas: list[str] = Field(default_factory=list, max_length=10)
mode: str = Field(default="quick", pattern="^(quick|browser)$")
environment: str | None = Field(default=None, max_length=60)
class RunTestsIn(BaseModel):
model_config = ConfigDict(extra="forbid")
skill: str | None = None
area: str | None = Field(default=None, max_length=60)
areas: list[str] = Field(default_factory=list, max_length=10)
mode: str = Field(default="quick", pattern="^(quick|browser)$")
environment: str | None = Field(default=None, max_length=60)
patch: str | None = Field(default=None, max_length=40)
def _bad(e: ValidationError) -> RpcError:
return RpcError(-32602, "Invalid input: " + "; ".join(f"{'.'.join(str(p) for p in x['loc'])}: {x['msg']}" for x in e.errors()[:8]))
def _parts(msg: dict) -> tuple[str, dict | None]:
"""The message's text (joined) and its first DataPart. FileParts are accepted and ignored (nothing is fetched)."""
texts, data = [], None
for p in msg["parts"]:
kind = p.get("kind") if isinstance(p, dict) else None
if kind == "text" and isinstance(p.get("text"), str):
texts.append(p["text"])
elif kind == "data" and isinstance(p.get("data"), dict):
data = p["data"] if data is None else data
elif kind != "file":
raise RpcError(-32602, "Each part needs kind text, data or file.")
text = "\n".join(texts)
if len(text) > MAX_TEXT:
raise RpcError(-32602, f"The text is longer than {MAX_TEXT} characters.")
return text, data
def _check_message(msg) -> dict:
if not isinstance(msg, dict) or msg.get("role") != "user" or not isinstance(msg.get("parts"), list) or not msg["parts"]:
raise RpcError(-32602, "params.message needs role 'user' and at least one part.")
if len(msg["parts"]) > MAX_PARTS:
raise RpcError(-32602, f"At most {MAX_PARTS} parts per message.")
for k in ("messageId", "taskId", "contextId"):
if msg.get(k) is not None and (not isinstance(msg[k], str) or len(msg[k]) > 100):
raise RpcError(-32602, f"message.{k} must be a short string.")
return msg
def _agent_message(task_id: str, context_id: str, text: str, data: dict | None = None) -> dict:
parts: list[dict] = [{"kind": "text", "text": text}]
if data is not None:
parts.append({"kind": "data", "data": data})
return {"kind": "message", "messageId": uuid.uuid4().hex, "role": "agent", "parts": parts, "taskId": task_id, "contextId": context_id}
def _choose_skill(msg: dict, text: str, data: dict | None) -> str | None:
named = (msg.get("metadata") or {}).get("skill") if isinstance(msg.get("metadata"), dict) else None
named = named or (data or {}).get("skill")
if named:
return str(named) if str(named) in SKILL_IDS else None
if data and "cases" in data:
return "test-these-cases"
if data and ("patch" in data or "pod" in data):
return "design-tests"
if data and "run_id" in data:
return "get-report"
if re.search(r"\breport\b", text or "", re.I):
return "get-report"
from ..chat.intent import route
return {"readiness": "assess-readiness", "start_run": "run-tests"}.get(route(text or "").tool)
# ------------------------------------------------------------------------------------------------ tasks
class A2AToolbox(Toolbox):
VIA = "a2a"
def task_out(row: dict, history_length: int | None = None) -> dict:
hist = json.loads(row["history_json"] or "[]")
status_msg = next((m for m in reversed(hist) if m.get("role") == "agent"), None)
if history_length is not None:
hist = hist[-history_length:] if history_length > 0 else []
return {"kind": "task", "id": row["id"], "contextId": row["context_id"],
"status": {"state": row["state"], **({"message": status_msg} if status_msg else {}), "timestamp": row["updated_at"]},
"history": hist, "artifacts": json.loads(row["artifacts_json"] or "[]"),
"metadata": {"skill": row["skill"], "run_id": row["run_id"], "batch_id": row["batch_id"]}}
class Tasks:
"""A2A tasks for one caller (token owner + token). Every method is blocking (database): call off the event loop."""
def __init__(self, request: Request, user, token: dict):
self.request, self.user, self.token = request, user, token
self.svc, self.runs = request.app.state.svc, request.app.state.runs
self.scopes = set(str(token["scopes"]).split(","))
def box(self) -> A2AToolbox:
return A2AToolbox(self.request, self.user, self.token)
def link(self, path: str) -> str:
from .mcp import _abs
return _abs(self.svc, path) or path
def audit(self, kind: str, row: dict | None, summary: str, **payload) -> None:
self.svc.audit.append(kind, actor=self.user.username, run_id=(row or {}).get("run_id"), summary=summary[:200],
payload={"task": (row or {}).get("id"), "skill": (row or {}).get("skill"), "token_id": self.token["id"], **payload})
# -- storage
def get(self, tid: str) -> dict | None:
return self.svc.db.one("SELECT * FROM a2a_tasks WHERE id=?", (tid,))
def own(self, tid, write: bool = False) -> dict:
row = self.get(str(tid)[:100]) if isinstance(tid, str) else None
mine = row and int(row["user_id"]) == int(self.user.id) and (not write or int(row["token_id"]) == int(self.token["id"]))
if not row or not (mine or (not write and self.user.role == "admin")):
raise RpcError(TASK_NOT_FOUND, "Task not found.")
return row
def create(self, skill: str, msg: dict, facts: dict | None = None) -> dict:
tid = secrets.token_urlsafe(12)
ctx = msg.get("contextId") or uuid.uuid4().hex
now = _now()
user_msg = {**msg, "taskId": tid, "contextId": ctx, "kind": "message"}
self.svc.db.insert("a2a_tasks", {"id": tid, "context_id": ctx, "user_id": self.user.id, "token_id": self.token["id"],
"skill": skill, "state": "submitted", "facts_json": json.dumps(facts) if facts else None,
"history_json": json.dumps([user_msg]), "artifacts_json": "[]",
"created_at": now, "updated_at": now})
row = self.get(tid)
self.audit("a2a.task", row, f"{skill} task from token '{self.token['name']}'")
return row
def update(self, row: dict, **cols) -> dict:
cols["updated_at"] = _now()
sets = ", ".join(f"{k}=?" for k in cols)
self.svc.db.x(f"UPDATE a2a_tasks SET {sets} WHERE id=?", (*cols.values(), row["id"])) # noqa: S608 (column names are ours)
return self.get(row["id"])
def add_user_message(self, row: dict, msg: dict) -> dict:
hist = json.loads(row["history_json"])[-(MAX_HISTORY - 1):] + [{**msg, "kind": "message", "taskId": row["id"], "contextId": row["context_id"]}]
return self.update(row, history_json=json.dumps(hist))
def state(self, row: dict, state: str, text: str, data: dict | None = None) -> dict:
if row["state"] == state and row["status_text"] == text:
return row
hist = json.loads(row["history_json"])[-(MAX_HISTORY - 1):] + [_agent_message(row["id"], row["context_id"], text, data)]
if row["state"] != state:
self.audit("a2a.state", row, f"{row['state']} -> {state}", **{"from": row["state"], "to": state})
return self.update(row, state=state, status_text=text, history_json=json.dumps(hist))
def artifact(self, row: dict, artifact_id: str, name: str, parts: list[dict], description: str | None = None) -> dict:
arts = [a for a in json.loads(row["artifacts_json"]) if a["artifactId"] != artifact_id]
arts.append({"artifactId": artifact_id, "name": name, **({"description": description} if description else {}), "parts": parts})
return self.update(row, artifacts_json=json.dumps(arts))
def claim(self, row: dict) -> bool:
"""input-required -> working in one statement: a second confirm racing the first finds nothing to claim."""
with self.svc.db.tx() as c:
return c.execute("UPDATE a2a_tasks SET state='working', updated_at=? WHERE id=? AND state='input-required'",
(_now(), row["id"])).rowcount == 1
# -- permission
def act_refusal(self, skill: str) -> str | None:
if "act" not in self.scopes:
return ("This token is read-only. Create a token with the 'read and act' scope in Astra "
"(Account → Access tokens for AI assistants) to design or run tests.")
if not self.user.can("run.start"):
return f"Your role ({self.user.role}) can't start test runs in Astra."
return None
# -- message/send
def send(self, msg: dict) -> dict:
_check_message(msg)
text, data = _parts(msg)
if msg.get("taskId"):
row = self.own(msg["taskId"], write=True)
if row["state"] in TERMINAL:
raise RpcError(UNSUPPORTED, f"This task is {row['state']}. Start a new task (send without taskId).")
return self.follow_up(self.add_user_message(row, msg), text, data)
skill = _choose_skill(msg, text, data)
if skill is None:
row = self.create("help", msg)
return self.state(row, "completed", HELP, {"skills": sorted(SKILL_IDS)})
if skill in ACT_SKILLS:
refusal = self.act_refusal(skill)
if refusal:
row = self.create(skill, msg)
self.audit("a2a.refused", row, refusal[:120])
return self.state(row, "rejected", refusal)
return getattr(self, "skill_" + skill.replace("-", "_"))(msg, text, data or {})
# -- read skills
def skill_assess_readiness(self, msg: dict, text: str, data: dict) -> dict:
from ..chat.intent import PATCH_ID, modules_in
row = self.create("assess-readiness", msg)
area = data.get("area") if isinstance(data.get("area"), str) else (modules_in(text) or [None])[0]
patch = data.get("patch") if isinstance(data.get("patch"), str) else (m.group(1).upper() if (m := PATCH_ID.search(text or "")) else None)
try:
res = self.box().readiness(area, patch)
except ToolFailure as e:
return self.state(row, "failed", str(e))
text_out = res["content"][0]["text"]
row = self.artifact(row, "readiness", "Patch readiness", [{"kind": "text", "text": text_out}, {"kind": "data", "data": res["structuredContent"]}])
return self.state(row, "completed", text_out)
def skill_get_report(self, msg: dict, text: str, data: dict) -> dict:
rid = data.get("run_id") if isinstance(data.get("run_id"), str) else None
if not rid:
rid = next((w for w in re.findall(r"[A-Za-z0-9_-]{6,64}", text or "")[:20] if self.svc.db.get_run(w)), None)
row = self.create("get-report", msg)
if not rid or not self.svc.db.get_run(rid[:64]):
return self.state(row, "rejected", "Say which test run: a DataPart {\"skill\": \"get-report\", \"run_id\": \"...\"}.")
row = self.update(row, run_id=rid)
return self.report(row, final=True)
def report(self, row: dict, final: bool) -> dict:
res = self.box().report_summary(row["run_id"])
info = res["structuredContent"]
parts = [{"kind": "text", "text": res["content"][0]["text"]}, {"kind": "data", "data": info}]
parts += [{"kind": "file", "file": {"uri": a["pdf"], "mimeType": "application/pdf", "name": f"patchwise-{row['run_id']}-{a['area'].lower()}.pdf"}}
for a in info.get("areas") or [] if a.get("pdf")]
row = self.artifact(row, "report", "Test report", parts, "Verdict and QA rule result per area, counts, exit criteria and links. "
"Sign-off happens in Astra.")
if not final:
return row
return self.state(row, "completed", res["content"][0]["text"])
# -- act skills: propose, then confirm on the same task
def skill_design_tests(self, msg: dict, text: str, data: dict) -> dict:
try:
d = DesignIn.model_validate(data)
except ValidationError as e:
raise _bad(e) from e
if len(json.dumps(d.pod)) > 16 * 1024:
raise RpcError(-32602, "pod details are larger than 16 KB.")
facts = {"pod": d.pod, "patch": d.patch.model_dump()}
row = self.create("design-tests", msg, facts)
mods, unknown = [], []
for a in d.areas + [c.area for c in d.patch.changes]:
try:
m = _module(a)
except ToolFailure:
unknown.append(a[:40])
continue
if m and m not in mods:
mods.append(m)
patch_id = d.patch.id.upper() if d.patch.id and PATCH_RE.match(d.patch.id) else None
note = (f" Your agent's facts are recorded on this task as data ({len(d.patch.changes)} change(s)"
+ (f", patch {d.patch.id[:40]}" if d.patch.id else "") + "); Astra's own generator chooses the scenarios"
+ (f" for patch {patch_id}" if patch_id else "") + "."
+ (f" Areas not recognised: {', '.join(sorted(set(unknown)))}." if unknown else ""))
if not mods:
from ..chat.intent import MODULE_NAMES
return self.state(row, "rejected", "None of the areas is a business area Astra tests. Known: "
+ ", ".join(f"{k} ({v})" for k, v in MODULE_NAMES.items()) + "." + note)
return self.propose(row, mods, d.mode, d.environment, patch_id, note)
def skill_run_tests(self, msg: dict, text: str, data: dict) -> dict:
if data:
try:
d = RunTestsIn.model_validate(data)
except ValidationError as e:
raise _bad(e) from e
row = self.create("run-tests", msg)
words = ([d.area] if d.area else []) + d.areas
mods = []
for a in words: # practice-app names here; an Oracle Fusion pod reads its own areas from the words
try:
mods.append(_module(a))
except ToolFailure:
pass
patch = d.patch.upper() if d.patch and PATCH_RE.match(d.patch) else None
return self.propose(row, list(dict.fromkeys(m for m in mods if m)), d.mode, d.environment, patch, "", " , ".join(words))
from ..chat.intent import args_for
a = args_for("start_run", text, {})
row = self.create("run-tests", msg)
return self.propose(row, a.get("modules") or [], "browser" if a.get("mode") == "live" else "quick", a.get("pod"), a.get("patch_id"), "", text)
def propose(self, row: dict, mods: list[str], mode: str, environment: str | None, patch_id: str | None, note: str,
area_text: str | None = None) -> dict:
box = self.box()
res = box._tools().start_run(modules=mods, mode="live" if mode == "browser" else "stub", pod=environment or None, patch_id=patch_id, # noqa: SLF001
area_text=area_text)
try:
out = box._propose(row["skill"], res, None) # noqa: SLF001
except ToolFailure as e:
return self.state(row, "rejected", str(e))
p = out["structuredContent"]
row = self.update(row, proposal_id=p["proposal_id"])
row = self.artifact(row, "proposal", "Proposed test run", [{"kind": "data", "data": {
"summary": p["summary"], "items": p["items"], "expires_at": p["expires_at"], "facts_recorded": bool(row["facts_json"])}}])
items = "\n".join(f"- {i['label']}: {i['value']}" for i in p["items"])
return self.state(row, "input-required", f"{p['summary']}\n{items}\n{note.strip()}\n\nReply {{\"confirm\": true}} on this task "
f"(taskId {row['id']}) to start it, or call tasks/cancel. The proposal expires {p['expires_at']}.".replace("\n\n\n", "\n\n"))
def skill_test_these_cases(self, msg: dict, text: str, data: dict) -> dict:
cases = data.get("cases")
if not isinstance(cases, list):
raise RpcError(-32602, "Send a DataPart {\"cases\": [...]}.")
if len(cases) > C.MAX_CASES:
raise RpcError(-32602, f"At most {C.MAX_CASES} cases per task ({len(cases)} given).")
extra = set(data) - {"skill", "cases", "environment"}
if extra:
raise RpcError(-32602, f"Unknown fields: {', '.join(sorted(extra))[:200]}.")
try: # the strict agent schema: an unknown field or a bad case rejects the whole set
parsed = C.CustomCases.model_validate({"cases": cases}).model_dump()["cases"]
except ValidationError as e:
raise _bad(e) from e
row = self.create("test-these-cases", msg)
try:
ok, warnings = C.validate(parsed, [])
if not ok:
return self.state(row, "rejected", "None of the cases can be used: " + "; ".join(warnings[:8]))
env = data.get("environment")
pods = PodRegistry(self.svc.db, self.svc.vault, self.svc.cfg, self.svc.egress, self.svc.audit).list() # seeds the default pod
pod = next((p for p in pods if p["name"].lower() == str(env)[:60].lower()), None) if env else (pods[0] if pods else None)
if env and not pod:
return self.state(row, "rejected", f"There is no test environment called '{str(env)[:40]}'.")
if not pod:
return self.state(row, "rejected", "There is no test environment to dry-run on yet.")
batch = C.create_batch(self.svc, self.user.username, "a2a", ok, warnings)
row = self.update(row, batch_id=batch["batch_id"])
self.audit("a2a.cases", row, f"{len(ok)} custom case(s) sent; build on pod {pod['id']}", batch=batch["batch_id"], cases=len(ok))
C.start_build(self.svc, batch["batch_id"], int(pod["id"]), self.user.username)
except C.CustomCaseError as e:
return self.state(row, "failed", str(e))
row = self.state(row, "working", "Writing scripts and dry-running your cases on the pod.")
return self.sync(row)
# -- follow-ups on an open task
def follow_up(self, row: dict, text: str, data: dict | None) -> dict:
row = self.sync(row)
if row["state"] != "input-required":
return row
d = data or {}
if any(k in d for k in ("approve", "approved", "approve_cases", "sign_off", "signoff", "verdict")):
self.audit("a2a.refused", row, "approval or sign-off asked through A2A")
return self.state(row, "input-required", "Only a person can approve, decide or sign off, in Astra. "
+ (row["status_text"] or ""))
if not (d.get("confirm") is True or (text or "").strip().lower().rstrip(".!") == "confirm"):
return self.state(row, "input-required", (row["status_text"] or "").split("\n\nReply")[0]
+ "\n\nReply {\"confirm\": true} on this task to go on, or call tasks/cancel.")
refusal = self.act_refusal(row["skill"])
if refusal:
return self.state(row, "input-required", refusal)
if row["proposal_id"] and not row["run_id"]:
return self.confirm_proposal(row)
if row["batch_id"] and not row["run_id"]:
return self.run_batch(row, d.get("mode") if d.get("mode") in ("quick", "browser") else "quick")
return self.sync(row) # a run waiting for a person: a confirm here changes nothing
def confirm_proposal(self, row: dict) -> dict:
if not self.claim(row):
return self.get(row["id"])
try:
res = self.box().confirm(row["proposal_id"])["structuredContent"]
except ToolFailure as e:
row = self.get(row["id"])
return self.state({**row, "state": "input-required"}, "failed", str(e))
row = self.update(self.get(row["id"]), run_id=res.get("run_id"))
self.audit("a2a.confirm", row, f"test run {res.get('run_id')} started")
return self.sync(self.state({**row, "state": "input-required"}, "working", f"The test run has started: {res.get('link') or ''}".strip()))
def run_batch(self, row: dict, mode: str) -> dict:
v = C.view(self.svc, row["batch_id"])
keys = [c["key"] for c in v["cases"] if c["state"] == "approved"]
if not keys:
return self.state(row, "input-required", "No case has been approved by a person yet. "
+ f"Waiting for a person to approve the scenarios in Astra: {self.link('/scenarios/import?batch=' + row['batch_id'])}")
if not self.claim(row):
return self.get(row["id"])
row = self.get(row["id"])
try:
rid = C.run(self.svc, self.runs, row["batch_id"], keys, mode, self.user.username)
except C.CustomCaseError as e:
return self.state({**row, "state": "input-required"}, "failed", str(e))
except ApiError as e: # the emergency stop
return self.state({**row, "state": "input-required"}, "failed", e.detail)
row = self.update(row, run_id=rid)
self.audit("a2a.run", row, f"test run {rid} of {len(keys)} approved custom case(s)", batch=row["batch_id"], keys=keys)
return self.sync(self.state({**row, "state": "input-required"}, "working", f"Testing {len(keys)} approved case(s): {self.link(f'/runs/{rid}')}"))
# -- following a run or a batch
def sync(self, row: dict) -> dict:
if row["state"] in TERMINAL:
return row
if row["run_id"]:
return self.follow_run(row)
if row["batch_id"]:
return self.follow_batch(row)
return row
def follow_run(self, row: dict) -> dict:
from ..chat.tools import STATUS_WORDS
rid = row["run_id"]
run = self.svc.db.get_run(rid)
if not run:
return self.state(row, "failed", "The test run no longer exists.")
st, gate = run.get("status"), run.get("pending_gate")
if gate == "approve_cases" or st == "waiting_approval":
return self.state(row, "input-required", f"Waiting for a person to approve the scenarios in Astra: {self.link(f'/runs/{rid}/scenarios')}")
if gate == "sign_in" or st == "waiting_sign_in":
return self.state(row, "input-required", f"Waiting for a person to sign in to the pod in Astra: {self.link(f'/runs/{rid}')}")
if gate == "human_review" or st == "waiting_review":
return self.state(row, "input-required", f"Waiting for a person to decide the failures in Astra: {self.link(f'/runs/{rid}/failures')}")
if st == "completed":
row = self.report(row, final=False)
return self.state(row, "completed", f"The test run finished. Report: {self.link(f'/runs/{rid}/report')}")
if st in ("failed", "killed"):
return self.state(row, "failed", f"The test run {STATUS_WORDS.get(st, st)}." + (f" {str(run.get('error'))[:200]}" if run.get("error") else ""))
if st == "cancelled":
return self.state(row, "canceled", "The test run was cancelled.")
step = f" ({run['current_node']})" if run.get("current_node") else ""
return self.state(row, "working", f"Testing: {STATUS_WORDS.get(st, st)}{step}. Follow it in Astra: {self.link(f'/runs/{rid}')}")
def follow_batch(self, row: dict) -> dict:
try:
v = C.view(self.svc, row["batch_id"])
except C.CustomCaseError as e:
return self.state(row, "failed", str(e))
cases = [{k: c.get(k) for k in ("key", "title", "area", "state", "case_id", "failed_step", "message", "simulated", "decided_by")}
for c in v["cases"]]
row = self.artifact(row, "cases", "Your test cases", [{"kind": "data", "data": {
"batch_id": row["batch_id"], "status": v["status"], "pod": v["pod"], "cases": cases}}])
link = self.link(f"/scenarios/import?batch={row['batch_id']}")
if v["status"] in ("parsed", "building"):
return self.state(row, "working", "Writing scripts and dry-running your cases on the pod.")
if v["status"] == "failed":
return self.state(row, "failed", f"The scripts could not be built: {v.get('message') or 'see Astra'}.")
by = lambda s: [c for c in cases if c["state"] == s] # noqa: E731
approved, waiting = by("approved"), by("dry_run_passed")
if waiting:
return self.state(row, "input-required", f"{len(waiting)} case(s) passed their dry run. Waiting for a person to approve the "
f"scenarios in Astra: {link}" + (f" ({len(approved)} already approved: reply {{\"confirm\": true}} to run those.)" if approved else ""))
if approved:
return self.state(row, "input-required", f"A person approved {len(approved)} case(s). Reply {{\"confirm\": true}} on this task "
"to run them (optionally with \"mode\": \"quick\" or \"browser\").")
return self.state(row, "completed", f"None of the cases can run: {len(by('not_scriptable'))} could not be scripted, "
f"{len(by('dry_run_failed'))} failed their dry run, {len(by('rejected'))} rejected. Details are in the 'cases' artifact.")
# -- tasks/cancel
def cancel(self, tid) -> dict:
row = self.own(tid, write=True)
row = self.sync(row)
if row["state"] in TERMINAL:
raise RpcError(NOT_CANCELABLE, f"Task cannot be canceled: it is already {row['state']}.")
if "act" not in self.scopes:
raise RpcError(NOT_CANCELABLE, "This token is read-only.")
if row["run_id"]:
from . import actions
run = self.svc.db.get_run(row["run_id"]) or {}
if not (self.user.can("run.control") and (run.get("created_by") == self.user.username or self.user.role == "admin")):
raise RpcError(NOT_CANCELABLE, "You can't cancel that test run (it isn't yours, or your role can't cancel runs).")
try:
actions.cancel_run(self.svc, self.runs, row["run_id"], self.user.username, "cancelled by an agent (A2A)", via="a2a")
except ApiError as e:
raise RpcError(NOT_CANCELABLE, e.detail) from e
elif row["proposal_id"]:
try:
self.box().cancel(row["proposal_id"])
except ToolFailure:
pass # expired or already used: nothing to drop
self.audit("a2a.cancel", row, "task canceled")
return self.state(row, "canceled", "Canceled." + (" The test run was cancelled." if row["run_id"] else " Nothing was started."))
# ------------------------------------------------------------------------------------------------ transport
def agent_card(request: Request) -> dict:
svc = request.app.state.svc
base = (svc.cfg.public_url or str(request.base_url)).rstrip("/")
return {
"protocolVersion": PROTOCOL_VERSION, "name": "Astra",
"description": "Astra tests Oracle Fusion patches before they go live: readiness per business area, test design "
"and runs on a test pod, your own test cases (a person approves them), and the report. Starting "
"anything needs a confirm; approvals and sign-off stay with people in Astra.",
"url": f"{base}/a2a", "preferredTransport": "JSONRPC", "version": VERSION,
"provider": {"organization": "Astra", "url": base},
"capabilities": {"streaming": True, "pushNotifications": False, "stateTransitionHistory": True},
"defaultInputModes": IO, "defaultOutputModes": IO,
"securitySchemes": {"bearer": {"type": "http", "scheme": "bearer",
"description": "Astra access token (pwt_…) from Account → Access tokens for AI assistants"}},
"security": [{"bearer": []}],
"skills": SKILLS,
"supportsAuthenticatedExtendedCard": False,
}
@router.get("/.well-known/agent-card.json", include_in_schema=False)
def well_known_card(request: Request) -> JSONResponse:
card = {k: v for k, v in agent_card(request).items() if v is not None}
return JSONResponse(card, headers={"Cache-Control": "public, max-age=300"})
def _ok(mid, result) -> dict:
return {"jsonrpc": "2.0", "id": mid, "result": result}
def _err(mid, code: int, message: str) -> dict:
return {"jsonrpc": "2.0", "id": mid, "error": {"code": code, "message": message}}
def _history_length(params: dict) -> int | None:
h = params.get("historyLength", (params.get("configuration") or {}).get("historyLength") if isinstance(params.get("configuration"), dict) else None)
return max(0, min(int(h), MAX_HISTORY)) if isinstance(h, int) and not isinstance(h, bool) else None
def _dispatch(tasks: Tasks, method: str, params: dict) -> dict:
"""The task (as the protocol shows it) for a non-streaming method, or RpcError."""
if method == "message/send":
cfg = params.get("configuration") or {}
if isinstance(cfg, dict) and cfg.get("pushNotificationConfig"):
raise RpcError(PUSH_UNSUPPORTED, "Push notifications are not supported: poll tasks/get or use message/stream.")
return task_out(tasks.send(params.get("message")), _history_length(params))
if method == "tasks/get":
return task_out(tasks.sync(tasks.own(params.get("id"))), _history_length(params))
if method == "tasks/cancel":
return task_out(tasks.cancel(params.get("id")))
if method.startswith("tasks/pushNotificationConfig/"):
raise RpcError(PUSH_UNSUPPORTED, "Push notifications are not supported.")
if method == "agent/getAuthenticatedExtendedCard":
raise RpcError(EXT_CARD, "There is no extended agent card.")
raise RpcError(-32601, f"Method not found: {method[:60]}")
def _handle(body, request: Request, user, token: dict) -> dict:
if not isinstance(body, dict) or body.get("jsonrpc") != "2.0" or not isinstance(body.get("method"), str):
return _err(body.get("id") if isinstance(body, dict) else None, -32600, "Invalid request")
mid, params = body.get("id"), body.get("params") or {}
if not isinstance(params, dict):
return _err(mid, -32602, "params must be an object")
try:
return _ok(mid, _dispatch(Tasks(request, user, token), body["method"], params))
except RpcError as e:
return _err(mid, e.code, str(e))
except Exception: # noqa: BLE001 (never a stack trace to the caller; the log has it)
log.exception("a2a %s failed", body["method"][:40])
return _err(mid, -32603, "Astra could not complete that. Try again, or open the app.")
def _sse(obj: dict) -> bytes:
return f"data: {json.dumps(obj, separators=(',', ':'))}\n\n".encode()
async def _stream(request: Request, tasks: Tasks, mid, method: str, params: dict):
"""message/stream and tasks/resubscribe: the Task, then status and artifact updates until input-required or a final
state (final: true), or STREAM_MAX_SECONDS (then final: true while still working: resubscribe or poll tasks/get)."""
def first():
if method == "message/stream":
return tasks.send(params.get("message"))
return tasks.sync(tasks.own(params.get("id")))
try:
row = await run_in_threadpool(first)
except RpcError as e:
yield _sse(_err(mid, e.code, str(e)))
return
except Exception: # noqa: BLE001
log.exception("a2a %s failed", method)
yield _sse(_err(mid, -32603, "Astra could not complete that."))
return
prev = task_out(row, _history_length(params))
yield _sse(_ok(mid, prev))
status = {"kind": "status-update", "taskId": row["id"], "contextId": row["context_id"]}
if row["state"] in STOP:
yield _sse(_ok(mid, {**status, "status": prev["status"], "final": True}))
return
deadline = time.monotonic() + STREAM_MAX_SECONDS
while time.monotonic() < deadline:
if await request.is_disconnected():
return
await asyncio.sleep(STREAM_POLL_SECONDS)
row = await run_in_threadpool(lambda: tasks.sync(tasks.get(row["id"])))
cur = task_out(row)
old = {a["artifactId"]: a for a in prev["artifacts"]}
for a in cur["artifacts"]:
if old.get(a["artifactId"]) != a:
yield _sse(_ok(mid, {"kind": "artifact-update", "taskId": row["id"], "contextId": row["context_id"], "artifact": a,
"append": False, "lastChunk": True}))
done = row["state"] in STOP
if cur["status"]["state"] != prev["status"]["state"] or cur["status"].get("message") != prev["status"].get("message") or done:
yield _sse(_ok(mid, {**status, "status": cur["status"], "final": done}))
if done:
return
prev = cur
yield _sse(_ok(mid, {**status, "status": prev["status"], "final": True}))
@router.post("/a2a", include_in_schema=False)
async def a2a_post(request: Request) -> Response:
if not mcp._origin_ok(request): # noqa: SLF001
return JSONResponse({"error": "forbidden", "detail": "origin not allowed"}, status_code=403)
authz = request.headers.get("authorization", "")
if not authz.lower().startswith("bearer "):
return mcp._unauthorized("a personal access token is required: Authorization: Bearer pwt_...") # noqa: SLF001
got = TokenStore(request.app.state.svc).resolve(authz[7:].strip())
if not got:
return mcp._unauthorized("the token is unknown, revoked or expired, or its owner is disabled") # noqa: SLF001
user, token = got
request.state.user = user
if not mcp._rate_ok(int(token["id"])): # noqa: SLF001 (one budget per token across /mcp and /a2a)
return JSONResponse(_err(None, -32000, "Too many requests: at most 60 a minute per token"), status_code=429, headers={"Retry-After": "60"})
if int(request.headers.get("content-length") or 0) > MAX_BODY:
return JSONResponse(_err(None, -32600, "Request too large (256 KB at most)"), status_code=413)
raw = await request.body()
if len(raw) > MAX_BODY:
return JSONResponse(_err(None, -32600, "Request too large (256 KB at most)"), status_code=413)
try:
body = json.loads(raw or b"null")
except ValueError:
return JSONResponse(_err(None, -32700, "Parse error"), status_code=400)
token = dict(token)
if isinstance(body, dict) and body.get("jsonrpc") == "2.0" and body.get("method") in ("message/stream", "tasks/resubscribe"):
params = body.get("params") if isinstance(body.get("params"), dict) else {}
return StreamingResponse(_stream(request, Tasks(request, user, token), body.get("id"), body["method"], params),
media_type="text/event-stream", headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"})
return JSONResponse(await run_in_threadpool(_handle, body, request, user, token))