mirror of
https://github.com/livekit/agents.git
synced 2026-12-06 04:18:36 +00:00
825 lines
33 KiB
Python
825 lines
33 KiB
Python
"""``a2a_session`` over the wire, in process: each server runs on the worker's own loopback
|
|
listener (``local_server.py``), which serves its text doors natively; a stock a2a-sdk client over
|
|
HTTP+SSE with and without the extension header, two workers sharing one local agent-db
|
|
(``storage_fixture.py``) for the thin slice, the interrupt and a task
|
|
read after a dropped stream. That listener vouches for every caller: authentication by bearer and by the node's
|
|
verdict is pinned by the door's own tests (``lk-agents-runtime/src/a2a/door_tests.rs``)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import contextlib
|
|
import json
|
|
import pickle
|
|
from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
|
|
from typing import Any
|
|
|
|
import httpx
|
|
import pytest
|
|
from a2a.client import ClientConfig, ClientFactory
|
|
from a2a.client.card_resolver import A2ACardResolver
|
|
from a2a.types import a2a_pb2 as pb
|
|
from a2a.utils.constants import TransportProtocol
|
|
from google.protobuf import json_format
|
|
|
|
from livekit.agents import Agent, AgentServer, RunContext, RunResult
|
|
from livekit.agents._generated.a2a_metadata import (
|
|
INTERRUPTED,
|
|
KIND,
|
|
KIND_CHAT_CTX,
|
|
REASON,
|
|
)
|
|
from livekit.agents._generated.storage_class import ThreadInfo
|
|
from livekit.agents.a2a import (
|
|
AGENT_CARD_PATH,
|
|
EXTENSION_URI,
|
|
A2AEndpoint,
|
|
A2ASessionContext,
|
|
AgentThreadGrant,
|
|
Credentials,
|
|
TextPart,
|
|
Unauthorized,
|
|
)
|
|
from livekit.agents.llm import FunctionToolCall
|
|
from livekit.agents.storage import Storage, StorageUnavailable
|
|
|
|
from .fake_llm import FakeLLM, FakeLLMResponse
|
|
from .local_server import serving
|
|
|
|
pytestmark = [pytest.mark.unit]
|
|
|
|
PROJECT_ENV = (
|
|
"LIVEKIT_URL",
|
|
"LIVEKIT_AGENT_NAME",
|
|
"LIVEKIT_AGENT_NAME_OVERRIDE",
|
|
"LIVEKIT_AGENT_DEPLOYMENT",
|
|
"LIVEKIT_AGENT_VERSION",
|
|
)
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def no_project_env(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
"""These tests run their servers in process on the loopback listener; a developer's
|
|
exported demo environment (``LIVEKIT_URL`` shapes the card's URLs, the agent variables its
|
|
name and version) must not reach them."""
|
|
for name in PROJECT_ENV:
|
|
monkeypatch.delenv(name, raising=False)
|
|
|
|
|
|
AGENT = "front-desk"
|
|
API_KEY = "APItest"
|
|
API_SECRET = "secret-secret-secret-secret-secret"
|
|
CREDENTIALS = Credentials(API_KEY, API_SECRET)
|
|
ENDPOINT = "desk"
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------
|
|
# the harness
|
|
# ---------------------------------------------------------------------------------------------
|
|
|
|
|
|
async def echo(ctx: A2ASessionContext) -> str:
|
|
await ctx.update("looking")
|
|
return "reply to: " + ctx.message.text_content
|
|
|
|
|
|
Workers = tuple[Storage, Storage]
|
|
|
|
|
|
def make_server(
|
|
storage: Storage,
|
|
handler: Callable[[A2ASessionContext], Awaitable[Any]] = echo,
|
|
**kw: Any,
|
|
) -> tuple[AgentServer, A2AEndpoint]:
|
|
server = AgentServer(storage=storage, agent_name=AGENT, api_key=API_KEY, api_secret=API_SECRET)
|
|
kw.setdefault("description", "Answers front desk questions.")
|
|
endpoint = server.a2a_session(endpoint=ENDPOINT, **kw)(handler)
|
|
return server, endpoint
|
|
|
|
|
|
@contextlib.asynccontextmanager
|
|
async def http_client(server: AgentServer) -> AsyncIterator[httpx.AsyncClient]:
|
|
"""A client of ``server`` while it serves its endpoints on its loopback listener."""
|
|
async with serving(server) as base:
|
|
async with httpx.AsyncClient(base_url=base, timeout=30.0) as http:
|
|
yield http
|
|
|
|
|
|
def endpoint_url(http: httpx.AsyncClient) -> str:
|
|
return f"{str(http.base_url).rstrip('/')}/{ENDPOINT}"
|
|
|
|
|
|
async def stock_client(http: httpx.AsyncClient, *, extensions: str | None = None) -> Any:
|
|
"""A vanilla a2a-sdk client over JSON-RPC; ``extensions`` is the header it sends."""
|
|
card = await A2ACardResolver(http, endpoint_url(http)).get_agent_card()
|
|
client = ClientFactory(
|
|
ClientConfig(
|
|
httpx_client=http,
|
|
streaming=True,
|
|
supported_protocol_bindings=[TransportProtocol.JSONRPC],
|
|
accepted_output_modes=["text/plain"],
|
|
)
|
|
).create(card)
|
|
if extensions:
|
|
from a2a.client import ClientCallContext
|
|
|
|
client._lk_context = ClientCallContext(service_parameters={"A2A-Extensions": extensions})
|
|
else:
|
|
client._lk_context = None
|
|
return client
|
|
|
|
|
|
def user_message(
|
|
text: str, message_id: str, *, context_id: str | None = None, **metadata: Any
|
|
) -> pb.Message:
|
|
msg = pb.Message(message_id=message_id, role=pb.Role.ROLE_USER, parts=[pb.Part(text=text)])
|
|
if context_id:
|
|
msg.context_id = context_id
|
|
if metadata:
|
|
json_format.ParseDict(metadata, msg.metadata)
|
|
return msg
|
|
|
|
|
|
async def send(client: Any, message: pb.Message) -> list[Any]:
|
|
request = pb.SendMessageRequest(message=message)
|
|
return [e async for e in client.send_message(request, context=client._lk_context)]
|
|
|
|
|
|
def payloads(events: list[Any]) -> list[Any]:
|
|
return [getattr(e, e.WhichOneof("payload")) for e in events]
|
|
|
|
|
|
async def rpc(
|
|
http: httpx.AsyncClient, method: str, params: Mapping[str, Any], **headers: str
|
|
) -> httpx.Response:
|
|
return await http.post(
|
|
f"{endpoint_url(http)}/v1",
|
|
json={"jsonrpc": "2.0", "id": method, "method": method, "params": dict(params)},
|
|
headers=headers,
|
|
)
|
|
|
|
|
|
def sse_results(response: httpx.Response) -> list[dict[str, Any]]:
|
|
out = []
|
|
for block in response.text.split("\n\n"):
|
|
for line in block.splitlines():
|
|
if line.startswith("data: "):
|
|
out.append(json.loads(line[len("data: ") :]))
|
|
return out
|
|
|
|
|
|
def wire(
|
|
text: str, message_id: str, *, context_id: str | None = None, **metadata: Any
|
|
) -> dict[str, Any]:
|
|
msg: dict[str, Any] = {"messageId": message_id, "role": "ROLE_USER", "parts": [{"text": text}]}
|
|
if context_id:
|
|
msg["contextId"] = context_id
|
|
if metadata:
|
|
msg["metadata"] = metadata
|
|
return msg
|
|
|
|
|
|
def state_of(result: dict[str, Any]) -> str | None:
|
|
update = result.get("statusUpdate")
|
|
return update["status"]["state"] if update else None
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------
|
|
# the card and the stock client
|
|
# ---------------------------------------------------------------------------------------------
|
|
|
|
|
|
async def test_the_card_lists_the_http_interface_and_offers_the_extension(
|
|
thread_storage: Storage,
|
|
) -> None:
|
|
server, endpoint = make_server(thread_storage)
|
|
async with http_client(server) as http:
|
|
response = await http.get(f"{endpoint_url(http)}{AGENT_CARD_PATH}")
|
|
url = endpoint_url(http)
|
|
assert response.status_code == 200
|
|
assert response.headers["content-type"] == "application/json"
|
|
card = response.json()
|
|
assert card["name"] == ENDPOINT
|
|
bindings = [(i["protocolBinding"], i["url"]) for i in card["supportedInterfaces"]]
|
|
assert bindings == [("JSONRPC", f"{url}/v1")]
|
|
extensions = {e["uri"]: e for e in card["capabilities"]["extensions"]}
|
|
assert set(extensions) == {EXTENSION_URI}
|
|
# proto3 omits a false bool: not required is said by saying nothing
|
|
assert all(e.get("required", False) is False for e in extensions.values())
|
|
assert [s["id"] for s in card["skills"]] == ["delegate"]
|
|
assert "livekit" in card["securitySchemes"]
|
|
# the url is the server's when it knows its project and deployment
|
|
endpoint.url = "https://acme.livekit.cloud/agents/front-desk/production/desk"
|
|
assert endpoint.card()["supportedInterfaces"][0]["url"] == (
|
|
"https://acme.livekit.cloud/agents/front-desk/production/desk/v1"
|
|
)
|
|
|
|
|
|
def test_the_card_version_is_read_when_the_card_is_served(
|
|
thread_storage: Storage, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
monkeypatch.delenv("LIVEKIT_AGENT_DEPLOYMENT", raising=False)
|
|
monkeypatch.delenv("LIVEKIT_AGENT_VERSION", raising=False)
|
|
_, endpoint = make_server(thread_storage)
|
|
monkeypatch.setenv("LIVEKIT_AGENT_VERSION", "2.3.4")
|
|
assert endpoint.card()["version"] == "2.3.4"
|
|
_, pinned = make_server(thread_storage, version="9.9.9")
|
|
assert pinned.card()["version"] == "9.9.9"
|
|
|
|
|
|
async def test_a_stock_client_without_the_header_gets_a_plain_text_agent(
|
|
thread_storage: Storage,
|
|
) -> None:
|
|
server, _ = make_server(thread_storage)
|
|
async with http_client(server) as http:
|
|
client = await stock_client(http)
|
|
events = await send(client, user_message("what is the fare", "m1"))
|
|
await client.close()
|
|
items = payloads(events)
|
|
assert isinstance(items[0], pb.Task) and items[0].id.startswith("AST_")
|
|
assert items[0].context_id.startswith("AT_")
|
|
statuses = [p for p in items if isinstance(p, pb.TaskStatusUpdateEvent)]
|
|
assert [s.status.state for s in statuses] == [
|
|
pb.TaskState.TASK_STATE_WORKING,
|
|
pb.TaskState.TASK_STATE_COMPLETED,
|
|
]
|
|
assert statuses[0].status.message.parts[0].text == "looking"
|
|
artifacts = [p for p in items if isinstance(p, pb.TaskArtifactUpdateEvent)]
|
|
assert [a.artifact.parts[0].text for a in artifacts] == ["reply to: what is the fare"]
|
|
assert artifacts[0].last_chunk is True
|
|
# nothing profile-specific rides on a plain request
|
|
for s in statuses:
|
|
assert not json_format.MessageToDict(s.status.message.metadata)
|
|
assert all(p.WhichOneof("content") == "text" for p in s.status.message.parts)
|
|
|
|
|
|
async def test_the_header_is_echoed(thread_storage: Storage) -> None:
|
|
async def handler(ctx: A2ASessionContext) -> str:
|
|
await ctx.update("one moment")
|
|
return "Goodbye."
|
|
|
|
server, _ = make_server(thread_storage, handler)
|
|
async with http_client(server) as http:
|
|
response = await rpc(
|
|
http,
|
|
"message/stream",
|
|
{"message": wire("that is all", "m1")},
|
|
**{"A2A-Extensions": EXTENSION_URI},
|
|
)
|
|
assert response.headers["a2a-extensions"] == EXTENSION_URI
|
|
results = [r["result"] for r in sse_results(response)]
|
|
working = next(r["statusUpdate"] for r in results if state_of(r) == "TASK_STATE_WORKING")
|
|
assert "metadata" not in working["status"]["message"]
|
|
|
|
# the same turn without the header: the same text, no echo
|
|
response = await rpc(http, "message/stream", {"message": wire("that is all", "m2")})
|
|
assert "a2a-extensions" not in response.headers
|
|
results = [r["result"] for r in sse_results(response)]
|
|
artifact = next(r["artifactUpdate"] for r in results if "artifactUpdate" in r)
|
|
assert artifact["artifact"]["parts"][0]["text"] == "Goodbye."
|
|
|
|
|
|
async def test_errors_map_as_the_plan_lists_them(thread_storage: Storage) -> None:
|
|
server, _ = make_server(thread_storage)
|
|
async with http_client(server) as http:
|
|
# a message with no messageId
|
|
r = await rpc(
|
|
http, "message/send", {"message": {"role": "ROLE_USER", "parts": [{"text": "x"}]}}
|
|
)
|
|
assert r.json()["error"]["code"] == -32602
|
|
# a task id alone names no session in v0
|
|
r = await rpc(http, "tasks/get", {"id": "AST_nope"})
|
|
assert r.json()["error"]["code"] == -32001
|
|
first = (await rpc(http, "message/send", {"message": wire("hello", "m1")})).json()[
|
|
"result"
|
|
]["task"]
|
|
ctx_id, task_id = first["contextId"], first["id"]
|
|
# a message to a terminal task
|
|
r = await rpc(
|
|
http,
|
|
"message/send",
|
|
{"message": {**wire("more", "m2", context_id=ctx_id), "taskId": task_id}},
|
|
)
|
|
assert r.json()["error"]["code"] == -32004
|
|
# cancel on a terminal task
|
|
r = await rpc(http, "tasks/cancel", {"id": task_id, "contextId": ctx_id})
|
|
assert r.json()["error"]["code"] == -32002
|
|
# an unknown method, a malformed envelope
|
|
r = await rpc(http, "tasks/explode", {})
|
|
assert r.json()["error"]["code"] == -32601
|
|
r = await http.post(f"{endpoint_url(http)}/v1", content=b"{not json")
|
|
assert r.json()["error"]["code"] == -32700
|
|
# an unknown session fails the task thread-not-found (5.12)
|
|
r = await rpc(http, "message/send", {"message": wire("hi", "m9", context_id="AT_unknown")})
|
|
task = r.json()["result"]["task"]
|
|
assert task["status"]["state"] == "TASK_STATE_FAILED"
|
|
assert task["metadata"][REASON] == "thread-not-found"
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------
|
|
# two workers, one backend: the demo checks (plan 10.1)
|
|
# ---------------------------------------------------------------------------------------------
|
|
|
|
|
|
async def test_thin_slice_across_two_workers(thread_storages: Workers) -> None:
|
|
a, b = thread_storages
|
|
seen: list[list[str]] = []
|
|
|
|
async def handler(ctx: A2ASessionContext) -> str:
|
|
seen.append([i.text_content or "" for i in ctx.message_history.items])
|
|
return "seen " + str(len(ctx.message_history.items))
|
|
|
|
server_a, _ = make_server(a, handler)
|
|
server_b, _ = make_server(b, handler)
|
|
async with http_client(server_a) as http_a, http_client(server_b) as http_b:
|
|
client_a = await stock_client(http_a)
|
|
first = payloads(await send(client_a, user_message("hello", "m1")))
|
|
ctx_id = first[0].context_id
|
|
assert ctx_id.startswith("AT_")
|
|
client_b = await stock_client(http_b)
|
|
second = payloads(await send(client_b, user_message("again", "m2", context_id=ctx_id)))
|
|
assert second[0].context_id == ctx_id
|
|
listed = await client_b.list_tasks(pb.ListTasksRequest(context_id=ctx_id))
|
|
await client_a.close()
|
|
await client_b.close()
|
|
assert seen == [[], ["hello", "seen 0"]]
|
|
assert [t.id for t in listed.tasks] == [second[0].id, first[0].id]
|
|
assert all(t.status.state == pb.TaskState.TASK_STATE_COMPLETED for t in listed.tasks)
|
|
|
|
|
|
async def test_a_server_defaults_to_project_isolated_sqlite(tmp_path, monkeypatch) -> None:
|
|
monkeypatch.setenv("HOME", str(tmp_path))
|
|
monkeypatch.setenv("USERPROFILE", str(tmp_path))
|
|
monkeypatch.delenv("LIVEKIT_AGENT_THREADS_DIR")
|
|
seen: list[list[str]] = []
|
|
|
|
async def handler(ctx: A2ASessionContext) -> str:
|
|
seen.append([i.text_content or "" for i in ctx.message_history.items])
|
|
return "seen " + str(len(ctx.message_history.items))
|
|
|
|
server = AgentServer(agent_name=AGENT, api_key=API_KEY, api_secret=API_SECRET)
|
|
server.a2a_session(endpoint=ENDPOINT, description="Answers.")(handler)
|
|
async with http_client(server) as http:
|
|
client = await stock_client(http)
|
|
first = payloads(await send(client, user_message("hello", "m1")))
|
|
ctx_id = first[0].context_id
|
|
second = payloads(await send(client, user_message("again", "m2", context_id=ctx_id)))
|
|
await client.close()
|
|
assert first[0].id.startswith("AST_") and second[0].id.startswith("AST_")
|
|
assert second[0].context_id == ctx_id
|
|
assert seen == [[], ["hello", "seen 0"]]
|
|
from livekit.agents.storage import SQLiteStorage
|
|
|
|
assert isinstance(server.storage, SQLiteStorage)
|
|
restored = pickle.loads(pickle.dumps(server.storage))
|
|
assert restored.threads.location == str(tmp_path / ".livekit" / "agent-threads" / "default")
|
|
assert (await restored.threads.get_thread(ctx_id)).thread_id == ctx_id
|
|
await restored.aclose()
|
|
await server.storage.aclose()
|
|
|
|
|
|
def _blocking_agent(tool_entered: asyncio.Event, release: asyncio.Event) -> Agent:
|
|
front = Agent(
|
|
instructions="front desk",
|
|
llm=FakeLLM(
|
|
fake_responses=[
|
|
FakeLLMResponse(
|
|
input="first",
|
|
content="",
|
|
ttft=0,
|
|
duration=0,
|
|
tool_calls=[FunctionToolCall(name="lookup", arguments="{}", call_id="c1")],
|
|
),
|
|
FakeLLMResponse(input="found", content="never sent", ttft=0, duration=0),
|
|
FakeLLMResponse(input="second", content="both answered", ttft=0, duration=0),
|
|
]
|
|
),
|
|
)
|
|
|
|
@front.tool
|
|
async def lookup(ctx: RunContext) -> str:
|
|
"""Look the caller up."""
|
|
tool_entered.set()
|
|
await release.wait()
|
|
return "found"
|
|
|
|
return front
|
|
|
|
|
|
async def first_event(http: httpx.AsyncClient, ctx_id: str) -> tuple[str, httpx.Response]:
|
|
"""A ``message/stream`` whose first event, the task, was read; the response stays open."""
|
|
request = http.build_request(
|
|
"POST",
|
|
f"{endpoint_url(http)}/v1",
|
|
json={
|
|
"jsonrpc": "2.0",
|
|
"id": "initial",
|
|
"method": "message/stream",
|
|
"params": {"message": wire("slow", "m1", context_id=ctx_id)},
|
|
},
|
|
)
|
|
response = await http.send(request, stream=True)
|
|
async for line in response.aiter_lines():
|
|
if line.startswith("data: "):
|
|
return json.loads(line[len("data: ") :])["result"]["task"]["id"], response
|
|
raise AssertionError("the stream ended before its first event")
|
|
|
|
|
|
async def settled_task(http: httpx.AsyncClient, task_id: str, ctx_id: str) -> dict[str, Any]:
|
|
"""The task as ``tasks/get`` returns it once it is terminal."""
|
|
async with asyncio.timeout(10):
|
|
while True:
|
|
r = await rpc(http, "tasks/get", {"id": task_id, "contextId": ctx_id})
|
|
task: dict[str, Any] = r.json()["result"]
|
|
if task["status"]["state"] != "TASK_STATE_WORKING":
|
|
return task
|
|
await asyncio.sleep(0.05)
|
|
|
|
|
|
async def test_a_dropped_stream_leaves_the_task_to_get_task_not_resubscribe(
|
|
thread_storages: Workers,
|
|
) -> None:
|
|
"""docs/protocol/a2a.md: events are live only; after a disconnect, GetTask returns the
|
|
current task and its saved answer, and resubscribe is an UnsupportedOperationError."""
|
|
a, b = thread_storages
|
|
release = asyncio.Event()
|
|
|
|
async def handler(ctx: A2ASessionContext) -> str:
|
|
await ctx.update("working on it")
|
|
await release.wait()
|
|
return "done"
|
|
|
|
server_a, _ = make_server(a, handler)
|
|
server_b, _ = make_server(b, handler)
|
|
ctx_id = (await a.threads.create_thread()).thread_id
|
|
|
|
async with http_client(server_a) as http_a, http_client(server_b) as http_b:
|
|
task_id, dropped = await first_event(http_a, ctx_id)
|
|
await dropped.aclose()
|
|
r = await rpc(http_b, "tasks/resubscribe", {"id": task_id, "contextId": ctx_id})
|
|
assert r.json()["error"]["code"] == -32004
|
|
release.set()
|
|
task = await settled_task(http_b, task_id, ctx_id)
|
|
assert task["status"]["state"] == "TASK_STATE_COMPLETED"
|
|
assert task["artifacts"][0]["parts"][0]["text"] == "done"
|
|
|
|
|
|
async def test_the_turn_completes_when_the_first_client_vanishes_without_closing(
|
|
thread_storages: Workers,
|
|
) -> None:
|
|
"""A browser reload drops the response mid-turn: the response is left open and unread,
|
|
never closed. The turn must still finish and save its answer for GetTask on another
|
|
worker."""
|
|
a, b = thread_storages
|
|
release = asyncio.Event()
|
|
|
|
async def handler(ctx: A2ASessionContext) -> str:
|
|
await ctx.update("working on it")
|
|
await release.wait()
|
|
return "done"
|
|
|
|
server_a, _ = make_server(a, handler)
|
|
server_b, _ = make_server(b, handler)
|
|
ctx_id = (await a.threads.create_thread()).thread_id
|
|
|
|
async with http_client(server_a) as http_a, http_client(server_b) as http_b:
|
|
# held, never closed: a response whose client is gone without closing
|
|
task_id, held = await first_event(http_a, ctx_id)
|
|
release.set()
|
|
task = await settled_task(http_b, task_id, ctx_id)
|
|
assert task["status"]["state"] == "TASK_STATE_COMPLETED"
|
|
assert task["artifacts"][0]["parts"][0]["text"] == "done"
|
|
await held.aclose()
|
|
|
|
|
|
async def test_tasks_cancel_ends_a_running_turn_at_its_checkpoint(
|
|
thread_storage: Storage,
|
|
) -> None:
|
|
entered, release = asyncio.Event(), asyncio.Event()
|
|
front = _blocking_agent(entered, release)
|
|
|
|
async def handler(ctx: A2ASessionContext) -> RunResult[str]:
|
|
return await front.run(ctx.message, message_history=ctx.message_history)
|
|
|
|
server, _ = make_server(thread_storage, handler)
|
|
ctx_id = (await thread_storage.threads.create_thread()).thread_id
|
|
async with http_client(server) as http:
|
|
running = asyncio.create_task(
|
|
rpc(http, "message/stream", {"message": wire("first", "m1", context_id=ctx_id)})
|
|
)
|
|
await asyncio.wait_for(entered.wait(), 5)
|
|
listed = (await rpc(http, "tasks/list", {"contextId": ctx_id})).json()["result"]["tasks"]
|
|
(task,) = listed
|
|
assert task["status"]["state"] == "TASK_STATE_WORKING"
|
|
canceled = await rpc(
|
|
http,
|
|
"tasks/cancel",
|
|
{
|
|
"id": task["id"],
|
|
"contextId": ctx_id,
|
|
"metadata": {f"{EXTENSION_URI}/reason": "user_interrupted"},
|
|
},
|
|
)
|
|
assert canceled.json()["result"]["status"]["state"] == "TASK_STATE_CANCELED"
|
|
release.set()
|
|
response = await running
|
|
results = [r["result"] for r in sse_results(response)]
|
|
final = results[-1]["statusUpdate"]
|
|
assert final["status"]["state"] == "TASK_STATE_CANCELED"
|
|
# a client's cancel, not the server's interrupt
|
|
assert INTERRUPTED not in final.get("metadata", {})
|
|
assert final["metadata"][REASON] == "user_interrupted"
|
|
|
|
|
|
# ---------------------------------------------------------------------------------------------
|
|
# the session grant at the endpoint (plan 4.3.2)
|
|
# ---------------------------------------------------------------------------------------------
|
|
|
|
|
|
def grant_token(scope: str, **flags: bool) -> str:
|
|
flags = flags or {"create": True, "write": True, "read": True, "list": True}
|
|
return CREDENTIALS.thread_grant_token(AgentThreadGrant(scope=scope, **flags))
|
|
|
|
|
|
def test_a_thread_grant_names_its_caller_and_its_threads() -> None:
|
|
"""A thread grant verifies as the grant it carries; one naming neither a scope nor a thread
|
|
is refused."""
|
|
principal = CREDENTIALS.verify(grant_token("user:bob"), agent_name=AGENT)
|
|
assert principal.kind == "grant" and principal.grant is not None
|
|
assert principal.grant.scope == "user:bob" and principal.grant.write
|
|
with pytest.raises(Unauthorized):
|
|
CREDENTIALS.verify(grant_token("", write=True), agent_name=AGENT)
|
|
# the checks, as protocol's: scope covers create and list, ids or all cover a thread,
|
|
# update needs all
|
|
thread = ThreadInfo(
|
|
thread_id="AT_1",
|
|
scope="user:bob",
|
|
attributes={},
|
|
created_at=0,
|
|
last_active=0,
|
|
expires_at=0,
|
|
idle_ttl_seconds=0,
|
|
)
|
|
listed = AgentThreadGrant(thread_ids=("AT_1",), read=True)
|
|
assert listed.can_read(thread) and not listed.can_write(thread)
|
|
assert not listed.can_create("user:bob")
|
|
scoped = AgentThreadGrant(scope="user:bob", create=True, write=True)
|
|
assert scoped.can_create("user:bob") and not scoped.can_create("user:x")
|
|
assert scoped.can_write(thread)
|
|
everything = AgentThreadGrant(all=True, create=True, write=True)
|
|
assert not everything.can_create("user:x") and everything.can_write(thread)
|
|
|
|
|
|
async def test_a_delegation_part_and_kind_reach_the_handler(
|
|
thread_storage: Storage,
|
|
) -> None:
|
|
seen: dict[str, Any] = {}
|
|
|
|
async def handler(ctx: A2ASessionContext) -> str:
|
|
seen["caller_history"] = ctx.caller_history
|
|
seen["channel"] = ctx.messages[0].channel
|
|
seen["parts"] = ctx.messages[0].parts
|
|
return "ok"
|
|
|
|
server, _ = make_server(thread_storage, handler)
|
|
from google.protobuf import json_format
|
|
|
|
# a2a.md#conversation-data-part: the narrower schema, not the stored chat context's
|
|
history = {
|
|
"items": [
|
|
{
|
|
"id": "i1",
|
|
"type": "message",
|
|
"role": "user",
|
|
"content": ["earlier"],
|
|
"created_at": 1.0,
|
|
}
|
|
]
|
|
}
|
|
msg = {
|
|
"messageId": "m1",
|
|
"role": "ROLE_USER",
|
|
"parts": [
|
|
{"text": "what is the fare"},
|
|
{"data": history, "metadata": {KIND: KIND_CHAT_CTX}},
|
|
],
|
|
"metadata": {KIND: "delegation"},
|
|
}
|
|
async with http_client(server) as http:
|
|
client = await stock_client(http, extensions=EXTENSION_URI)
|
|
events = await send(client, json_format.ParseDict(msg, pb.Message()))
|
|
await client.close()
|
|
assert payloads(events)[-1].status.state == pb.TaskState.TASK_STATE_COMPLETED
|
|
assert seen["channel"] == "delegation"
|
|
assert seen["caller_history"] is not None
|
|
assert [i.text_content for i in seen["caller_history"].items] == ["earlier"]
|
|
# the conversation part is not the turn's text
|
|
assert seen["parts"] == [TextPart(text="what is the fare")]
|
|
|
|
|
|
async def test_a_remote_agent_with_no_token_answers_in_the_callers_thread(
|
|
thread_storage: Storage,
|
|
) -> None:
|
|
"""docs/internals/storage.md "Two brains, one thread": the fast brain's ``RemoteAgent(url)``
|
|
with no token, in a conversation on thread T, mints a grant for T and shares it; the grant
|
|
may write T, and the back office answers in T on its own partition_key. A project credential alone
|
|
(what it minted before) grants no thread: the door refuses it 403 for a message
|
|
(``door_tests.rs``)."""
|
|
from livekit.agents import _core
|
|
from livekit.agents.llm import FunctionCall
|
|
|
|
seen: dict[str, Any] = {}
|
|
|
|
async def handler(ctx: A2ASessionContext) -> str:
|
|
seen["thread"] = ctx.thread.id
|
|
return "booked"
|
|
|
|
server, _ = make_server(thread_storage, handler)
|
|
storage = server.storage
|
|
assert storage is not None
|
|
caller = await storage.threads.create_thread(scope="user:alice")
|
|
project = ("wss://agents.test", API_KEY, API_SECRET)
|
|
url = f"https://agents.test/{ENDPOINT}"
|
|
token = _core._core_remote_token(url, *project, None, caller.thread_id)
|
|
call = FunctionCall(call_id="call_1", name="desk", arguments='{"request": "book"}')
|
|
interaction = _core._core_RemoteInteraction(url, "desk", call, [], *project)
|
|
message = interaction.message({"request": "book"}, False, True, [], caller.thread_id, token)
|
|
assert message.context_id == caller.thread_id
|
|
assert token is not None
|
|
shared = CREDENTIALS.verify(token, agent_name=AGENT)
|
|
assert shared.grant is not None and shared.grant.can_write(caller)
|
|
endpoint_only = _core._core_remote_token(url, *project, None, None)
|
|
assert endpoint_only is not None
|
|
alone = CREDENTIALS.verify(endpoint_only, agent_name=AGENT)
|
|
assert alone.kind == "project" and alone.grant is None
|
|
async with http_client(server) as http:
|
|
sent = wire("book", message.message_id, context_id=message.context_id, kind="delegation")
|
|
r = await rpc(http, "message/send", {"message": sent}, Authorization=f"Bearer {token}")
|
|
assert r.status_code == 200, r.text
|
|
task = r.json()["result"]["task"]
|
|
assert (task["contextId"], task["status"]["state"]) == (
|
|
caller.thread_id,
|
|
"TASK_STATE_COMPLETED",
|
|
)
|
|
assert seen["thread"] == caller.thread_id
|
|
|
|
|
|
async def test_a_storage_error_mid_turn_fails_the_task_storage_unavailable(
|
|
thread_storages: Workers,
|
|
) -> None:
|
|
"""docs/protocol/a2a.md: the turn's save could not be written; the task fails with the reason, and
|
|
the client resends."""
|
|
a, _ = thread_storages
|
|
|
|
async def handler(ctx: A2ASessionContext) -> str:
|
|
raise StorageUnavailable("the database went away")
|
|
|
|
server, _ = make_server(a, handler)
|
|
ctx_id = (await a.threads.create_thread()).thread_id
|
|
async with http_client(server) as http:
|
|
r = await rpc(http, "message/send", {"message": wire("hi", "m1", context_id=ctx_id)})
|
|
task = r.json()["result"]["task"]
|
|
assert task["status"]["state"] == "TASK_STATE_FAILED"
|
|
reason = task["status"]["message"]["metadata"][REASON]
|
|
assert reason == "storage-unavailable"
|
|
|
|
|
|
async def test_each_request_runs_in_its_own_application_context(thread_storage: Storage) -> None:
|
|
"""A handler runs in a copy of the context the server started in: what one request sets is
|
|
not what the next one sees."""
|
|
import contextvars
|
|
|
|
label = contextvars.ContextVar("request-label", default="missing")
|
|
seen: list[str] = []
|
|
|
|
async def handler(ctx: A2ASessionContext) -> str:
|
|
seen.append(label.get())
|
|
label.set(ctx.message.text_content or "")
|
|
return label.get()
|
|
|
|
server, _ = make_server(thread_storage, handler)
|
|
token = label.set("server")
|
|
try:
|
|
async with http_client(server) as http:
|
|
for value in ("first", "second"):
|
|
result = await rpc(http, "message/send", {"message": wire(value, value)})
|
|
assert result.json()["result"]["task"]["artifacts"][0]["parts"][0]["text"] == value
|
|
finally:
|
|
label.reset(token)
|
|
assert seen == ["server", "server"]
|
|
|
|
|
|
# Catches: a fast brain's call to its slow brain starting a new trace at the endpoint.
|
|
async def test_the_turn_continues_the_callers_trace(thread_storage: Storage) -> None:
|
|
from opentelemetry import trace
|
|
|
|
seen: list[int] = []
|
|
|
|
async def handler(ctx: A2ASessionContext) -> str:
|
|
seen.append(trace.get_current_span().get_span_context().trace_id)
|
|
return "ok"
|
|
|
|
server, _ = make_server(thread_storage, handler)
|
|
traceparent = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"
|
|
async with http_client(server) as http:
|
|
await rpc(http, "message/send", {"message": wire("hello", "m1")}, traceparent=traceparent)
|
|
assert seen == [0x0AF7651916CD43DD8448EB211C80319C]
|
|
|
|
|
|
async def test_application_typed_output_crosses_the_native_door(thread_storage: Storage) -> None:
|
|
from pydantic import BaseModel
|
|
|
|
class Answer(BaseModel):
|
|
reservation: str
|
|
|
|
async def handler(ctx: A2ASessionContext) -> Answer:
|
|
return Answer(reservation="R42")
|
|
|
|
server, _ = make_server(thread_storage, handler)
|
|
async with http_client(server) as http:
|
|
response = await rpc(http, "message/send", {"message": wire("book", "typed")})
|
|
task = response.json()["result"]["task"]
|
|
assert task["status"]["state"] == "TASK_STATE_COMPLETED"
|
|
assert task["artifacts"][0]["parts"][0]["data"] == {"reservation": "R42"}
|
|
|
|
|
|
async def test_handler_transitions_answer_the_task(thread_storage: Storage) -> None:
|
|
from livekit.agents import Completed, Failed
|
|
|
|
async def handler(ctx: A2ASessionContext) -> Completed[str] | Failed:
|
|
if ctx.message.text_content == "fail":
|
|
return Failed("no room on that date")
|
|
return Completed("booked")
|
|
|
|
server, _ = make_server(thread_storage, handler)
|
|
async with http_client(server) as http:
|
|
done = (await rpc(http, "message/send", {"message": wire("book", "ok")})).json()
|
|
failed = (await rpc(http, "message/send", {"message": wire("fail", "no")})).json()
|
|
done_task, failed_task = done["result"]["task"], failed["result"]["task"]
|
|
assert done_task["status"]["state"] == "TASK_STATE_COMPLETED"
|
|
assert done_task["artifacts"][0]["parts"][0]["text"] == "booked"
|
|
assert failed_task["status"]["state"] == "TASK_STATE_FAILED"
|
|
|
|
|
|
async def test_payload_budget_refuses_before_durable_receipt(thread_storage: Storage) -> None:
|
|
calls = 0
|
|
|
|
async def handler(ctx: A2ASessionContext) -> str:
|
|
nonlocal calls
|
|
calls += 1
|
|
return "unexpected"
|
|
|
|
server, endpoint = make_server(thread_storage, handler)
|
|
native = endpoint._door()
|
|
async with http_client(server) as http:
|
|
response = await http.post(
|
|
f"{endpoint_url(http)}/v1", content=b" " * (native.max_payload_bytes + 1)
|
|
)
|
|
assert response.json()["error"]["code"] == -32602
|
|
assert calls == 0
|
|
assert (await thread_storage.threads.list_threads("console")).threads == []
|
|
|
|
|
|
async def test_delegation_partition_reentry_fails_before_task_admission(
|
|
thread_storage: Storage,
|
|
) -> None:
|
|
from livekit.agents._generated.a2a_metadata import PARTITION_CHAIN_KEY
|
|
from livekit.agents.storage import DEFAULT_PARTITION_KEY
|
|
|
|
entered = False
|
|
|
|
async def handler(ctx: A2ASessionContext) -> str:
|
|
nonlocal entered
|
|
entered = True
|
|
return "unexpected"
|
|
|
|
server, _ = make_server(thread_storage, handler)
|
|
thread_id = (await thread_storage.threads.create_thread()).thread_id
|
|
caller = {
|
|
"storage_location": thread_storage._core.location,
|
|
"storage_project": thread_storage._core.project_id,
|
|
"thread_id": thread_id,
|
|
"partition_key": DEFAULT_PARTITION_KEY,
|
|
}
|
|
async with http_client(server) as http:
|
|
response = await rpc(
|
|
http,
|
|
"message/send",
|
|
{
|
|
"message": wire(
|
|
"delegate",
|
|
"reentry",
|
|
context_id=thread_id,
|
|
**{PARTITION_CHAIN_KEY: [caller]},
|
|
)
|
|
},
|
|
)
|
|
assert "partition_key" in response.text and "re-enter" in response.text
|
|
assert not entered
|
|
core = await thread_storage._open(thread_id)
|
|
try:
|
|
assert not await core.tasks(DEFAULT_PARTITION_KEY, limit=10)
|
|
assert not await core.inbox(DEFAULT_PARTITION_KEY, pending=True)
|
|
finally:
|
|
core.close()
|