Files
splinter/tests/fake_a2a.py
T
lotherk 9c205dcd21 a2a: the client can send a file, and already saves what it receives
a2a_send posts SendMessage with a text part and, when a path is given, a file
part: base64 bytes, a name (the path's last component) and a media type
guessed from the name, at most 8 MiB -- the same cap the server enforces on
the way in. The answer is text; a file the other side sends back is saved by
collect_parts and named by path, which the tool returns.

sp_b64_encode is the missing direction of the base64 helper, with vectors of
its own in test_b64: empty input, one and two trailing bytes, a NUL.

test_a2a: a real PNG is attached, the request carries name, mimeType and the
base64 bytes, and the other side names it in the answer; a missing path is an
error, not a silent empty message.
2026-11-11 10:25:49 +00:00

222 lines
10 KiB
Python

# fake A2A agent for tests/test_a2a.sh and tests/test_a2a_ui.sh.
# argv: port, request log. SendMessage (JSON) and SendStreamingMessage (SSE).
import base64, http.server, json, sys
LOG = sys.argv[2]
def task_obj(state, message=None, artifacts=None):
t = {"id": "task-1", "contextId": "ctx-1",
"status": {"state": state}}
if message is not None:
t["status"]["message"] = {"messageId": "m2", "role": "ROLE_AGENT",
"parts": [{"text": message}]}
if artifacts is not None:
t["artifacts"] = [{"artifactId": "a1",
"parts": [{"text": artifacts}]}]
return t
def event(rid, obj):
return "data: " + json.dumps({"jsonrpc": "2.0", "id": rid,
"result": obj}) + "\n\n"
def error_event(rid, code, message):
return "data: " + json.dumps({"jsonrpc": "2.0", "id": rid,
"error": {"code": code,
"message": message}}) + "\n\n"
class H(http.server.BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def reply(self, obj, ctype="application/json"):
b = obj if isinstance(obj, bytes) else json.dumps(obj).encode()
self.send_response(200)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(b)))
self.end_headers()
self.wfile.write(b)
def do_GET(self):
port = self.server.server_address[1]
if self.path.endswith("old-card.json"):
body = {"name": "fake", "version": "1.0.0",
"url": "http://127.0.0.1:%d/rpc" % port}
else:
body = {"name": "fake", "version": "1.0.0",
"supportedInterfaces": [{
"url": "http://127.0.0.1:%d/rpc" % port,
"protocolBinding": "JSONRPC",
"protocolVersion": "1.0"}]}
b = json.dumps(body).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(b)))
self.end_headers()
self.wfile.write(b)
def do_POST(self):
global last_task
n = int(self.headers.get("Content-Length", 0))
raw = self.rfile.read(n)
with open(LOG, "a") as f:
f.write(raw.decode("utf-8") + "\n")
req = json.loads(raw)
stream = req.get("method") == "SendStreamingMessage"
text = ""
try:
for p in req["params"]["message"]["parts"]:
text += p.get("text", "")
except Exception:
pass
rid = req.get("id")
# a file part: note it so the answer can name it
fpart = None
try:
for p in req["params"]["message"]["parts"]:
if "file" in p:
f = p["file"]
fpart = (f.get("name", ""),
len(base64.b64decode(f.get("bytes", ""))))
except Exception:
pass
ctype = "text/event-stream" if stream else "application/json"
method = req.get("method", "")
if method == "SubscribeToTask":
# the subscription: a state update and an artifact, then the end
if req.get("params", {}).get("id", "") != "task-1":
b = json.dumps({"jsonrpc": "2.0", "id": rid, "error": {
"code": -32001, "message": "TaskNotFound"}}).encode()
return self.reply(b, "application/json")
b = (event(rid, {"statusUpdate": {
"taskId": "task-1", "contextId": "ctx-1",
"status": {"state": "TASK_STATE_COMPLETED",
"message": {"messageId": "m7",
"role": "ROLE_AGENT",
"parts": [{"text": "abo text"}]}}}}) +
event(rid, {"artifactUpdate": {
"taskId": "task-1", "contextId": "ctx-1",
"artifact": {"artifactId": "a4", "parts": [
{"text": "abo teil"}]}}})).encode()
return self.reply(b, "text/event-stream")
if method == "SendMessage" and fpart is not None:
task = task_obj("TASK_STATE_COMPLETED",
"datei empfangen: %s %d" % fpart)
last_task = task
return self.reply({"jsonrpc": "2.0", "id": rid,
"result": {"task": task}})
if method == "GetTask":
task = last_task if last_task is not None else task_obj(
"TASK_STATE_COMPLETED", "a2a sagt hallo", "und tschuess")
return self.reply({"jsonrpc": "2.0", "id": rid, "result": task})
if method == "CancelTask":
return self.reply({"jsonrpc": "2.0", "id": rid,
"error": {"code": -32002,
"message": "TaskNotCancelable"}})
want_auth = "auth" in text
if want_auth and self.headers.get("Authorization") != "Bearer tok":
if stream:
b = error_event(rid, -32000, "unauthorized").encode()
else:
b = json.dumps({"jsonrpc": "2.0", "id": rid,
"error": {"code": -32000,
"message": "unauthorized"}}).encode()
elif "fehler" in text:
if stream:
b = error_event(rid, -32603, "boom from a2a").encode()
else:
b = json.dumps({"jsonrpc": "2.0", "id": rid,
"error": {"code": -32603,
"message": "boom from a2a"}}).encode()
elif "direkt" in text:
msg = {"messageId": "m1", "contextId": "ctx-1",
"role": "ROLE_AGENT",
"parts": [{"text": "direkt vom agenten"}]}
if stream:
b = event(rid, {"message": msg}).encode()
else:
b = json.dumps({"jsonrpc": "2.0", "id": rid,
"result": {"message": msg}}).encode()
elif "datei" in text:
# an answer with a binary part: the client saves it and tells the
# model the path
task = {"id": "task-1", "contextId": "ctx-1",
"status": {"state": "TASK_STATE_COMPLETED",
"message": {"messageId": "m6",
"role": "ROLE_AGENT",
"parts": [
{"text": "hier ist die datei"},
{"file": {
"name": "bild.png",
"mimeType": "image/png",
"bytes": base64.b64encode(
b"PNGDATA").decode()}}]}}}
last_task = task
body = {"jsonrpc": "2.0", "id": rid, "result": {"task": task}}
b = json.dumps(body).encode()
elif "raw" in text:
task = {"id": "task-1", "contextId": "ctx-1",
"status": {"state": "TASK_STATE_COMPLETED",
"message": {"messageId": "m5",
"role": "ROLE_AGENT",
"parts": [{"text": "text teil"}]}},
"artifacts": [{"artifactId": "a3", "parts": [
{"raw": "aGFsbG8=", "mediaType": "text/plain"},
{"data": "struktur"}]}]}
last_task = task
body = {"jsonrpc": "2.0", "id": rid, "result": {"task": task}}
b = json.dumps(body).encode()
elif stream and "streamstatus" in text:
b = (event(rid, {"task": task_obj("TASK_STATE_WORKING")}) +
event(rid, {"statusUpdate": {
"taskId": "task-1", "contextId": "ctx-1",
"status": {"state": "TASK_STATE_COMPLETED",
"message": {"messageId": "m3",
"role": "ROLE_AGENT",
"parts": [{"text": "nur status"}]}}}})).encode()
elif stream and "stream" in text:
b = (event(rid, {"task": task_obj("TASK_STATE_WORKING")}) +
event(rid, {"artifactUpdate": {
"taskId": "task-1", "contextId": "ctx-1",
"artifact": {"artifactId": "a2",
"parts": [{"text": "teil eins"}]}}}) +
event(rid, {"artifactUpdate": {
"taskId": "task-1", "contextId": "ctx-1",
"append": True,
"artifact": {"artifactId": "a2",
"parts": [{"text": " teil zwei"}]}}}) +
event(rid, {"statusUpdate": {
"taskId": "task-1", "contextId": "ctx-1",
"status": {"state": "TASK_STATE_COMPLETED",
"message": {"messageId": "m4",
"role": "ROLE_AGENT",
"parts": [{"text": "fertig"}]}}}})).encode()
elif "streamstatus" in text:
b = json.dumps({"jsonrpc": "2.0", "id": rid, "result": {
"task": task_obj("TASK_STATE_COMPLETED", "nur status")}}).encode()
elif "stream" in text:
b = json.dumps({"jsonrpc": "2.0", "id": rid, "result": {
"task": task_obj("TASK_STATE_COMPLETED", None,
"teil eins teil zwei")}}).encode()
else:
task = task_obj("TASK_STATE_COMPLETED", "a2a sagt hallo",
"und tschuess")
last_task = task
if stream:
b = event(rid, {"task": task}).encode()
else:
b = json.dumps({"jsonrpc": "2.0", "id": rid,
"result": {"task": task}}).encode()
self.send_response(200)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(b)))
self.end_headers()
self.wfile.write(b)
http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()