Language guide

AgentSpaces for Rust

Write an agent as an async Rust function, or run any program as a worker with the aspace command. A Rust peer holds its own identity, founds or joins a group over tcp or tls, and takes work under the same rules as every other member. aspace seed listens, so a fleet can be Rust programs and shell scripts alone.

Rust 1.99 through rustup, on Linux or macOScrates at 0.5.0, built from a clone (not yet on crates.io)a Tokio peer and a blocking facadedials and listens on tcp and tlsthe aspace command, aspace seed, and an MCP gatewayno votes, content swarm, or persistent values yet
aspace://guide/rust/intro

Introduction

AgentSpaces lets programs coordinate through shared, replicated memory with no broker or scheduler in the middle. The Rust repository, agentspaces-rust, gives you a peer on Tokio, typed entries, workers, and one command, aspace, for scripts and shells. This part walks you from a clone to two Rust workers that share orders and survive a kill.

The words this guide uses:

  • A peer is one running process in the fleet. It holds its own Ed25519 identity, and its PeerID is the hash of its public key.
  • A group is the set of peers that share spaces. The quick start's group is founded from the text shop-v1.
  • A seed is a peer that listens, so others can dial it to join a group. aspace seed is one, and so is any Java node or the Node host.
  • A space is a named, replicated store of entries inside a group, such as orders.
  • An entry is one typed record in a space. In Rust it is a plain struct with #[derive(Entry)].
  • A lease is how long an entry, a take, or a card lasts before it lapses.
  • A take is an exclusive hold on one entry. If the taker dies, the lease lapses and the entry comes back for another worker.
  • An agent is a named worker inside a peer, written <PeerID>/<name>. Its card (AgentCard) tells the fleet what it offers, and each action on the card, such as ship, can be called by name.
  • A capability is a fleet service a peer advertises, such as vote counting. The Rust peer has no capability clients yet (what is not built yet).

The four cards

A card is a signed, leased advertisement that tells the group what one thing offers. Four kinds of card describe the four kinds of thing a fleet holds: agents, data, models, and applications.

CardWhat it advertisesWho issues itHow discovery finds it
AgentCardAn agent: its description and goals, one action per bound method with the entry types it consumes and produces, and the space each input comes from.The binder, when you bind an agent.By the types it consumes or produces, by name, or by meaning. Remote actions and planners read its actions.
AssetCardA data asset: its name, source URI, shape of data, freshness, and how to query or invoke it. A content store advertises itself with one too.A connector peer, one card per asset it holds.By asset name, shape, or access mode, or by meaning.
ModelCardA model the group may route to: its tasks, limits, licence, provenance, residency, engine, and the peers that serve it.The peer that serves the model, or a registry that admits models to the group.By name, task, engine, or residency site, or by meaning.
AppCardAn application that joins the fleet: how it connects, its shape, the spaces it reads, the actions it may request, its views, and the A2UI components it draws.The application's publisher.By kind, origin, or the formats it handles, or by meaning. A console lists the fleet's apps from these cards.

All four travel the same way. The issuer signs the card and gives it a lifetime (its TTL). Gossip carries it on the group's ads stream into every member's local cache, and the issuer refreshes it while the thing it describes is live. A card whose issuer stops refreshing it ages out of every cache when its TTL runs out, so a card can outlive its issuer by up to one TTL.

Every peer finds cards in its own cache, by structure: a card type plus conditions on its fields. Semantic discovery also ranks cards by meaning against a text query. Treat what you find as a hint about a live fleet: work still reaches a worker through its space and entry type, whether or not the card has arrived.

ONE GROUP: FOUR KINDS OF CARD ON ONE ADS STREAMagent peerthe binder issues itAgentCarddescription, goalsactions: consumes, producesspaceBindingsagent key, certificatesigned, leased, refreshedconnectorone card per assetAssetCardasset, uri, descriptionshape, freshnessaccess: query, invoke-opscostHintssigned, leased, refreshedmodel serverserves the modelModelCardname, version, taskslimits, licence, provenanceresidency, engineserverssigned, leased, refreshedapplicationits publisher issues itAppCardname, kind, shape, ownerreads, actions, viewsui: its A2UI componentsorigin, formatssigned, leased, refreshedthe ads stream: gossip carries every card to every member of the groupeach member's ad cache: the newest issue per id, aged out at its TTLfind(type, predicate)by structure: a card type and its fieldssemantic queryby meaning: names, descriptions, and tasksa planner, a console, or a caller reads the cards; work itself still routes by space and entry type
The four cards. An agent peer, a connector, a model server, and an application each sign a card and lease it. Gossip carries every card on the group's ads stream into each member's cache, where any peer finds it by type and fields or by meaning. A card whose issuer stops refreshing it ages out.

The four cards in Rust shows how a Rust peer issues and finds each card.

Install

You need Linux or macOS and Rust through rustup. The repository pins its toolchain, Rust 1.99, in rust-toolchain.toml, and rustup installs it on first use. The quick start's seed is the aspace command too, so you need nothing else.

The crates are not on crates.io yet. Clone the repository and work in its quick start directory:

git clone https://github.com/badmonkeyai/agentspaces-rust
cd agentspaces-rust/quickstart

The quick start's Cargo.toml depends on the crate in the clone by path:

# Cargo.toml
[dependencies]
# Until agentspaces is on crates.io, build against this repository's crate.
# Once it is published, write this line instead:  agentspaces = "0.5.0"
agentspaces = { path = "../crates/agentspaces" }
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "time"] }

A project outside the clone can depend on the repository by git instead: agentspaces = { git = "https://github.com/badmonkeyai/agentspaces-rust" }.

Note. The Rust crates are numbered 0.5.0 and speak the wire of the upcoming 0.6.0 release, on wire version 3. Their cross-language tests run against the 0.6.0 Java jars, so a Rust peer can join a 0.6.0 group. The crate version moves to the core's version when the crates are published.

Start a seed

The quick start starts a seed first. seed.sh runs aspace seed, a listening member. It reads fleet.yaml, listens on 127.0.0.1:7700, serves the group shop-v1, and keeps the space orders, so a worker or the desk can leave and the orders stay. Run it in a terminal of its own:

./seed.sh

It runs the aspace on your PATH, or builds the clone's on the first run. It prints one JSON line when it listens, then one line per member it admits. Leave it running, and press Ctrl-C to stop it. A Java node can be the seed instead: SEED=java ./seed.sh runs the clone's scripted Java node, with a JDK 21 or newer and Maven.

The Rust program finds the fleet through fleet.yaml. It is the same agentspaces: file the Spring and Micronaut starters, the Node host, and the Ruby client read:

# fleet.yaml
agentspaces:
  groups:
    - name: shop
      founding: shop-v1                 # the group the seed founds
      seeds: [ "tcp://127.0.0.1:7700" ] # plain tcp on loopback only; use tls:// on a network
      spaces: [ orders ]

Plain tcp signs every frame but encrypts nothing. So the peer accepts a tcp seed only on loopback, or under the dev-local profile, which is for a laptop and never for a shared network. On a network, use a tls://host:port seed. Any listening peer can be the seed: aspace seed, a Java node, a Spring Boot or Micronaut service, or the Node host.

Entries

#[derive(Entry)] binds a struct to its wire schema, the name every language on the wire agrees on. serde does the rest:

// src/main.rs
/// An order. It travels as `shop.Order#v1` with the fields `orderId` and `item`.
#[derive(Debug, Serialize, Deserialize, Entry)]
#[entry(schema = "shop.Order#v1")]
#[serde(rename_all = "camelCase")]
struct Order {
    order_id: String,
    item: String,
}
  • #[entry(schema = "shop.Order#v1")] names the schema. A missing, repeated, or malformed attribute is a compile error that says what to write.
  • rename_all = "camelCase" gives the fields their wire names, so order_id travels as orderId.
  • A Java record reads the same bytes when its components have the same names and types. The quick start's Shipment struct adds a by field to the same two.

Your first agent

The quick start's program is a worker when it runs with no argument, and a desk that places one order when it runs with one. The agent's action is an async function: an Order in, a Shipment out.

