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#
| 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:
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=...).
| 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=...)). Theschemenames the adapter that should check it; theclaimis 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": ...}:
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:
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():
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:
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:
What the example shows, and what any adapter needs to get right:
- Return
Noneto accept, raiseAuthErrorto reject. Turn your library's errors intoAuthError, as theexceptblock 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
subcheck is what stops Alice's token from registering an agent namedbob. Whatever your credential identifies (a subject, a tenant, a certificate), compare it topassport.nameorpassport.owner. - Read the credential from
claim, not frompassport.auth.claim. The hub doesn't store credentials. When a remote agent reconnects withattach, the hub callsvalidateagain with the stored passport, whose claim is empty, and passes the newly sent credential inclaim. 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):
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 fromRule.limits.channel_ttl_defaultor 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:
register_sweeper(name, interval_seconds, fn)is synchronous (it only updates bookkeeping). If the hub has already started (Hub.open(...)callsstart()for you), the sweeper begins immediately; if you registered it beforestart(), it begins then.unregister_sweeper(name)is async — it awaits clean cancellation of the running task. Unknown names are a no-op.- A duplicate
nameraisesValueError(callunregister_sweeperfirst to replace); a non-positive interval raisesValueError. hub.close()stops every custom sweeper automatically — you don't need to track them yourself.
Closing Down#
Cancels all sweeper tasks, closes the underlying store, drains pending I/O. Always pair Hub.open(...) with hub.close() (typically in a try/finally).