Skip to content
robolibsPublic

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

agentio

agentio is a Rust library for composing authenticated peerbus endpoints by topic name. One Agent owns one peerbus::Node, one Ed25519 identity, a local directory, and its control-plane workers. A multi-machine composition consists of several Agents that exchange signed directory records.

Model

  • A Machine is one endpoint identity and its peerbus::Node.
  • An Agent is the owning handle for that Machine's IO and directory state.
  • A topic is a normalized absolute path such as /perception/pose. Topics under /__agentio are reserved for agentio's own records.
  • qualify_participant_topic and subscribe_in provide local topic-prefix convenience. There is no participant registry or participant discovery.

Each hosted exchange is recorded with its topic, exchange family, request and response type hashes, owner endpoint, revision, lease expiry, machine name, the owner's per-start instance nonce, its dial address, its advertised QoS, optional metadata pairs, and the owner signature (directory protocol v2, see docs/decisions/007-protocol-v2-and-presence.md). Received announcements and snapshots are verified before insertion. Older revisions, expired records, invalid signatures, type mismatches, and competing live owners are rejected. Hosted records are renewed; dropping the returned Registered publisher/server handle sends a signed withdrawal bound to the exact signed record it removes, and dropping the agent withdraws everything it still hosts. Startup and periodic reconciliation recover missed announcements; reconcile_now also triggers it on demand. Snapshot pages carry a generation number, so a mutation during pagination restarts the snapshot instead of mixing two directory states.

Every agent also hosts a signed presence record. peers() lists every live agent of the composition, including agents that host no topics, with their names and metadata; a crashed agent drops out when its lease runs out. peer_named(name) and wait_for_peer(name, timeout) find an agent by its builder name, and by_name(name) dials it directly like by_id. When several live agents share a name, the one renewed last wins.

Minimal example

use agentio::{Agent, IdentitySource};
use datapod::datapod;
use std::time::Duration;

#[datapod]
struct Pose {
    x: f32,
    y: f32,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let agent = Agent::builder()
        .identity(IdentitySource::Random)
        .name("local")
        .build()?;
    let mut publisher = agent.publish::<Pose>("/pose")?;
    let mut subscriber = agent.subscribe::<Pose>("/pose")?;

    publisher.send(&Pose { x: 1.0, y: 2.0 })?;
    let sample = subscriber
        .recv_timeout(Duration::from_secs(1))?
        .ok_or("pose timed out")?;
    assert_eq!(sample.header().x, 1.0);
    Ok(())
}

Membership and authorization

Discovery and authorization are separate:

  • bootstrap([...]) configures outbound directory seeds only. A seed given as an EndpointAddr or a LocalAgent also contributes its dial address.
  • bootstrap_local(name) and allow_local(name) find a live agent on this host by builder name through its rendezvous record.
  • allow_peer(id) and allow_peers([...]) configure inbound transport access.
  • allow_any_peer() explicitly opts out of the deny-by-default allowlist.
  • revoke_peer(id) refuses a peer's new connections and closes its live ones, overriding allow_any_peer; allow_peer lifts it again.
  • restrict_topic(topic, [...]), or HostOptions::allow_only([...]) when hosting, admits only the listed peers to one topic.
  • A Trust set shares trusted peers across the agents of one process: agents join with AgentBuilder::trust(&set) or set.join(&agent), and set.allow(peer) / set.revoke(peer) apply to every live member and to agents that join later.
  • DirectoryMode::Replicated reconciles every configured seed.
  • DirectoryMode::FrontDoor(id) uses one directory authority. The front-door ID is not automatically authorized for inbound transport.

Revocation and topic rules are enforced on QUIC. Same-host shared memory is not authenticated by peerbus; use skip_shm() where co-located peers must be held to the same rules. For production, exchange endpoint IDs through a trusted channel and use explicit allowlists. allow_any_peer is appropriate only for a deliberately permissive trust boundary. An ALPN identifies a protocol; it is not a secret or an authorization mechanism. See docs/decisions/008-access-rules-and-standby.md.

Resolution and transport

A typed client first checks its verified local directory and can query a seed's reserved __agentio_resolve req/res service. It validates the returned topic, exchange family, and type hashes before dialing the owner directly. A local record of the wrong type does not stop resolution: the seeds are asked for a usable one. by_id bypasses directory resolution but not peerbus transport authorization.

Dials use every address known for the owner: explicit addresses (add_peer_addr, address-carrying seeds), the address signed into the owner's newest record, and its host-local rendezvous record. Co-located agents and seeds given by address therefore connect without iroh discovery.

Each configured directory target has one bounded worker and one persistent control client. Unreachable seeds therefore do not serialize calls to healthy seeds. control_timeout bounds the caller-visible wait; the target worker may still be completing the underlying peerbus call. lease_duration controls record expiry and the automatic renewal cadence. The defaults are six seconds for control calls and 30 seconds for leases. An agent's shared-memory services accept at least MIN_LOCAL_PRODUCERS (32) local request producers, so many co-located agents can use one seed.

Peerbus can use shared memory for co-located endpoints and iroh QUIC for remote endpoints. skip_shm() forces QUIC; no_relay() disables relay fallback. wait_for_direct_addresses provides bounded address readiness for remote setups. Rust transport type hashes include the Rust type path, so separate binaries must import shared message definitions from the same crate. The heavy and camera examples use the small examples/shared_types support crate for this reason.

Options, waiting and following