// src/main.rs
/// The agent's one action: an Order in, a Shipment out.
async fn ship(order: Order, ctx: TakeContext) -> Result<Reply, HandlerError> {
    println!("shipping {} (attempt {})", order.order_id, ctx.attempt());
    // keepalive renews the take while the work runs, however long it takes.
    ctx.keepalive(tokio::time::sleep(ship_time())).await;
    let shipment = Shipment {
        order_id: order.order_id,
        item: order.item,
        by: ctx.agent_id().to_owned(),
    };
    Ok(shipment.into())
}
// ...
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let fleet = Fleet::join_config(&Config::load("fleet.yaml")?).await?;

    if let Some(item) = std::env::args().nth(1) {
        // The desk: write an order, then wait for the shipment that answers it.
        let orders = fleet.space("orders");
        let order = Order {
            order_id: format!("o-{}", std::process::id()),
            item,
        };
        orders
            .write(&order, Lease::parse("10m")?, Map::new())
            .await?;
        println!("ordered {}", order.order_id);
        let answer = format!("orderId={}", order.order_id);
        let shipped = Template::of::<Shipment>().where_clause(&answer)?;
        let shipment = orders.read_typed::<Shipment>(&shipped, WAIT).await?;
        println!("{:?}", shipment.ok_or("no shipment within 90 s")?.value());
    } else {
        // The worker: take orders, holding each for 30 s at a time, until Ctrl-C.
        let worker = fleet
            .agent("fulfiller")
            .describe("Ships orders")
            .take("orders", Lease::parse("30s")?, ship)
            .action("ship")
            .produces::<Shipment>()
            .bind()
            .await?;
        let pid = std::process::id();
        println!("serving as {} (pid {pid})", worker.agent_id());
        worker.stop_on_signals().await?;
    }

    fleet.close().await?;
    Ok(())
}

What each part does:

  • Fleet::join_config dials the seed that fleet.yaml names, joins the group, and returns a running peer.
  • fleet.agent("fulfiller") names the agent. .take("orders", Lease::parse("30s")?, ship) takes each Order from orders and holds it for 30 seconds while ship runs. .action("ship") names the action on the agent's card.
  • Whatever ship returns completes the take. An Err lets the take lapse, so another worker gets the order.
  • ctx.keepalive(work) renews the take while long work runs, such as a model call. ctx.attempt() counts the takes, so a retry shows as attempt 2.
  • The desk writes an Order with a 10-minute lease, then waits up to 90 seconds for the Shipment whose orderId matches.
  • worker.stop_on_signals() serves until SIGINT or SIGTERM, then stops within a grace period.

Run two workers and kill one

Start each worker in a terminal of its own, then run the desk in a third:

cargo run -q            # worker 1
cargo run -q            # worker 2
cargo run -q -- kite    # the desk

Each worker prints the agent it serves as, <PeerID>/fulfiller, and its process id. The desk prints the order and its shipment. Either worker can take the order, because both take Order entries from orders, and by names the one that did:

ordered o-79914
Shipment { order_id: "o-79914", item: "kite", by: "z7BcP43ftjA4eJo4ABn9F2YfyN6a6LS7cEk9Wfv2uj3L5/fulfiller" }

To watch a take recover from a crash:

  1. Stop both workers and start them again with slow shipping: SHIP_SECONDS=10 cargo run -q.
  2. Run the desk again. One worker prints shipping o-... (attempt 1).
  3. Kill that worker with kill -9 <pid>, using the pid from its serving as line.
  4. Within 30 seconds the take lapses. The other worker prints attempt 2, and the desk prints the shipment with the survivor in by.

No code on the surviving worker handles the failure. The lease on the take lapsed, and the order reappeared for the next taker.

A second verb: notify

take is exclusive: one worker gets each entry. notify runs a handler on every matching entry that is written, and leaves the entry in place, so several agents can each see it. Use it for audit trails, receipts, and tracking. This agent, from the crate's tests, writes a Report for each Task written to the space audit:

// tests/agents.rs
let bound = worker
    .agent("watcher")
    .notify("audit", |task: Task, ctx: NotifyContext| async move {
        Ok(Reply::from(report(&task.topic, ctx.space().name())))
    })
    .produces::<Report>()
    .bind()
    .await
    .expect("bind");
  • The closure's parameter type picks the entries. A typed notify passes over entries that do not decode as a Task.
  • ctx.space() is the space the entry arrived in. Reply::from(...) writes the handler's result, and Reply::none() writes nothing.
  • One agent can carry several take and notify bindings before .bind().

To follow every change to a schema, watch_typed streams each entry's transitions: written, taken, completed, expired, and reappeared (the space verbs).

Where to read next

  • Key features covers the space verbs, workers, the blocking facade, the fleet file, aspace, running a seed, the MCP gateway, and what the Rust peer does not do yet.
  • Examples runs a fleet from the shell with nothing but aspace, runs the fulfiller with no Rust code, and puts Rust workers on a Java research fleet.
  • The developer guide's Rust section maps the Rust peer onto the Java chapters. Read leases and cards there for depth.
  • The architecture guide explains replication, leases, and membership, and which peer kind hosts which work.
  • For other languages, read the Python, TypeScript, Ruby, Clojure, and Groovy guides.
aspace://guide/rust/features

Key features

The pieces in this part are specific to the Rust repository: the async space verbs, workers and their cards, the blocking facade, the fleet file, the aspace command, running a seed, and the MCP gateway. The last section says plainly what is not built yet.

The four cards in Rust

The Rust peer keeps every card it hears as a map in its cache. peer.cards() returns the live AgentCards, and peer.ads(kind) returns the live cards of any kind.

CardIssue itFind it
AgentCardfleet.agent(name) with its handlers, then .bind(), publishes the card with its declared actions and refreshes it every 5 minutespeer.cards(); FleetCatalog and aspace cards list the fleet's offerings
AssetCardnot yet: the 0.5.0 crates have no connectorpeer.ads("AssetCard")
ModelCardnot yetpeer.ads("ModelCard")
AppCardagentspaces_wire::ads::AppCard builds the card with to_map, without the newer origin and formatspeer.ads("AppCard")

The Rust peer has no semantic discovery yet. This test publishes a fleet's AgentCards, waits for them to arrive, and reads the fleet catalogue built from them:

// catalog.rs
let catalog = FleetCatalog::new(&fleet);
eventually("every card arrives", || async {
    fleet.peer().cards().await.len() == CARDS
})
.await;
// ...
let offerings = catalog.current().await;

Read cards, the ad cache, and the ads stream for every field of each card.

The space verbs

fleet.space(name) is a cheap handle on one replicated space. Every verb is async and typed. The Order in this excerpt has sku and qty fields:

let orders = fleet.space("orders");
let order = Order { order_id: "o-1".into(), sku: "A-1".into(), qty: 12 };
let id = orders.write(&order, Lease::parse("10m")?, Map::new()).await?;

let big = Template::of::<Order>().where_clause("qty>=10")?;
let first = orders.read_typed::<Order>(&big, Duration::from_secs(5)).await?;
let all_now = orders.read_all_typed::<Order>(&big, 100).await?;

let wait = Duration::from_secs(5);
if let Some(taken) = orders.take_typed::<Order>(&big, Lease::parse("30s")?, wait).await? {
    let order_id = taken.value().order_id.clone();
    let shipment = Shipment { order_id, tracking: "Z9".into() };
    taken.complete_with(&shipment, Lease::parse("1h")?, Map::new()).await?;
}

let mut events = orders.watch_typed::<Order>(&Template::of::<Order>()).await?;
while let Some(event) = events.next().await {
    println!("{:?} {:?}", event.kind, event.entry.value());
}
  • write returns the entry's id, and the entry lives for its lease. The last argument holds the entry's tags, empty here.
  • read_typed waits up to its timeout for a match. read_all_typed returns what is there now, up to a limit.
  • take_typed holds an entry exclusively for its lease. Complete it, or let the hold lapse and the entry reappears.
  • watch_typed streams Written, Taken, Completed, Expired, and Reappeared.
  • Templates take filter clauses such as qty>=10 or region in eu, us, the grammar every AgentSpaces language reads.

The crate also has the untyped forms (write_value, take_value, notify_value) for entries whose schema has no Rust type. A payload over 64 KiB travels as a content-addressed block, fetched from the writer or another member that holds it.

Workers and their cards

fleet.agent(name) binds handlers as an agent with an identity of its own. Its work reads as AGENT_ATTESTED, and its AgentCard lets the fleet catalogue, aspace call, and MCP hosts find it:

async fn ship(order: Order, ctx: TakeContext) -> Result<Reply, HandlerError> {
    // book_courier is your own async work, a model or an API call. keepalive renews the take
    // while it runs.
    let tracking = ctx.keepalive(book_courier(&order)).await?;
    Ok(Shipment { order_id: order.order_id, tracking }.into())
}

let worker = fleet
    .agent("fulfiller")
    .describe("Ships orders")
    .take("orders", Lease::parse("30s")?, ship)
    .action("ship")
    .produces::<Shipment>()
    .parallel(4)
    .bind()
    .await?;
worker.stop_on_signals().await?; // runs until SIGINT or SIGTERM, then finishes within a grace
  • A handler returns an entry (which completes the take), nothing, several entries, or an error (the take lapses and another worker gets the task).
  • .parallel(4) lets the binding handle up to four tasks at once. A take handles one at a time by default.
  • The peer publishes the card with its declared actions and refreshes it every 5 minutes.
  • Remote actions work both ways: a Rust program can invoke an action on any live card, and Java agents can call Rust actions.

Without async: the blocking facade

agentspaces::blocking mirrors the verbs over a runtime of its own. Use it for scripts, tests, and code that has no Tokio:

use agentspaces::blocking::Fleet;
// ...
let fleet = Fleet::join_from_env()?; // ASPACE_CONFIG=fleet.yaml, or the other ASPACE_* variables
let orders = fleet.space("orders");
let order = Order { order_id: "o-2".into(), sku: "B-7".into(), qty: 1 };
orders.write(&order, Lease::parse("10m")?, Map::new())?;
let shipped = Template::of::<Shipment>().where_clause("orderId=o-2")?;
let shipment = orders.read_typed::<Shipment>(&shipped, Duration::from_secs(30))?;
fleet.close()?;

The fleet file, variables, and security

The fleet file is the agentspaces: subtree every AgentSpaces host reads, and the peer ignores the keys it does not use. A fleet on a network looks like this:

agentspaces:
  keystore: ~/.config/agentspaces/keys    # peer.key and peer.pub, shared with Java, Python, Ruby
  security:
    profile: mtls                         # tls:// seeds must attest; dev-local allows plain tcp
  groups:
    - name: research-fleet
      join: aspace://zQm...               # or founding: <text>
      seeds: [ "tls://fleet.example.com:7500" ]
      spaces: [ tasks ]

The ASPACE_* variables override the file, and Fleet::join_from_env() reads them over ~/.config/agentspaces/fleet.yaml:

VariableMeaning
ASPACE_CONFIGthe fleet file
ASPACE_SEEDSseeds, comma-separated: tls://host:port, tcp://host:port, or host:port (tcp)
ASPACE_GROUPa group of the fleet file by name, or else a founding text
ASPACE_JOINa group by id: aspace://<group-id>
ASPACE_KEYSTOREthe keystore directory; without one the crate runs with a fresh identity
ASPACE_PROFILEmtls (the default) or dev-local
ASPACE_SPACESthe spaces to pull after joining, comma-separated
ASPACE_INVITEan invite key (aspace-inv1-...), for joining an invite group
ASPACE_LISTENfor aspace seed: where to listen, comma-separated tcp://host:port or tls://host:port
ASPACE_ADVERTISEfor aspace seed: the address other members dial, when it differs from the listener's

Security works like this:

  • A tls:// seed is dialed over TLS 1.3 with a channel certificate: a fresh P-256 key that the peer's Ed25519 identity key endorses. No certificate authority is involved, and the peer refuses a seed whose certificate attests nobody.
  • join: aspace://<id> fetches the group's founding document from a seed and checks it before joining. A group founded from a text has no founding document, so join it with founding:.
  • The peer verifies every frame, record, claim, card, and revocation before it acts on one, and it bounds what a remote can make it hold.
  • The keystore is the directory layout Java, Python, and Ruby share. It is owner-only, and a private key others can read is refused.

The aspace command

aspace is a fleet member for scripts, hooks, and shells. Build it from the clone with cargo install --locked --path crates/aspace; it lands in ~/.cargo/bin. Most commands join, do one thing, and leave:

CommandWhat it does
aspace idcreate or show this machine's identity and print its PeerID
aspace statusjoin, report the group, members, links, and catalogue, and leave
aspace write SCHEMA --json OBJECTwrite one entry and print its id
aspace read SCHEMAprint the entries of a schema; --where filters, --timeout waits for a first match
aspace take SCHEMA, aspace complete IDtake one entry and print it; complete it later from the same keystore
aspace watch SCHEMAstream the transitions of a schema's entries
aspace cards, aspace call TARGET --json OBJECTlist the fleet's offerings; invoke one and print its result
aspace work --take SCHEMA --space SPACE -- PROGRAMrun a program for each task taken, as an agent with a card
aspace seedlisten and serve a group as its seed (run a seed)
aspace invite --found NAMEprint an invite key of an invite group this keystore founded
aspace daemonstay joined and serve the other commands over a local socket
aspace mcpserve the fleet's offerings as MCP tools
aspace doctorcheck the configuration, the keystore, the seeds, and the join

What a script can rely on:

  • Results are JSON on standard output: one object, or one object per line for streams. Diagnostics go to standard error.
  • The exit codes are 0 for success, 1 for an error, 2 for refused or not found, 3 for a timeout, and 4 for authentication or authorization.
  • Each command joins the fleet on its own unless aspace daemon runs. While the daemon runs, the commands that name its group, keystore, and profile go through it and answer in milliseconds.

