378 lines
17 KiB
Python
378 lines
17 KiB
Python
"""Registry + self-registration over HTTP."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import json
|
||
|
||
from tests.conftest import BASE, add_agent, mock_agent, register
|
||
|
||
|
||
def test_meta_advertises_the_plugin_surface(hub):
|
||
meta = hub.get(f"{BASE}/meta").json()
|
||
assert meta["app"] == "AgentHub"
|
||
# 驱动、类型、接入方式、部署形态都只由 /meta 下发(控制台不再各存一份硬编码副本)
|
||
assert {"mock", "nanobot", "openclaw", "connector", "openai_compatible"} <= {
|
||
item["name"] for item in meta["drivers"]
|
||
}
|
||
assert {"sequential", "parallel", "round_robin", "handoff"} == {item["name"] for item in meta["playbooks"]}
|
||
assert set(meta["agent_types"]) == {"nanobot", "deepseek_harness", "openclaw", "hermes"}
|
||
assert set(meta["connection_modes"]) == {"direct", "connector", "embedded"}
|
||
assert meta["deployment_kinds"] == ["local", "docker", "cloud"]
|
||
assert "driver_names" not in meta, "裸名字列表是 drivers 的重复副本,已删除"
|
||
|
||
|
||
def test_issue_a_credential_then_the_agent_dials_in(hub):
|
||
offer = register(
|
||
hub,
|
||
"nanobot-laptop",
|
||
driver="nanobot",
|
||
connection_mode="connector",
|
||
deployment_kind="local",
|
||
labels={"env": "dev"},
|
||
)
|
||
agent_id, token = offer["agent_id"], offer["agent_token"]
|
||
assert token.startswith("ag_")
|
||
|
||
agent = hub.get(f"{BASE}/agents/{agent_id}").json()
|
||
# 签发凭证 ≠ 上线:档案是控制台建的,状态得等 Agent 真的拨进来再说
|
||
assert agent["status"] == "unknown" and agent["source"] == "manual"
|
||
assert agent["labels"] == {"env": "dev"} and agent["connection_mode"] == "connector"
|
||
|
||
beat = hub.post(
|
||
f"{BASE}/gateway/heartbeat",
|
||
json={"status": "online", "active_tasks": 1, "health": {"queue": 0}},
|
||
headers={"Authorization": f"Bearer {token}"},
|
||
)
|
||
assert beat.status_code == 200
|
||
back = hub.get(f"{BASE}/agents/{agent_id}").json()
|
||
assert back["active_tasks"] == 1 and back["status"] == "online"
|
||
|
||
assert hub.post(f"{BASE}/gateway/deregister", headers={"Authorization": f"Bearer {token}"}).status_code == 200
|
||
assert hub.get(f"{BASE}/agents/{agent_id}").json()["status"] == "offline"
|
||
|
||
|
||
def test_a_status_only_beat_does_not_erase_what_the_agent_reported(hub):
|
||
"""SDK 的 REST 探针只带 status,hub 不能因此把自省清空。
|
||
|
||
cli-bridge 每轮心跳成对发:WS 那条带 capabilities/health(host、workdir、model),
|
||
紧跟一条 REST「还认我不」只带 status —— 早期 heartbeat() 把两个空字典当新值写回,
|
||
于是 hub 上 agent 的能力每 15 秒被抹平一次。
|
||
"""
|
||
token = register(hub, "cli-worker", driver="connector")["agent_token"]
|
||
auth = {"Authorization": f"Bearer {token}"}
|
||
hub.post(
|
||
f"{BASE}/gateway/heartbeat",
|
||
json={"status": "online", "capabilities": {"cli": "workbuddy", "host": "mac-1"}, "health": {"uptime_s": 3}},
|
||
headers=auth,
|
||
)
|
||
hub.post(f"{BASE}/gateway/heartbeat", json={"status": "online", "active_tasks": 0}, headers=auth)
|
||
|
||
agent = hub.get(f"{BASE}/agents/cli-worker").json()
|
||
assert agent["capabilities"] == {"cli": "workbuddy", "host": "mac-1"}
|
||
assert agent["health"] == {"uptime_s": 3}
|
||
assert agent["active_tasks"] == 0 # 探针自己带的字段照旧生效
|
||
|
||
|
||
def test_the_old_self_registration_routes_are_gone(hub):
|
||
"""接入只剩「地址 + 凭证」一条路,换身份的入口全部 404。"""
|
||
for route in ("/gateway/register", "/gateway/join", "/enrollment", "/meta/hub-id"):
|
||
assert hub.post(f"{BASE}{route}", json={}).status_code == 404, route
|
||
|
||
|
||
def test_an_agent_can_report_the_hub_url_it_can_reach(hub):
|
||
"""The address the hub listens on is not the address an agent can dial it on.
|
||
|
||
A connector only ever dials one URL, so whatever it registered through is the
|
||
URL to advertise back to that agent (a container cannot reach 127.0.0.1).
|
||
"""
|
||
add_agent(hub, "dockerized", driver="mock", config={"hub_url": "http://host.docker.internal:8100"})
|
||
agent = hub.get(f"{BASE}/agents/dockerized").json()
|
||
assert agent["config"]["hub_url"] == "http://host.docker.internal:8100"
|
||
|
||
|
||
def test_manual_registration_can_issue_the_agents_own_credential(hub):
|
||
"""A hand-registered agent that dials out needs a credential; hand it out."""
|
||
agent = add_agent(
|
||
hub,
|
||
"manual-outbound",
|
||
driver="nanobot",
|
||
connection_mode="embedded",
|
||
issue_credential=True,
|
||
)
|
||
token = agent["agent_token"]
|
||
assert token.startswith("ag_")
|
||
assert agent["credential"]["installed"] is True
|
||
assert agent["credential"]["preview"].startswith("ag_")
|
||
assert agent["credential"]["viewable"] is True
|
||
assert hub.get(f"{BASE}/agents/manual-outbound/credentials").json()["agent_token"] == token
|
||
|
||
beat = hub.post(
|
||
f"{BASE}/gateway/heartbeat",
|
||
json={"status": "online"},
|
||
headers={"Authorization": f"Bearer {token}"},
|
||
)
|
||
assert beat.status_code == 200
|
||
|
||
# The same credential opens the outbound socket channel the plugin/channel uses.
|
||
with hub.websocket_connect(f"{BASE}/gateway/ws?agent_token={token}") as socket:
|
||
assert socket.receive_json()["kind"] == "hub.hello"
|
||
|
||
|
||
def test_rotating_a_credential_kills_the_previous_one(hub):
|
||
agent = add_agent(hub, "rotator", driver="nanobot", connection_mode="embedded", issue_credential=True)
|
||
old = agent["agent_token"]
|
||
|
||
rotated = hub.post(f"{BASE}/agents/{agent['id']}/credentials", json={})
|
||
assert rotated.status_code == 201
|
||
new = rotated.json()["agent_token"]
|
||
assert new.startswith("ag_") and new != old
|
||
|
||
assert (
|
||
hub.post(f"{BASE}/gateway/heartbeat", json={}, headers={"Authorization": f"Bearer {new}"}).status_code
|
||
== 200
|
||
)
|
||
assert (
|
||
hub.post(f"{BASE}/gateway/heartbeat", json={}, headers={"Authorization": f"Bearer {old}"}).status_code
|
||
in (401, 403)
|
||
)
|
||
|
||
|
||
def test_plaintext_credentials_never_come_back_from_reads(hub):
|
||
agent = add_agent(hub, "secretive", driver="nanobot", connection_mode="embedded", issue_credential=True)
|
||
token = agent["agent_token"]
|
||
|
||
detail = hub.get(f"{BASE}/agents/{agent['id']}").json()
|
||
listing = hub.get(f"{BASE}/agents").json()
|
||
assert "agent_token" not in detail and "agent_token" not in listing[0]
|
||
assert detail["credential"]["installed"] is True
|
||
assert token not in json.dumps(detail) and token not in json.dumps(listing)
|
||
|
||
|
||
def _beat(hub, token: str):
|
||
return hub.post(f"{BASE}/gateway/heartbeat", json={}, headers={"Authorization": f"Bearer {token}"})
|
||
|
||
|
||
def test_rotation_grace_window_keeps_both_credentials_working_until_it_closes(hub):
|
||
"""A rolling restart must not drop the agent: the old credential has a window."""
|
||
agent = add_agent(hub, "graceful", driver="nanobot", connection_mode="embedded", issue_credential=True)
|
||
old = agent["agent_token"]
|
||
|
||
rotated = hub.post(f"{BASE}/agents/{agent['id']}/credentials", json={"grace_seconds": 30}).json()
|
||
new = rotated["agent_token"]
|
||
assert _beat(hub, new).status_code == 200
|
||
assert _beat(hub, old).status_code == 200 # still inside the grace window
|
||
|
||
# A later rotation without a window closes it and kills the old credential.
|
||
assert hub.post(f"{BASE}/agents/{agent['id']}/credentials", json={}).status_code == 201
|
||
assert _beat(hub, old).status_code in (401, 403)
|
||
assert hub.post(f"{BASE}/agents/{agent['id']}/credentials", json={"grace_seconds": -1}).status_code == 400
|
||
|
||
|
||
def test_role_is_a_hub_side_field_not_something_the_agent_configures(hub):
|
||
"""An agent may claim anything; the role still comes from the hub side."""
|
||
"""角色只由控制台写,Agent 侧的心跳改不动它。"""
|
||
offer = register(hub, "role-agent", role="editor")
|
||
agent_id = offer["agent_id"]
|
||
assert hub.get(f"{BASE}/agents/{agent_id}").json()["role"] == "editor"
|
||
|
||
hub.post(
|
||
f"{BASE}/gateway/heartbeat",
|
||
json={"role": "writer", "status": "online"},
|
||
headers={"Authorization": f"Bearer {offer['agent_token']}"},
|
||
)
|
||
assert hub.get(f"{BASE}/agents/{agent_id}").json()["role"] == "editor"
|
||
|
||
hub.patch(f"{BASE}/agents/{agent_id}", json={"role": "reviewer"})
|
||
assert hub.get(f"{BASE}/agents/{agent_id}").json()["role"] == "reviewer"
|
||
|
||
|
||
def test_model_is_self_reported_through_heartbeat_capabilities(hub):
|
||
offer = register(hub, "model-agent")
|
||
beat = hub.post(
|
||
f"{BASE}/gateway/heartbeat",
|
||
json={"capabilities": {"streaming": True, "model": "qwen3.6-plus"}},
|
||
headers={"Authorization": f"Bearer {offer['agent_token']}"},
|
||
)
|
||
assert beat.status_code == 200
|
||
agent = hub.get(f"{BASE}/agents/{offer['agent_id']}").json()
|
||
assert agent["model"] == "qwen3.6-plus"
|
||
assert agent["capabilities"]["streaming"] is True
|
||
|
||
|
||
def test_manual_agent_crud_and_filters(hub):
|
||
add_agent(hub, "researcher", driver="mock", role="researcher", labels={"team": "payments"}, emoji="🔎")
|
||
add_agent(hub, "reviewer", driver="mock", role="reviewer", labels={"team": "core"})
|
||
|
||
assert hub.get(f"{BASE}/agents?label=team%3Dpayments").json()[0]["name"] == "researcher"
|
||
assert len(hub.get(f"{BASE}/agents?driver=mock").json()) == 2
|
||
|
||
patched = hub.patch(f"{BASE}/agents/researcher", json={"role": "lead", "description": "senior"}).json()
|
||
assert patched["role"] == "lead" and patched["description"] == "senior"
|
||
|
||
assert hub.delete(f"{BASE}/agents/reviewer").status_code == 200
|
||
assert hub.get(f"{BASE}/agents/reviewer").status_code == 404
|
||
|
||
|
||
def test_probe_and_describe_use_the_driver(hub):
|
||
agent = mock_agent(hub, "mocky", reply="hi")
|
||
probe = hub.post(f"{BASE}/agents/mocky/probe").json()
|
||
assert probe["ok"] is True
|
||
assert probe["health"]["latency_ms"] >= 0
|
||
described = hub.post(f"{BASE}/agents/{agent['id']}/describe").json()
|
||
assert described["capabilities"]["streaming"] is True
|
||
assert hub.get(f"{BASE}/agents/mocky").json()["capabilities"]["models"] == ["mock-1"]
|
||
|
||
|
||
def test_unreachable_direct_agent_reports_a_failed_probe(hub):
|
||
add_agent(hub, "ghost", driver="openai_compatible", base_url="http://127.0.0.1:1")
|
||
probe = hub.post(f"{BASE}/agents/ghost/probe").json()
|
||
assert probe["ok"] is False and probe["error"]
|
||
assert hub.get(f"{BASE}/agents/ghost").json()["status"] == "offline"
|
||
|
||
|
||
def test_an_issued_credential_can_be_read_back_as_often_as_needed(hub):
|
||
"""签过的凭证要能反复回看:控制台不该为了再看一眼明文就轮换一次。
|
||
|
||
认证走的仍是哈希,库里另外存了一份 seal 过的副本(密钥是 hub 自己的
|
||
secret_key)专门给这个路由用,所以轮换之后查到的是新值;列表/详情里
|
||
仍然只有不可逆的 preview。
|
||
"""
|
||
agent = add_agent(
|
||
hub, "viewable", driver="nanobot", connection_mode="embedded", issue_credential=True
|
||
)
|
||
token = agent["agent_token"]
|
||
path = f"{BASE}/agents/viewable/credentials"
|
||
assert hub.get(path).json()["agent_token"] == token
|
||
assert hub.get(path).json()["agent_token"] == token, "同一把凭证第二次读要还是它"
|
||
|
||
rotated = hub.post(path, json={"grace_seconds": 0}).json()
|
||
assert rotated["agent_token"] != token
|
||
assert hub.get(path).json()["agent_token"] == rotated["agent_token"], "轮换之后要读到新的那把"
|
||
assert hub.get(f"{BASE}/agents/viewable").json()["credential"]["preview"] != token
|
||
|
||
|
||
def test_an_agent_without_a_credential_reads_back_empty(hub):
|
||
"""没签过凭证的 Agent:这个路由答 installed=false,而不是编一把假的出来。"""
|
||
add_agent(hub, "credential-less", driver="nanobot", connection_mode="embedded")
|
||
body = hub.get(f"{BASE}/agents/credential-less/credentials").json()
|
||
assert body["installed"] is False and body["agent_token"] == ""
|
||
|
||
|
||
def test_agent_secrets_never_leave_the_hub(hub):
|
||
add_agent(hub, "vaulted", driver="openai_compatible", base_url="http://x/v1", auth={"token": "sk-super-secret"})
|
||
body = hub.get(f"{BASE}/agents/vaulted").text
|
||
assert "sk-super-secret" not in body
|
||
assert hub.get(f"{BASE}/agents/vaulted").json()["auth"]["token"] != "sk-super-secret"
|
||
|
||
|
||
async def test_an_agent_that_comes_back_clears_the_old_error(hub):
|
||
"""A recovered connector must not keep advertising the reason it once went dark."""
|
||
from agenthub import presence
|
||
from agenthub.config import get_settings
|
||
|
||
offer = register(hub, "nanobot-flaky", driver="nanobot", connection_mode="connector")
|
||
agent_id, token = offer["agent_id"], offer["agent_token"]
|
||
hub.post(
|
||
f"{BASE}/gateway/heartbeat",
|
||
json={"status": "online"},
|
||
headers={"Authorization": f"Bearer {token}"},
|
||
)
|
||
|
||
get_settings().heartbeat_timeout_s = -1.0 # the next sweep calls it silent
|
||
await presence.sweep_once(probe_direct=False)
|
||
gone = hub.get(f"{BASE}/agents/{agent_id}").json()
|
||
assert gone["status"] == "offline" and "timeout" in gone["last_error"]
|
||
|
||
hub.post(f"{BASE}/gateway/heartbeat", json={"status": "online"},
|
||
headers={"Authorization": f"Bearer {token}"})
|
||
back = hub.get(f"{BASE}/agents/{agent_id}").json()
|
||
assert back["status"] == "online" and back["last_error"] == ""
|
||
|
||
async def test_an_embedded_agent_is_reached_over_its_socket(hub):
|
||
"""An agent that carries the client inside it still travels on the socket.
|
||
|
||
``connection_mode=embedded`` is the no-extra-process shape (nanobot loads the
|
||
agenthub channel in its own process). It must use the same outbound socket
|
||
as a connector and must never make the hub dial a base_url it cannot reach.
|
||
"""
|
||
from agenthub import presence
|
||
from agenthub.adapters import driver_for
|
||
from agenthub.config import get_settings
|
||
from agenthub.db.base import session_scope
|
||
from agenthub.services import registry
|
||
|
||
offer = register(
|
||
hub,
|
||
"nanobot-embedded",
|
||
driver="nanobot",
|
||
connection_mode="embedded",
|
||
base_url="http://127.0.0.1:1/v1", # a lie: nothing is dialable behind it
|
||
)
|
||
agent_id = offer["agent_id"]
|
||
assert hub.get(f"{BASE}/agents/{agent_id}").json()["connection_mode"] == "embedded"
|
||
hub.post(
|
||
f"{BASE}/gateway/heartbeat",
|
||
json={"status": "online"},
|
||
headers={"Authorization": f"Bearer {offer['agent_token']}"},
|
||
)
|
||
|
||
async with session_scope() as session:
|
||
row = await registry.get_agent(session, agent_id)
|
||
assert driver_for(row).name == "connector"
|
||
|
||
get_settings().heartbeat_timeout_s = -1.0 # the next sweep calls it silent
|
||
counters = await presence.sweep_once(probe_direct=True)
|
||
assert counters["expired"] == 1 and counters["probed"] == 0
|
||
agent = hub.get(f"{BASE}/agents/{agent_id}").json()
|
||
assert agent["status"] == "offline" and "connector silent" in agent["last_error"]
|
||
|
||
|
||
def test_agent_type_is_explicit_or_derived_from_the_driver(hub):
|
||
"""Four named products, one honest fallback, and no empty type anywhere."""
|
||
explicit = add_agent(hub, "dsh-1", driver="deepseek_harness", agent_type="deepseek_harness")
|
||
assert explicit["agent_type"] == "deepseek_harness"
|
||
assert add_agent(hub, "claw-1", driver="openclaw")["agent_type"] == "openclaw"
|
||
# nanobot reached through its WebSocket channel is still a nanobot
|
||
assert add_agent(hub, "ws-1", driver="nanobot_ws")["agent_type"] == "nanobot"
|
||
# a driver that is not one of the four products stays honest about it
|
||
assert add_agent(hub, "mock-1", driver="mock")["agent_type"] == "custom"
|
||
|
||
|
||
def test_driver_changes_move_a_derived_type_and_an_explicit_one_sticks(hub):
|
||
add_agent(hub, "switch-1", driver="nanobot")
|
||
moved = hub.patch(f"{BASE}/agents/switch-1", json={"driver": "openclaw"}).json()
|
||
assert moved["agent_type"] == "openclaw"
|
||
|
||
typed = hub.patch(f"{BASE}/agents/switch-1", json={"agent_type": "hermes"}).json()
|
||
assert typed["agent_type"] == "hermes"
|
||
assert [row["name"] for row in hub.get(f"{BASE}/agents?agent_type=hermes").json()] == ["switch-1"]
|
||
# ...and an explicit identity is never silently overwritten by a driver change
|
||
hub.patch(f"{BASE}/agents/switch-1", json={"driver": "nanobot"})
|
||
assert hub.get(f"{BASE}/agents/switch-1").json()["agent_type"] == "hermes"
|
||
|
||
|
||
def test_a_self_registered_deepseek_harness_lands_as_that_type(hub):
|
||
"""The dsh plugin registers itself as embedded + deepseek_harness."""
|
||
offer = register(
|
||
hub,
|
||
"dsh-2",
|
||
driver="deepseek_harness",
|
||
agent_type="deepseek_harness",
|
||
connection_mode="embedded",
|
||
)
|
||
row = hub.get(f"{BASE}/agents/{offer['agent_id']}").json()
|
||
assert row["agent_type"] == "deepseek_harness"
|
||
assert row["connection_mode"] == "embedded"
|
||
|
||
async def check() -> str:
|
||
from agenthub.adapters import driver_for
|
||
from agenthub.db.base import session_scope
|
||
from agenthub.services import registry
|
||
|
||
async with session_scope() as session:
|
||
return driver_for(await registry.get_agent(session, offer["agent_id"])).name
|
||
|
||
# embedded agents are always reached over their outbound socket
|
||
assert asyncio.run(check()) == "connector"
|