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.
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 seedis 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 asship, 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.
| Card | What it advertises | Who issues it | How discovery finds it |
|---|---|---|---|
| AgentCard | An 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. |
| AssetCard | A 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. |
| ModelCard | A 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. |
| AppCard | An 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.
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" }.
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.shIt 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, soorder_idtravels asorderId.- A Java record reads the same bytes when its components have the same names and types. The quick start's
Shipmentstruct adds abyfield 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_configdials the seed thatfleet.yamlnames, joins the group, and returns a running peer.fleet.agent("fulfiller")names the agent..take("orders", Lease::parse("30s")?, ship)takes eachOrderfromordersand holds it for 30 seconds whileshipruns..action("ship")names the action on the agent's card.- Whatever
shipreturns completes the take. AnErrlets 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
Orderwith a 10-minute lease, then waits up to 90 seconds for theShipmentwhoseorderIdmatches. 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:
- Stop both workers and start them again with slow shipping:
SHIP_SECONDS=10 cargo run -q. - Run the desk again. One worker prints
shipping o-... (attempt 1). - Kill that worker with
kill -9 <pid>, using the pid from itsserving asline. - Within 30 seconds the take lapses. The other worker prints
attempt 2, and the desk prints the shipment with the survivor inby.
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
notifypasses over entries that do not decode as aTask. ctx.space()is the space the entry arrived in.Reply::from(...)writes the handler's result, andReply::none()writes nothing.- One agent can carry several
takeandnotifybindings 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.
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.
| Card | Issue it | Find it |
|---|---|---|
| AgentCard | fleet.agent(name) with its handlers, then .bind(), publishes the card with its declared actions and refreshes it every 5 minutes | peer.cards(); FleetCatalog and aspace cards list the fleet's offerings |
| AssetCard | not yet: the 0.5.0 crates have no connector | peer.ads("AssetCard") |
| ModelCard | not yet | peer.ads("ModelCard") |
| AppCard | agentspaces_wire::ads::AppCard builds the card with to_map, without the newer origin and formats | peer.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()); }
writereturns the entry's id, and the entry lives for its lease. The last argument holds the entry's tags, empty here.read_typedwaits up to its timeout for a match.read_all_typedreturns what is there now, up to a limit.take_typedholds an entry exclusively for its lease. Complete it, or let the hold lapse and the entry reappears.watch_typedstreamsWritten,Taken,Completed,Expired, andReappeared.- Templates take filter clauses such as
qty>=10orregion 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:
| Variable | Meaning |
|---|---|
ASPACE_CONFIG | the fleet file |
ASPACE_SEEDS | seeds, comma-separated: tls://host:port, tcp://host:port, or host:port (tcp) |
ASPACE_GROUP | a group of the fleet file by name, or else a founding text |
ASPACE_JOIN | a group by id: aspace://<group-id> |
ASPACE_KEYSTORE | the keystore directory; without one the crate runs with a fresh identity |
ASPACE_PROFILE | mtls (the default) or dev-local |
ASPACE_SPACES | the spaces to pull after joining, comma-separated |
ASPACE_INVITE | an invite key (aspace-inv1-...), for joining an invite group |
ASPACE_LISTEN | for aspace seed: where to listen, comma-separated tcp://host:port or tls://host:port |
ASPACE_ADVERTISE | for 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 withfounding:.- 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:
| Command | What it does |
|---|---|
aspace id | create or show this machine's identity and print its PeerID |
aspace status | join, report the group, members, links, and catalogue, and leave |
aspace write SCHEMA --json OBJECT | write one entry and print its id |
aspace read SCHEMA | print the entries of a schema; --where filters, --timeout waits for a first match |
aspace take SCHEMA, aspace complete ID | take one entry and print it; complete it later from the same keystore |
aspace watch SCHEMA | stream the transitions of a schema's entries |
aspace cards, aspace call TARGET --json OBJECT | list the fleet's offerings; invoke one and print its result |
aspace work --take SCHEMA --space SPACE -- PROGRAM | run a program for each task taken, as an agent with a card |
aspace seed | listen and serve a group as its seed (run a seed) |
aspace invite --found NAME | print an invite key of an invite group this keystore founded |
aspace daemon | stay joined and serve the other commands over a local socket |
aspace mcp | serve the fleet's offerings as MCP tools |
aspace doctor | check 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 daemonruns. 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 NAMEsigns 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 theaspace://id members join with.--group TEXTserves 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 NAMEprints one, and joiners pass it with--inviteorASPACE_INVITE.--require-attestationon atlslistener 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::tcpandListenerSpec::tlsname 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_loadmakes or loads a signed founding, as--founddoes.
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 PATTERNlimits what a model sees, and--policy FILEmaps token scopes to the offerings each may call.- Hosts get
notifications/tools/list_changedwhen 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
aspacemember 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
tcpand attestedtls, 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 seedand joins a Python, a TypeScript, a Ruby, and a Rust peer to it, overtcpand overtlswith 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:
| Missing | Use instead |
|---|---|
| a full mesh: a Rust peer dials its seeds and not every other member | give every member the same seeds; a second seed joins the first with --join |
the ws, http, QUIC, DTLS, and WebRTC transports | tcp on loopback, or tls |
| session attestation on the peer | attested tls; on tcp, frames are signed and nothing is encrypted |
| the vote, aggregate, semantic discovery, and connector capabilities | a JVM, Python, TypeScript, or Ruby peer for ballots, estimates, and connector queries |
| the ordered log | a JVM or Node service peer for once-only work |
| the content swarm, artifacts, persistent values, and content stores | a JVM peer, or a Python or TypeScript client, for large data and values that change |
aspace on Windows, release binaries, and crates.io | Linux 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.
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 on127.0.0.1:7700, and prints theaspace://id to join by. - Peer 2 writes a note to the space
notes, reads it back, and leaves. - A worker serves the action
shoutwith 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_SEEDSandASPACE_JOINpoint every visitor at the seed and the group, and--keystoregives each its own identity.callwrites the input where theshoutagent takes its work, and prints the result whose shared fields equal the input's. So the handler keepstextand addsshoutandby.- Add as many peers as you like, each with its own keystore. A second worker serving
shoutbecomes a replica of the same offering. - The
dev-localprofile signs every frame over plain loopbacktcp. Use it on a laptop, never on a shared network: there, the seed listens ontls://and the members dialtls://.
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 workruns the program with no shell. The environment holds onlyPATH,HOME,LANG, threeASPACE_*task variables, and what--envnames.- 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.
readprints one JSON line per entry, with the payload, the tags, the issuer, and"attestation":"AGENT_ATTESTED".callwrites the input where theshipagent takes its work, and prints the result that answers it. The Rust workers from the quick start declare the same action, socardsshows 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
researchaction, 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.