Run a seed

aspace seed is a listening member. Other members dial it to join its group. It admits them under the group's membership, forwards what each one writes to the others, answers late joiners from what it holds, and relays frames between members that cannot reach each other. A writer can leave, and a later visitor still reads what it wrote.

Name the group one of three ways:

aspace --keystore keys/seed seed --found demo --listen tls://0.0.0.0:7700    # found the group demo
aspace seed --group shop-v1 --listen tls://0.0.0.0:7700                      # a group founded from a text
aspace seed --join aspace://<group-id> --seeds tls://first.example:7700 --listen tls://0.0.0.0:7701   # a second seed
  • --found NAME signs a founding on the first run and keeps it beside the keystore, so a restart keeps the group's id. Its one line on standard output names the aspace:// id members join with.
  • --group TEXT serves a group founded from a text. Members join it with the same founding text, because such a group has no founding document to fetch.
  • --membership invite (with --found) admits only peers that hold an invite key. aspace invite --found NAME prints one, and joiners pass it with --invite or ASPACE_INVITE.
  • --require-attestation on a tls listener refuses every frame that its link does not attest.
  • It keeps the group's spaces, plus up to 64 spaces it hears about (--replicate, --max-spaces), each bounded in entries and bytes.

A Rust program listens the same way. This test starts a hub that listens on a free tcp port, and a member that dials it:

// tests/listen.rs
let identity = Identity::generate().expect("identity");
let mut config = PeerConfig::new(identity, GroupSpec::FoundingText(FOUNDING.to_owned()));
// ...
let listener = match wire {
    Wire::Memory => ListenerSpec::bound(Arc::new(network.listen(address))),
    Wire::Tcp => ListenerSpec::tcp("127.0.0.1:0"),
};
config = config.listen_on(listener);
// ...
let hub = Peer::start(config).await.expect("the hub starts");
let bound = hub.listen_addrs();
// ...
config.seeds = vec![self.seed.parse().expect("seed")];
  • ListenerSpec::tcp and ListenerSpec::tls name a bind address, and .advertise(address) names the one others dial when it differs.
  • listen_addrs() reports the real port when the bind asks for port 0.
  • agentspaces::group::found_or_load makes or loads a signed founding, as --found does.

MCP: the fleet as tools

aspace mcp serves the fleet's catalogue to any MCP host, such as Codex CLI, Claude Code, goose, or Zed. Each offering becomes one tool. A tool call writes the input entry where the advertising agent takes its work, waits for the result, and returns it. Over stdio the host starts the gateway, as in this .mcp.json:

{"mcpServers": {"fleet": {"command": "aspace", "args": ["mcp"]}}}

For a team, serve Streamable HTTP. The gateway binds loopback by default and refuses to start without a token verifier (a token file, or JWTs from your issuer):

aspace mcp --http 127.0.0.1:8740 --tokens ~/.config/agentspaces/mcp-tokens.yaml --only 'shop.*'
  • --only PATTERN limits what a model sees, and --policy FILE maps token scopes to the offerings each may call.
  • Hosts get notifications/tools/list_changed when offerings come and go.
  • The gateway strips control and invisible characters from card text, caps its length, and frames descriptions as data from the fleet.
  • Give the gateway a keystore that no other running aspace member uses.

A Rust program with its own rmcp server can embed FleetMcpServer from the agentspaces-mcp crate.

Proven against Java and the other clients

A Rust member has to agree with the Java reference byte for byte, and the repository checks it three ways:

  • Golden vectors. The wire crate carries a copy of the specification's golden vectors, which the Java codec produced, and the wire-encoding vectors with Java's verdict on each input. It reproduces the vectors of every feature it has byte for byte, and reaches Java's verdict on all 205 wire-encoding inputs. The vectors it skips belong to features the Rust peer does not have yet.
  • A live Java peer. The interop tests start the scripted Java seed and check membership over tcp and attested tls, writes, takes, and completions both ways, and races in which each task is completed exactly once. They also check that a crashed Rust worker's task reappears for a Java agent, that Rust and Java agents call each other's actions, and that a Java node joins a Rust seed.
  • Every client through a Rust seed. A test starts aspace seed and joins a Python, a TypeScript, a Ruby, and a Rust peer to it, over tcp and over tls with attestation required. The four race for twelve tasks, each task is completed exactly once, and each language's watch sees the others' writes.

What is not built yet