Every exchange family has a plain method and a _with variant:

  • HostOptions sets the transport QoS (advertised in the signed record), record metadata, standby() hosting and allow_only peers.
  • ClientOptions sets the QoS (by default the host's advertised one) and wait(timeout), which keeps resolving while no usable owner exists yet.
  • wait_for_topic(topic, timeout) waits for any live record of a topic.
  • subscribe_follow, req_client_follow and the other *_follow methods return a Follow handle that reopens against the current owner whenever the owner changes, restarts with a new instance, withdraws or expires.

A reader that falls behind its owner's ring skips the overwritten samples instead of failing: Follow, PrefixSubscriber and the bag Recorder keep their subscriptions and count the skipped samples in dropped().

Directory events and prefixes

  • topics(prefix) lists live records under a prefix on segment boundaries.
  • watch(prefix) streams DirectoryEvent::{Added, Updated, Withdrawn, Expired}; renewals are silent. watch_peers() does the same for presence records.
  • subscribe_prefix::<T>(prefix, options) merges every topic of type T under a prefix into one stream, adding and dropping members as they come and go.

Serving

  • serve, serve_queries and serve_uploads answer a topic on a service thread with a closure over decoded values; dropping the Service stops it and withdraws its record.
  • ServeRequests, ServeQueries and ServeUploads add serve_pending and serve_timeout to hosted servers for callers that poll from their own loop.
  • call, query and upload resolve, send once and decode the reply.

Envelopes

agentio::envelope carries values in DatapodMsg envelopes: the inner type hash travels with the wire bytes, so Rust, Python and C peers that share a canonical datapod name use one transport type. pack and unpack convert values, and every received envelope sample has unpack::<T>(), which checks the type. Envelope handles gain send_packed, take_packed/recv_packed, call_packed, query_packed, serve_packed and answer_packed, and the agent has one-shot call_packed/query_packed plus service threads serve_packed/answer_packed. A request taken with take_message and answered later gets its reply through respond_packed(token, &value).

Failover

HostOptions::standby() hosts a handle while another live owner holds the topic. Once no live owner record remains in the local directory, the control loop claims the topic and announces it; Follow clients move to the standby. Registered::is_active() tells a standby from the live owner.

Configuration from the environment

AgentBuilder::from_env("ROBOT"), or .env("ROBOT") over an existing builder, reads ROBOT_NAME, ROBOT_IDENTITY, ROBOT_BOOTSTRAP, ROBOT_ALLOW, ROBOT_FRONT_DOOR, ROBOT_RELAY, ROBOT_SHM, ROBOT_LEASE_MS, ROBOT_METADATA and the other variables listed on AgentBuilder::env. Unset variables keep the builder's settings, and a malformed one fails build with the variable's name. env_with takes the variables from any lookup function.

Identities

IdentitySource::Random creates a non-persistent identity. Named, default, DID, and explicit-file sources persist 32-byte keys with owner-only Unix permissions and fail on malformed or insecure existing files. DID-index copy failures are returned to the caller. A human-readable name is never converted into private key material. See docs/migrations/identity-derived-name.md when migrating from the removed name-derived API.

Lifecycle and health

Agent clones share one inner node. Dropping a non-final clone changes nothing; dropping the final clone withdraws every hosted record, signals and joins both control workers, and closes the node. Publisher and server wrappers withdraw their records on drop while the Agent remains live.

directory_health() snapshots announcement successes/failures, resolver errors, rejected records, last successful reconciliation, stale seed count, conflicts, and pending announcements. Configuration, signature, expiry, ownership, exchange, type, batch, and stale-revision failures are typed Error variants.

Each agent writes a host-local rendezvous record (rendezvous_dir()) with its name, did:key, dial address, process and metadata(...) pairs, refreshed as its addresses change. local_agents(), find_local(name) and find_local_did(did) read them; records of dead processes are pruned.

Features

Feature Adds
async agentio::aio: AgentBuilder::build_async, Agent::blocking, and Async<H> wrappers that run calls on tokio's blocking pool
ffi the C ABI in include/agentio.h over RawMsg topics
python the agentio Python module (pyo3)

agentio::bag records typed topics (Recorder) into timestamped bag files and replays them through typed publishers (Player) at a chosen speed.

Commands

.make.lua is the supported command surface (oslo make, or make at an oslo prompt):

make run
make run --example 05_all_exchanges
make run --example 07_client_all --args '<SERVER_DID_KEY>'
make c-example
make integration
make agent-test
make directory-test
make remote-test
make examples-smoke
make verify

Camera stream example

Examples 10/11 publish RGB frames from a Linux V4L2 camera and subscribe from a second Agent. They use GStreamer for camera capture and optional display, while the frame payload travels through agentio over iroh by default.

# Terminal 1: copy the printed did:key value
make camera-publisher --device /dev/video0

# Terminal 2: receive frames and open a display window
make camera-subscriber --server '<PUBLISHER_DID_KEY>' --args '--display'

Pass --args '--frames 30' for a bounded headless receiver, or --args '--use-shm' to either target when shared-memory transport is desired. Camera access requires read/write permission on the selected /dev/video* device. --args '--test-pattern' on the publisher replaces the camera with a GStreamer test pattern for transport testing.

Examples 06/07 are the two-process exchange demos. Examples 08/09 are bounded on every remote-controlled allocation and are throughput demos that measure actual received payload bytes and validate their content; they are not repeatable statistical benchmarks. examples/c/pubsub.c and examples/python/watch_peers.py show the C and Python bindings.

agentio is library-only. CI builds, tests, lints, and documents the library; it does not package an application binary. Source releases remain a manual maintainer operation.

The audit target explicitly reports but does not block on RUSTSEC-2023-0071, a medium-severity timing advisory in rsa with no fixed release. Agentio's directory protocol uses Ed25519, not RSA. Applications that use RSA through the re-exported authbox surface must assess that advisory for their own threat model. The current dependency graph also produces a non-vulnerability maintenance warning for transitive paste 1.0.15 through iroh's networking stack.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages