Skip to content

Hub & Identity

The hub is the network's single source of truth: registry, audit log, channel table, write-ahead logs, expectation evaluators, sweepers. Every send, observation, and rule check goes through it.

This page covers the registry-side primitives — what you stand up before any agent connects.

Hub.open#

1
2
3
4
5
6
7
8
9
from ag2.knowledge import MemoryKnowledgeStore
from ag2.network import Hub

hub = await Hub.open(
    MemoryKnowledgeStore(),
    ttl_sweep_interval=30.0,        # default: 30s
    expectation_sweep_interval=10.0,# default: 10s
    invite_ack_timeout=30.0,        # default: 30s
)
Parameter Type Description
store KnowledgeStore Persistent backing for the audit log, registry, and WAL. MemoryKnowledgeStore for in-process; DiskKnowledgeStore(path) for durability across restarts.
auth AuthRegistry | None Authentication adapters. Defaults to AuthRegistry.default() (which has NoAuth only).
clock Callable[[], str] | None ISO-8601 clock. Tests override with a MockClock; production uses the default UTC clock.
ttl_sweep_interval float How often the TTL sweeper walks active channels. Set to 0 to disable.
expectation_sweep_interval float How often the expectation sweeper checks declared expectations. Set to 0 to disable.
invite_ack_timeout float Per-channel ack window before the hub auto-closes.

Hub.open(...) is the factory; the constructor Hub(...) exists but doesn't start sweepers. Use open() unless you have a reason not to.

Note

All side effects (sweeper tasks, store initialisation) happen inside Hub.open(), never in the constructor — this matches the AGENTS.md "no side effects in __init__" rule. The same pattern applies throughout the package.

Identity Model#

Three small dataclasses describe an agent on the network:

from ag2.network import Passport, Resume, ResumeExample

passport = Passport(
    name="alice",
    owner="acme",
    model="claude-sonnet-5",
)

resume = Resume(
    claimed_capabilities=["analysis", "policy"],
    domains=["finance"],
    summary="Senior policy analyst — scenario synthesis and rebuttal review.",
    examples=[ResumeExample(title="Q3 risk brief", note="…")],
)

Passport — stable identity#

Field Required Notes
name ✓ Unique within the hub. The human-readable handle.
agent_id hub-stamped Issued by the hub at registration; use this for routing.
owner optional Tenant id for multi-tenant deployments.
model optional Free-form model identifier; surfaces on peer-lookup results when peer discovery ships.
kind optional One of "agent", "human", "remote_agent", or None. None is the back-compat alias for "agent". "human" is set automatically by hc.register_human(...); "remote_agent" is reserved for a future federation / A2A bridge. __post_init__ rejects any other value. Exported as PassportKind / PASSPORT_KINDS.
created_at hub-stamped ISO-Z timestamp.

hub.list_agents(kind=...) filters the registry by participant kind — kind="human" returns only humans, kind="agent" returns agents (and matches kind=None passports), kind=None returns everything. Non-LLM participants are registered via hc.register_human(...) — see HumanClient (HITL).

Resume — capability claims and observed track record#

Field Source Notes
claimed_capabilities tenant Free-form capability strings (e.g. "research", "summarisation").
domains tenant Coarse subject-matter areas.
summary tenant One-line description, indexed for peer lookup.
examples tenant Optional ResumeExample records — exemplar past work.
observed hub-mutated Per-capability ObservedStat: counts of completed/failed/expired tasks plus a p50_latency_ms. Updated automatically when an agent runs a capability-tagged Task(...) inside a network turn — see Task Observation.
last_updated hub-stamped ISO-Z, refreshed on every mutation.

Resume is the agent's network "CV" — both what it claims to do and what the hub has observed it actually doing.

Rule — per-agent governance#

Optional per-agent policy. Pass to hub.register(agent, passport, resume, rule=...).

from ag2.network import Rule, AccessBlock, ChannelTypeAccess, LimitsBlock, RateBlock, InboxBlock

rule = Rule(
    access=AccessBlock(
        outbound_to=["bob", "carol"],   # whitelist who this agent can address
        channel_types=ChannelTypeAccess(
            initiate=["consulting", "discussion"],
            accept=["consulting", "discussion"],
        ),
    ),
    limits=LimitsBlock(
        channel_ttl_default="4h",
        delegation_depth=2,
        rate=RateBlock(per_minute=60),
        inbox=InboxBlock(max_pending=100),
    ),
)
Block Controls
AccessBlock Who this agent can address (outbound_to) and who can address it (inbound_from); channel-type allowlists (channel_types, stored only).
LimitsBlock Default TTLs for channels this agent creates; max delegation depth.
RateBlock Rate-limit configuration stored under limits.rate; not enforced by the in-process hub.
InboxBlock Inbound queue cap under limits.inbox — protects an agent from being flooded.