The Rust peer works, calls, and serves a group as its seed. These parts of AgentSpaces are not in the 0.5.0 crates, and each has another way in:

MissingUse instead
a full mesh: a Rust peer dials its seeds and not every other membergive every member the same seeds; a second seed joins the first with --join
the ws, http, QUIC, DTLS, and WebRTC transportstcp on loopback, or tls
session attestation on the peerattested tls; on tcp, frames are signed and nothing is encrypted
the vote, aggregate, semantic discovery, and connector capabilitiesa JVM, Python, TypeScript, or Ruby peer for ballots, estimates, and connector queries
the ordered loga JVM or Node service peer for once-only work
the content swarm, artifacts, persistent values, and content storesa JVM peer, or a Python or TypeScript client, for large data and values that change
aspace on Windows, release binaries, and crates.ioLinux or macOS, and a clone

The repository's plan lists these next: the capabilities and the ws transport, the content swarm with aspace put and aspace get, bindings for C, Swift, Kotlin, and WASI, and a crates.io release.

aspace://guide/rust/examples

Examples

The first example needs nothing but aspace. The second runs on the quick start's seed. The third puts Rust members on a Java fleet, so it also needs example 02 of the core repository at 0.6.0, built into ~/.m2.

A fleet from the shell

This example runs a whole fleet from a shell with nothing but the aspace binary: no JVM, no Node, no Python, no Ruby, and no Rust code. Every peer is a separate process with its own identity, so each command below names its own keystore:

  • Peer 1, the seed, founds the group demo, listens on 127.0.0.1:7700, and prints the aspace:// id to join by.
  • Peer 2 writes a note to the space notes, reads it back, and leaves.
  • A worker serves the action shout with a shell script, and a third peer finds the action and calls it.
  • A late visitor joins after peer 2 left and still reads its note, because the seed keeps what the group wrote.

The commands, as the example's script runs them:

aspace --profile dev-local --keystore keys/seed seed --found demo --listen tcp://127.0.0.1:7700 &
export ASPACE_PROFILE=dev-local ASPACE_SEEDS=tcp://127.0.0.1:7700 ASPACE_JOIN=aspace://<group-id from the seed>
aspace --keystore keys/peer2 write 'demo.Note#v1' --space notes --json '{"text":"hello from peer 2"}'
aspace --keystore keys/peer2 read 'demo.Note#v1' --space notes
aspace --keystore keys/worker work --space desk --take 'demo.Shout#v1' --produces 'demo.Shouted#v1' \
    --action shout -- ./handler.sh &
aspace --keystore keys/caller cards
aspace --keystore keys/caller call shout --json '{"text":"hello, fleet"}' --timeout 30s
aspace --keystore keys/late read 'demo.Note#v1' --space notes
aspace --keystore keys/late status

The seed's one line, the call's result, and the late visitor's count of members, from a real run (ids differ in every run):

{"event":"listening","peer":"z4kMUMVP…","group":"z4ZbWj6S…","join":"aspace://z4ZbWj6S…","listen":["tcp://127.0.0.1:7741"],"advertise":[],"membership":"OPEN"}
{"offering":"shout",…,"entry":{"text":"hello, fleet","shout":"HELLO, FLEET","by":"handler.sh"},…,"attestation":"AGENT_ATTESTED",…}
members  4 (1 reachable)

From the clone, examples/two-peers/two-peers.sh runs the whole thing in a scratch directory in about four seconds. It prints each command and what it printed, and stops every process it started. cargo test -p aspace --test two_peers checks each step.

How it works:

  • ASPACE_SEEDS and ASPACE_JOIN point every visitor at the seed and the group, and --keystore gives each its own identity.
  • call writes the input where the shout agent takes its work, and prints the result whose shared fields equal the input's. So the handler keeps text and adds shout and by.
  • Add as many peers as you like, each with its own keystore. A second worker serving shout becomes a replica of the same offering.
  • The dev-local profile signs every frame over plain loopback tcp. Use it on a laptop, never on a shared network: there, the seed listens on tls:// and the members dial tls://.

The fulfiller with no Rust code

This example shows aspace work, which runs any program as a worker. It starts the program once per task, with the entry as JSON on standard input, and completes the take with the first JSON object the program prints. This shell script is the quick start's fulfiller:

#!/bin/sh
# The Fulfiller with no Rust code: `aspace work` runs this once per order.
# The order arrives on standard input as one line of JSON: {"orderId":"o-2","item":"ball"}
# The first JSON object printed is the shipment. A non-zero exit hands the order back.
set -eu
order=$(cat)
echo "shipping $order" >&2
# The shipment is the order plus one field: drop the closing brace and add "by".
printf '%s,"by":"fulfil.sh"}\n' "${order%\}}"

With the seed running, install aspace and start the script as a worker on a keystore of its own:

cargo install --locked --path ../crates/aspace
aspace --config fleet.yaml --keystore keys/script work --space orders \
    --take 'shop.Order#v1' --produces 'shop.Shipment#v1' --name fulfiller --action ship -- ./fulfil.sh

In another terminal, list the cards, write an order, read its shipment, and call the action in one step:

aspace --config fleet.yaml cards
aspace --config fleet.yaml write 'shop.Order#v1' --space orders --json '{"orderId":"o-2","item":"ball"}'
aspace --config fleet.yaml read 'shop.Shipment#v1' --space orders --where 'orderId=o-2' --timeout 30s
aspace --config fleet.yaml call ship --json '{"orderId":"o-3","item":"yo-yo"}'

How it works:

  • A keystore is one identity, so two members running at once need two. The worker uses keys/script, and the other commands use the default, ~/.config/agentspaces/keys.
  • aspace work runs the program with no shell. The environment holds only PATH, HOME, LANG, three ASPACE_* task variables, and what --env names.
  • The take is renewed at half its lease while the program runs. A non-zero exit, a signal, or output that is not an object lets the take lapse, so another worker gets the task.
  • read prints one JSON line per entry, with the payload, the tags, the issuer, and "attestation":"AGENT_ATTESTED".
  • call writes the input where the ship agent takes its work, and prints the result that answers it. The Rust workers from the quick start declare the same action, so cards shows one offering with a replica for each worker.

Rust and shell workers on a Java research fleet

This example puts Rust members on the Java research fleet of the core repository's example 02. A Java coordinator publishes six ResearchTask entries and tallies the Finding entries that answer them. A Rust worker and a shell script under aspace work share the tasks.

The Rust entries name the Java records' schemas, so both sides read the same values:

// examples/rust-fleet/src/main.rs
#[derive(Debug, Clone, Serialize, Deserialize, Entry)]
#[entry(schema = "ai.badmonkey.agentspaces.examples.fleet.ResearchFleet$ResearchTask#v1")]
#[serde(rename_all = "camelCase")]
struct ResearchTask {
    topic: String,
    priority: i32,
}
// ...
const WORKER: &str = "rust-worker";
// ...
async fn run() -> Result<(), Box<dyn std::error::Error>> {
    let fleet = Fleet::join_from_env().await?;
    let bound = fleet
        .agent(WORKER)
        .describe("Researches a topic (example 32's Rust worker)")
        .take::<ResearchTask, _, _>("tasks", Lease::parse("30s")?, research)
        .action("research")
        .produces::<Finding>()
        .bind()
        .await?;
    // ...
    bound.stop_on_signals().await?;
    // ...
    fleet.close().await?;
    Ok(())
}

Fleet::join_from_env reads ASPACE_SEEDS, ASPACE_GROUP, and ASPACE_KEYSTORE, so one binary joins any fleet. The example resolves the AgentSpaces 0.6.0 jars from ~/.m2, including example 02's example-02-research-fleet 0.6.0, which is not on Maven Central. So first run mvn install -DskipTests in a clone of the core repository at 0.6.0. Then, from the Rust clone:

cd examples/rust-fleet
./run.sh          # over tcp, about 10 s once built
./run.sh --tls    # over tls with attestation required, about 25 s

run.sh builds both workers, starts a Java seed, the two workers, and the coordinator, then runs aspace cards and aspace call, and stops everything. It exits 0 only when the coordinator recorded findings from both workers, the call printed a Finding, and both workers stopped cleanly. A run ends like this:

[coordinator] tally: {rust-worker=3, script-worker=3}
==> aspace cards listed research with 2 replica(s)
==> the call printed a Finding for topic rust by rust-worker
example 32: ok (tcp)

How it works:

  • Both workers declare the same research action, so the catalogue folds them into one offering with two replicas. A call reaches whichever worker takes the task.
  • The Java seed runs discovery and keeps the cards. Example 02's coordinator keeps none, so a caller that joined through it alone would see the workers' cards only at the next refresh.
  • Over tls, every link to the seed is attested, and the seed sends bare frames on those links.

The full source and the expected output of both runs are in examples/rust-fleet. The Ruby guide runs the same coordinator with a Ruby worker.