AccessBlock.channel_types uses separate allowlists for initiating and accepting channels; like RateBlock, it is stored on the rule but not enforced by the in-process hub yet. RateBlock and InboxBlock belong inside LimitsBlock, not directly on Rule. Setting RateBlock.per_minute stores the configuration; it does not enable throttling in the in-process hub.

When a rule's check fails, the hub raises AccessDeniedError (deny by access) or InboxFull (queue cap) instead of letting the envelope through.

Authentication#

Authentication decides whether a participant may register under the name in its passport. By default the hub accepts everyone: Hub.open(store) uses AuthRegistry.default(), which holds only NoAuth. That is fine while every agent runs inside your own process, because the hub then holds only agents your code created.

Turn authentication on once other processes can connect to the hub. Over the network, NoAuth lets any client act as any agent, so serve_ws refuses to bind a hub that still accepts it to a non-loopback address — see Distributed Networks.

How it fits together#

Authentication has two halves:

  • The hub is opened with an AuthRegistry — a list of adapters. Each adapter handles one scheme, a short string such as "api_key".
  • Each agent presents a credential in its passport: Passport(auth=AuthBlock(scheme=..., claim=...)). The scheme names the adapter that should check it; the claim is the credential itself, a dict whose shape that adapter defines.

At registration the hub looks up the adapter for passport.auth.scheme and calls its validate(passport, claim). If the adapter raises AuthError, or no adapter is registered for that scheme, hub.register(...) raises AuthError and the agent is not registered.

A passport built without auth= carries AuthBlock(), whose scheme is "none" — the scheme NoAuth handles. That is why plain registration works on a default hub, and why it is rejected once NoAuth is gone.

API keys#

ApiKeyAuth is the built-in adapter: each agent name has one secret token. Configure the tokens on the hub, and have each agent send its own token as {"token": ...}:

import os

from ag2 import Agent
from ag2.knowledge import MemoryKnowledgeStore
from ag2.network import ApiKeyAuth, AuthBlock, AuthRegistry, Hub, Passport

auth = AuthRegistry([ApiKeyAuth(keys={"alice": os.environ["ALICE_API_KEY"]})])
hub = await Hub.open(MemoryKnowledgeStore(), auth=auth)

alice = await hub.register(
    Agent("alice"),
    passport=Passport(
        name="alice",
        auth=AuthBlock(scheme="api_key", claim={"token": os.environ["ALICE_API_KEY"]}),
    ),
)

Lines 7–8 are the hub's side: keys maps a passport name to the token expected for it. Lines 12–15 are the agent's side. Both run in one process here to keep the example short; in a real deployment the agent registers from another process through a HubClient and reads its token from its own configuration.

Registration fails with AuthError when the token is wrong, when the name has no key, or when the passport has no api_key credential at all — for example await hub.register(Agent("bob")) on this hub raises AuthError: unknown auth scheme: 'none'.

When tokens live in a secret manager or a database, pass an async resolver instead of (or in addition to) keys. It receives the passport name and returns the expected token, or None for an unknown name; keys is checked first:

1
2
3
4
5
6
7
8
9
import os

from ag2.network import ApiKeyAuth, AuthRegistry

async def lookup_api_key(name: str) -> str | None:
    # Replace with a call to your secret store.
    return os.environ.get(f"{name.upper()}_API_KEY")

auth = AuthRegistry([ApiKeyAuth(resolver=lookup_api_key)])

Mixing authenticated and open registration#

A registry may hold several adapters, and each agent picks one through its passport's scheme. To keep accepting agents without credentials alongside API-key agents, add NoAuth():

1
2
3
from ag2.network import ApiKeyAuth, AuthRegistry, NoAuth

auth = AuthRegistry([NoAuth(), ApiKeyAuth(keys={"alice": "..."})])

Note that with NoAuth present, any client can still register under any name the API keys don't cover, and serve_ws treats the hub as unauthenticated.

Writing a custom adapter#

Write your own adapter when agents already hold credentials from another system — for example, JWTs issued by your identity provider. An adapter is any class with a scheme attribute and an async validate(passport, claim) method; it satisfies the AuthAdapter protocol structurally, with no base class.

This adapter accepts agents that present a JWT signed by your identity provider. It uses PyJWT (pip install "pyjwt[crypto]") to check the signature, expiry and audience:

from typing import Any

import jwt

from ag2.network import AuthError, AuthRegistry, Passport

class JwtAuth:
    scheme = "jwt"

    def __init__(self, public_key: str, audience: str) -> None:
        self._public_key = public_key
        self._audience = audience

    async def validate(self, passport: Passport, claim: dict[str, Any]) -> None:
        try:
            payload = jwt.decode(
                claim.get("token", ""),
                self._public_key,
                algorithms=["RS256"],
                audience=self._audience,
            )
        except jwt.InvalidTokenError as exc:
            raise AuthError(f"invalid token for {passport.name!r}") from exc
        if payload.get("sub") != passport.name:
            raise AuthError(f"token was not issued to {passport.name!r}")

auth = AuthRegistry([JwtAuth(public_key=IDP_PUBLIC_KEY, audience="ag2-hub")])

IDP_PUBLIC_KEY stands for your identity provider's public key, loaded from configuration. The hub only verifies tokens and never holds a signing secret. Each agent registers with the token it got from the provider:

passport = Passport(name="alice", auth=AuthBlock(scheme="jwt", claim={"token": alice_jwt}))

What the example shows, and what any adapter needs to get right:

  • Return None to accept, raise AuthError to reject. Turn your library's errors into AuthError, as the except block does. The message reaches the client, so don't put secrets in it.
  • Tie the credential to the passport. A valid token proves only that its holder is somebody. The sub check is what stops Alice's token from registering an agent named bob. Whatever your credential identifies (a subject, a tenant, a certificate), compare it to passport.name or passport.owner.
  • Read the credential from claim, not from passport.auth.claim. The hub doesn't store credentials. When a remote agent reconnects with attach, the hub calls validate again with the stored passport, whose claim is empty, and passes the newly sent credential in claim. The reconnect must use the scheme the agent registered with.
  • Leave the cryptography to a library. Verifying signatures, expiry and audience is the library's job. Your adapter maps its result onto the hub's identity.

Audit Log#

Every governance-relevant event the hub processes lands in hub.audit_log (an AuditLog, which is itself a registered HubListener):

1
2
3
records = await hub.audit_log.read_all()
for r in records:
    print(r["kind"], r["at"], r)

Audit kinds (re-exported from ag2.network):

Kind When
AUDIT_KIND_AGENT_REGISTERED hub.register(...)
AUDIT_KIND_AGENT_UNREGISTERED hc.unregister(...)
AUDIT_KIND_RESUME_SET hub.set_resume(...)
AUDIT_KIND_SKILL_SET hub.set_skill(...)
AUDIT_KIND_RULE_SET hub.set_rule(...)
AUDIT_KIND_CHANNEL_CREATED alice.open(...)
AUDIT_KIND_CHANNEL_CLOSED adapter close, explicit close, or auto_close violation
AUDIT_KIND_CHANNEL_EXPIRED TTL sweep
AUDIT_KIND_TASK_TERMINATED A task observed via TaskMirror reached a terminal state
AUDIT_KIND_EXPECTATION_VIOLATED An expectation evaluator's threshold elapsed
AUDIT_KIND_TURN_FAILED A notify handler crashed while processing an inbound envelope (channel stays alive — see resilience note below)

The kind set is open — tenants and hub subclasses can write their own kinds via hub.audit_log.append(record). The audit log is the single trail for compliance and debugging — see Governance, Audit & Observability.

Reading Hub State#

Call Returns
await hub.get_channel(channel_id) ChannelMetadata snapshot.
await hub.get_resume(agent_id) Current Resume.
await hub.get_agent(name_or_id) Current Passport, looked up by name or id.
await hub.read_wal(channel_id) Ordered list of Envelopes in that channel.
hub.audit_log The AuditLog instance — await hub.audit_log.read_all() for every record, hub.audit_log.subscribe(cb) to live-tail.
hub.health() Cheap in-memory operational snapshot (active_channels, registered_agents, pending_inbox_total, max_pending_inbox_depth, registered_listeners, adapters_loaded, audit_log_bytes).

Hub TTL & Sweepers#

Two background tasks run as long as the hub is open:

  • TTL sweeper — walks active channels and expires those past created_at + ttl. Default TTL comes from Rule.limits.channel_ttl_default or the adapter's manifest.
  • Expectation sweeper — walks the expectation evaluators registered for each open channel, fires ViolationHandlers on threshold breach.

Both are tunable via ttl_sweep_interval and expectation_sweep_interval. Set to 0 to disable for tests; in those cases call await hub._ttl_tick() or await hub._expectation_tick() manually for deterministic timing.

Custom sweepers#

Attach your own periodic worker — protocol-specific background work like polling a chat platform's presence list or refreshing an auth token:

1
2
3
4
5
6
async def heartbeat() -> None:
    ...  # runs every 30s

hub.register_sweeper("heartbeat", 30.0, heartbeat)
# later, e.g. on a config reload:
await hub.unregister_sweeper("heartbeat")
  • register_sweeper(name, interval_seconds, fn) is synchronous (it only updates bookkeeping). If the hub has already started (Hub.open(...) calls start() for you), the sweeper begins immediately; if you registered it before start(), it begins then.
  • unregister_sweeper(name) is async — it awaits clean cancellation of the running task. Unknown names are a no-op.
  • A duplicate name raises ValueError (call unregister_sweeper first to replace); a non-positive interval raises ValueError.
  • hub.close() stops every custom sweeper automatically — you don't need to track them yourself.

Closing Down#

await hub.close()

Cancels all sweeper tasks, closes the underlying store, drains pending I/O. Always pair Hub.open(...) with hub.close() (typically in a try/finally).