AgentSpaces for Clojure
Write an agent as one defagent form and start a peer from a plain config map. The Clojure library drives the Java binder, so a Clojure peer joins any AgentSpaces fleet with every verb and capability a Java peer has.
Introduction
AgentSpaces lets programs coordinate through shared, replicated memory with no broker. The Clojure library, agentspaces-clj, hands you that memory as maps, keywords, and functions. A Clojure peer is a JVM peer, and it works in one group with Java, Python, TypeScript, and Ruby peers.
The words this guide uses:
- Peer: one running process in the fabric.
fleet/startmakes one. - Group: the set of peers that share spaces. A peer joins a group through a seed, another peer it already knows.
- Space: a named, replicated store of entries inside a group, such as
orders. - Entry: one typed record in a space. In Clojure you write and read entries as maps.
- Lease: how long an entry, or a claim on one, lives. An entry nobody renews disappears.
- Take: an exclusive claim on an entry. If the taker dies before it completes, the take lease lapses and the entry comes back for another worker.
- Agent: code bound to a peer that reacts to entries.
defagentdefines one. - Capability: a fleet-wide service a peer provides, such as voting or the ordered log.
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 Clojure shows how a Clojure peer issues and finds each card.
Install
You need Java 21 or newer and the Clojure CLI. The library pulls the AgentSpaces 0.7.0 Java libraries from Maven Central. Clojars has agentspaces-clj 0.6.0; the 0.7.0 bindings, which this guide describes, install from a clone of agentspaces-clj. Install them into ~/.m2 once:
git clone https://github.com/badmonkeyai/agentspaces-clj.git cd agentspaces-clj && clojure -T:build install
Then name the library in deps.edn. The coordinate resolves from ~/.m2:
;; deps.edn :deps {org.clojure/clojure {:mvn/version "1.11.1"} ai.badmonkey.agentspaces/agentspaces-clj {:mvn/version "0.7.0"}
To build against the clone without installing it, replace :mvn/version with :local/root. The quick start project used below does that, and it also puts the compiled entry classes on the path:
;; deps.edn {:paths ["classes"] :deps {ai.badmonkey.agentspaces/agentspaces-clj {:local/root "../../agentspaces-clj"}}}
Installing from a clone says when each one fits.
Entries are Java records
Every peer, in every language, agrees on entry types by name. On the JVM an entry type is a Java record, so you keep one small Java file per type. The shop in this guide starts with two:
// src/shop/Order.java package shop; public record Order(String orderId, String item) { }
// src/shop/Shipment.java package shop; public record Shipment(String orderId, String item, String by) { }
Compile them once into classes/:
mkdir -p classes && javac -d classes src/shop/*.java
After that you rarely touch the classes:
- A write takes a map and builds the record through its constructor. A Clojure long fills an
intfield. - A read or a take returns a map. The record rides along in the map's metadata, and
core/rawgets it back. - You can still build a record with interop, such as
(Label. id address), wherever a map would do.
Your first agent
The fulfiller takes each Order from the space orders and writes a Shipment back. One file holds the agent and the peer that runs it.
;; fulfiller.clj (ns shop.fulfiller (:require [agentspaces.agents :as agents :refer [defagent]] [agentspaces.fleet :as fleet] [agentspaces.space :as space]) (:import (shop Order Shipment))) (defagent Fulfiller {:description "Ships orders"} (take ship [^Order order] {:space "orders" :lease "30s"} ^Shipment {:orderId (:orderId order) :item (:item order) :by "fulfiller"})) (let [[port seed item] *command-line-args* ; clojure -M fulfiller.clj 7702 127.0.0.1:7701 kite system (fleet/start {:bind (str "127.0.0.1:" (or port 7701)) :group {:name "shop" :founding "shop-v1" :seeds (if seed [seed] []) :spaces [{:name "orders"}]}})] (agents/bind! system (->Fulfiller)) (if item (let [orders (fleet/space system "orders")] (space/write! orders Order {:orderId "o-1" :item item} {:lease "10m"}) (println (space/read orders Shipment {:timeout "30s"})) (fleet/stop! system)) @(promise)))
What each part does:
defagentnames the agent and lists its verbs. This one has a singletakeclause calledship.[^Order order]names the entry type the clause takes. The order arrives as a map.{:space "orders" :lease "30s"}are the verb's options. The agent may hold an order for 30 seconds before it returns to the space.^Shipmenton the body names the entry type the clause writes. The body returns a plain map, and the library turns it into aShipment.fleet/startstarts a peer from a config map.agents/bind!attaches the agent to the peer and starts its take loop.- Given an item argument, the program also writes an order and reads the shipment.
Run two instances
Compile the records. Start the first instance and leave it running, then run the second in another terminal:
clojure -M fulfiller.clj clojure -M fulfiller.clj 7702 127.0.0.1:7701 kite
The first instance has no seeds, so it founds the group shop on port 7701. Both instances compute the same group id from the founding text shop-v1. The second binds port 7702, dials the first as its seed, writes order o-1, and prints the shipment as a map. Either instance may ship the order, because both run the fulfiller.
The quick start leaves :security out, so it runs under the default :dev-local profile. Set the profile in every config instead, as the tested shop programs do. They share this helper, and the examples below call it as peers/start:
;; peers.clj (defn config "Peer config on 127.0.0.1:`port`; `seed` is a port or \"host:port\" (nil founds)." [port {:keys [seed spaces extra] :or {spaces [{:name "orders"}]}}] (merge {:bind (str "127.0.0.1:" port) :security {:profile :dev-local} :group {:name "shop" :founding "shop-v1" :seeds (cond (nil? seed) [] (number? seed) [(str "127.0.0.1:" seed)] :else [seed]) :spaces spaces}} extra)) (defn start "Starts a peer on `port` with the shared settings." ([port] (start port {})) ([port opts] (fleet/start (config port opts))))
dev-local profile authenticates each connection with a signed handshake and sends frames over plain TCP. Use it on a laptop, never on a shared network. Production fleets use :security {:profile :mtls}.A second verb: bid
In an auction space, the cheapest bidder gets the take. A bid clause returns a price as a double. Every peer registers the space with :strategy :auction, and the space collects bids for its settle window before it picks a winner.
;; step06.clj ;; every peer registers the space with the auction strategy: the lowest bid takes (def spaces [{:name "auction" :strategy :auction :settle "500ms"}]) (defn price-a [order] (double (count (:item order)))) ; A bids the item's length (defn price-b [_order] 5.0) ; B always bids 5 (defagent PricerA {:name "pricer" :description "Bids the item's length"} (bid price [^Order order] {:space "auction"} ^double (price-a order)) (take ship [^Order order] {:space "auction"} ^Shipment {:orderId (:orderId order) :item (:item order) :by "A" :note ""})) (defagent PricerB {:name "pricer" :description "Always bids 5"} (bid price [^Order order] {:space "auction"} ^double (price-b order)) (take ship [^Order order] {:space "auction"} ^Shipment {:orderId (:orderId order) :item (:item order) :by "B" :note ""}))
Peer A binds PricerA and peer B binds PricerB. Peer A ships the kite and the tent for 4.0, and peer B ships the bicycle for 5.0. Both definitions carry {:name "pricer"} because a defagent takes no constructor arguments. Two peers that need different behavior bind two definitions under one agent name.
The other everyday verb is notify. A notify clause runs for every matching entry and leaves the entry in place, so several agents can each see it. Use it for receipts, tracking, and audit. defagent and its verbs lists the rest.
Where to read next
- Key features covers the config map, every verb, the capabilities, values that change, a database on a ref, the REPL workflow, and the Java side.
- Babashka reads a fleet from a shell script with
bb as, and hosts a space for development. - In the console runs Clojure cells beside Groovy ones in a desktop notebook.
- Examples walks through crash recovery, a vote, and exactly-once payment.
- The developer guide's Clojure summary maps this library onto the Java chapters, and the verb chapters explain each verb's semantics.
- The architecture guide explains replication, leases, and membership. The workflow guide shows the coordination patterns.
- For other languages, read the Python, TypeScript, Groovy, Ruby, and Rust guides.
Key features
The four cards in Clojure
A Clojure peer runs on the Java binder, so each card is the Java record of its name in ai.badmonkey.agentspaces.api.ad. The system's :discovery is the Java discovery service, and a reify of java.util.function.Predicate filters its cache.
| Card | Issue it | Find it |
|---|---|---|
| AgentCard | (agents/bind! peer agent) publishes the card; (agents/card bound) shows it as a map | (remote/actions peer) lists the actions the cards declare; .find on (:discovery system) with AgentCard |
| AssetCard | a :store block's content store publishes its own card; the Java connector SDK (ConnectorRuntime) publishes one per asset | .find with AssetCard |
| ModelCard | .publish on the discovery with a signed ModelCard record | .find with ModelCard, testing .serves or .residentAt |
| AppCard | .publish on the discovery with a signed AppCard; agents/app-card-origin and agents/app-card-host build its groups | .find with AppCard, testing .fromOrigin or .handles; agents/resolve-card fetches a large card's parts |
semantic/query ranks AgentCards, AssetCards, and AppCards by meaning. Step 8 of the Jungle Gym binds the fulfiller on peer A and lists the actions of its card on peer B:
;; step08.clj (let [bound (agents/bind! peer-a (->Fulfiller))] (println "peer A published the card of" (:agent (agents/card bound))))) ;; ... (let [actions (remote/actions peer-b) _ (doseq [a actions] (println "found card" (:agent a)))
A test signs an AppCard, publishes it, and finds it again by its origin:
;; card_spill_test.clj (.publish discovery (.sign (AdvertisementSigner.) stub (:identity system))) (let [cached (first (.find discovery AppCard (reify java.util.function.Predicate (test [_ a] (.fromOrigin ^AppCard a "console")))))] ;; ... (is (= full (agents/resolve-card system cached)))
Read cards, the ad cache, and the ads stream for every field of each card.
One call starts a peer
fleet/start takes one map and returns a system map. The keys mirror the Spring starter's properties, so moving a config between a Clojure peer and a Spring Boot peer mostly means renaming keys. Only :group is required.
| Key | What it sets |
|---|---|
:bind | "host:port" to listen on. Leave it out for a dial-only peer. |
:security | {:profile ...}, one of :dev-local, :mtls, :mtls-oidc, :zero-trust |
:group | :name, :founding, :seeds, :spaces, and the ways to join covered in Groups |
:capabilities | the fleet services this peer provides, covered in Capabilities |
:content | the content swarm for large artifacts |
:agents | true publishes bound agents' cards even without a capability |
:keystore | a directory that keeps this peer's identity across restarts |
:time | the node's clock, a TimeSource; a test passes a VirtualTime and moves time with no real wait |
:watchdog | {:escalation :report :hold-limit "5m"}: :exit ends the process when the loop watchdog escalates |
:ttl | {:strict true} refuses to start on a TTL under 60 s, unless :expert-overrides names it |
The system map holds what fleet/start built. fleet/space returns a space by name, fleet/peer-id returns the peer's id, and fleet/stop! closes everything. The raw Java objects stay reachable too, under keys such as :node, :runtime, and :facade.
With no :security key the profile is :dev-local. The Spring starter defaults to mtls, so a config copied from one to the other changes its security silently. Write :security into every config. The OIDC profiles also need an Authorizer you build and pass under [:security :authorizer]. Read security levels before you pick one.
This peer joins a group founded by a Java peer on port 7701:
;; step11.clj (def peer-d-config {:bind "127.0.0.1:7704" :security {:profile :dev-local} :group {:name "shop" :founding "shop-v1" :seeds ["127.0.0.1:7701"] ; the Java peer A :spaces [{:name "orders"}]}})
The node loop, the watchdog, and TTLs
A peer has no tick to set. Its node loop runs each job, such as a probe, a lease sweep, or a retry, when that job's deadline comes up or a frame arrives, and sleeps in between. Three keys of the config map shape it:
:timegives the node its clock. Every part of the peer reads time from it, so a test can pass aVirtualTime, advance five minutes, and check what happened, with no real wait.:watchdogsets what happens when the loop stalls.:escalation :report(the default) marks the loop down and keeps running;:exitends the process, for a host whose supervisor restarts it.:hold-limitstops renewing the take of an ordered handler held longer than that.:ttlis the TTL floor. A lease or member TTL under 60 s logs a warning,{:strict true}refuses to start instead, and{:expert-overrides {"<property>" "reason"}}lets one key through. Under a strict floor,agents/bind!also refuses an agent whose take lease is under 60 s.
fleet/loop-health reads the loop's state as the watchdog judges it, and fleet/on-loop-health! calls a function on each change. A test in the library starts a peer with a watchdog and reads both:
;; fleet_parity_test.clj (let [a (fleet/start (config "clj-watchdog" (free-port) nil {:watchdog {:hold-limit "5m" :escalation "exit"}})) seen (atom [])] (try ;; ... (is (= :ok (:state (fleet/loop-health a)))) (fleet/on-loop-health! a #(swap! seen conj %)) (finally (fleet/stop! a))))
configis the test's helper that builds afleet/startmap; the last map holds the top-level keys.- The health is a map,
{:state :ok :reasons []}, whose state is:ok,:degraded, or:down. A host with a liveness probe reports:downas not live. - The listener runs on the loop's thread or the watchdog's, so it must be quick.
The developer guide's node loop section explains the deadlines, and TTLs explains the floor.
defagent and its verbs
Each clause in a defagent has the shape (verb method-name [^Type param] opts ^ReturnType body). The options are the Java annotation's attributes in kebab case: :space, :lease, :poll-timeout, :result-space, :tags, :where, :prefix, :key, :parts, :mode, and :produces. The macro writes a Java interface that carries the annotations, plus a constructor ->Name. The Java binder runs the result unchanged.
| Clause | Java annotation | What it does | Needs |
|---|---|---|---|
take | @SpaceTake | claims an entry and writes the result | nothing |
notify | @SpaceNotify | runs for each matching entry and leaves it in place | nothing |
bid | @BidFunction | prices an entry in an auction space | a space with :strategy :auction |
ballot | @Ballot | casts one vote on each matching proposal | :vote |
on-decision | @OnDecision | runs once when a vote closes | :vote |
propose | @Propose | opens one vote per cue key | :vote |
join | @SpaceJoin | waits for every part with one key, then fires once | :ordered under :mode :ordered |
reduce | @SpaceReduce | folds each element into an accumulator per key | :ordered under :mode :ordered |
ordered-take | @OrderedTake | takes through the ordered log, exactly once | :ordered |
on-estimate | @OnEstimate | runs once when an aggregate estimate settles | :aggregate |
A clause body can return several things:
- A map under a record hint becomes that record.
nilcompletes the take and writes nothing. In aballot,nilabstains.- A vector forks into one entry per element. Leave the return hint off and list the types under
:produces. agents/motionopens a vote,agents/contributionfeeds the aggregate, andagents/taggedwrites an entry with tags.
Here a packer forks an Order into a Label and an Invoice, and an assembler joins the two by orderId into a Parcel:
;; step07.clj (defagent Packer {:description "Splits an order into a label and an invoice"} (take pack [^Order order] {:space "orders" :produces [Label Invoice]} (println "packer forked" (:orderId order) "into Label and Invoice") [(Label. (:orderId order) "12 Vine St") (Invoice. (:orderId order) 2500)])) (defagent Assembler {:description "Joins a label and an invoice into a parcel"} (join assemble [^Joined parts] {:space "orders" :key "orderId" :parts [{:value Label} {:value Invoice}]} ^Parcel (let [label (core/from-entry (.get parts Label)) invoice (core/from-entry (.get parts Invoice))] (println "assembler joined" (.key parts) "into Parcel") {:orderId (.key parts) :address (:address label) :cents (:cents invoice)})))
A join receives the Java Joined object. (.get parts Label) returns one part's record, and core/from-entry turns it into a map. The agent's name defaults to the lowercased form name, so this one is assembler. agents/card returns the bound agent's card as a map, with the types it consumes and produces.
Capabilities: the :capabilities map
Some verbs need a fleet service under them. A ballot needs the vote capability, for example. You switch services on with the :capabilities key, and agents/bind! fails with the missing capability's name if a verb needs one you left out. Each service also has a namespace of plain functions for use outside an agent.
| Config | Namespace | Functions |
|---|---|---|
:vote {:space "votes"} | agentspaces.vote | propose!, cast!, proposal, tally, decision, on-decision! |
:aggregate true | agentspaces.aggregate | start!, estimate, await-settled (:settle, :tolerance, :timeout), on-estimate! |
:ordered {:space .. :members [..] :seed n} | agentspaces.ordered | take!, complete!, leader? |
:semantic true | agentspaces.semantic | query, remote-query |
:learn true or {:metrics "metrics"} | agentspaces.learn | start!, model, round, end-epoch! |
:agents true | agentspaces.remote | actions, invoke! |
:content {...}, a top-level key | agentspaces.content | publish!, fetch!, await, progress, read-bytes, list-manifests |
The content swarm moves large artifacts in pieces, from every peer that holds a copy. Here peer A publishes a 4 MiB checkpoint, and any other peer fetches it by its root:
;; step12.clj ;; each peer starts with this: the content swarm, with its pieces kept in memory (def content-config {:content {:piece-size "256KiB" :store {:backends [:memory]}}}) (defn publish [peer-a] (let [artifact (checkpoint) manifest (content/publish! peer-a artifact {:name "checkpoint-1"})] (println "peer A published checkpoint-1:" (:size manifest) "bytes") (sha-256 artifact))) (defn fetch-checkpoint [peer] (let [manifest (wait/manifest-named peer "checkpoint-1") ; replicated by the space fetch (content/fetch! peer (:root manifest))] (when (content/await fetch "30s") fetch)))
The aggregate's settle rule is a duration. (aggregate/await-settled peer "load" {:settle "8s" :tolerance 0.001 :timeout "30s"}) blocks until the estimate has held within the tolerance for 8 seconds, as Java's @OnEstimate(settle = "PT8S") does. The older :ticks count is read as rounds of about a second.
In that program peer B fetches the checkpoint, peer A stops, and peer C still fetches every piece from B. wait/manifest-named polls content/list-manifests. Read capabilities and the content swarm for depth.
Values that change: agentspaces.pdt
An entry never changes, so a large map that changes often used to cost every reader a whole new fetch. A persistent value is a map, set, vector, or blob held as a tree of hashed nodes, after Clojure's own collections: an update copies the path to the change and shares the rest, so one small change ships only its delta.
A ref is a named, leased entry that points at the current root. The agentspaces.pdt namespace hands you both as Clojure values: get-in, assoc-in, transient, deref, and add-watch work on them.
Switch it on with a :pdt block beside :content (the trees travel over the content swarm):
;; pdt_test.clj [agentspaces.pdt :as pdt]) ;; ... :pdt {:space "pdt" :store {:kind :memory} :load-timeout "20s" :collect-every "0ms"} ;; ... (let [facts-a (pdt/ref a "facts" :map) facts-b (pdt/ref b "pdt" "facts" :map) claim {:text "water boils at 100 C" :score 3 :tags [:physics :water]}] (let [written (pdt/swap! facts-a assoc-in [:claims "c1"] claim)] (is (= claim (get-in written [:claims "c1"]))) ;; ... (is (await-truthy 20000 #(= claim (get-in @facts-b [:claims "c1"])))) (is (= (pdt/root @facts-a) (pdt/root @facts-b))) (pdt/swap! facts-b update-in [:claims "c1" :score] inc) ;; ... (add-watch facts-b :test (fn [k r old new] (swap! fired conj {:key k :ref r :old old :new new}))) ;; ... earlier (pdt/history facts-a 10)]
pdt/reftakes the system, an optional space name, the ref's name, and a kind::map,:set,:vector,:blob, or:tree. One handle per name.pdt/swap!applies a function to the current value and writes a new head;@facts-bon the other peer derefs the same root once the delta lands. A delta of 32 KiB or less rides on the head itself.transient,assoc!,conj!, andpersistent!batch many changes into one delta, and give the same root as the path copies would.pdt/history,pdt/at, andpdt/headsread earlier versions;pdt/on-conflictreports a key two writers changed at once;pdt/blobandpdt/publish-treehandle files and directories.:store {:kind :memory}suits a test. Use{:kind :pack :path "..."}in a real peer so the nodes survive a restart.
Two more kinds of value come with the namespace:
- Long vectors.
pdt/splice,pdt/insert-at,pdt/subvec, andpdt/catvecedit a vector in the middle and copy only the nodes on the paths they touch. On a plain vector they act asclojure.corewould. - Texts. A
:textref holds a map whose values are texts.pdt/textmakes one under this peer's replica, andpdt/insertandpdt/deleteedit it. Edits that two peers make at once meet in the union of their characters, with no conflict:
;; pdt_test.clj (let [notes-a (pdt/ref a "notes" :text) notes-b (pdt/ref b "notes" :text) ;; ... (pdt/swap! notes-a assoc :doc (pdt/text a "ac")) ;; ... (pdt/swap! notes-b update :doc pdt/insert 1 "b") (is (await-truthy 20000 #(= "abc" (text-of notes-a))))
agentspaces.pdt has no function of its own yet for pushed deltas, verified windows (PBlob.openVerified), or sharing a ref into a second group (Pdt.share). These are calls on the Java facade, which the developer guide shows.
Each head renews at half its lease while its writer runs, and the writer cancels a head about 2 s after a newer one replaces it, so readers see one head again. Read values that change for the Java facade, the sealing modes, and the keys.
A database on a ref: agentspaces.datascript
agentspaces-datascript keeps a DataScript database on a persistent ref, so every member of the group reads the same database and a restarted peer comes back without a replay. It is a separate library, so agentspaces-clj pins neither DataScript nor its sorted sets:
;; deps.edn :deps {org.clojure/clojure {:mvn/version "1.11.1"} ai.badmonkey.agentspaces/agentspaces-clj {:mvn/version "0.7.0"} ai.badmonkey.agentspaces/agentspaces-datascript {:mvn/version "0.7.0"}
This is the Superfriends graph's own deps.edn. Clojars has agentspaces-datascript 0.6.0 only, built for agentspaces-clj 0.6.0. Its 0.7.0 is not published, and its source is not yet public.
datascript-conn takes the system, the ref space, the ref's name, and a schema, and returns a DataScript conn. d/transact! on it writes the next head, and the other member reads the same database:
;; datascript_test.clj (def schema {:person/name {:db/index true} :person/email {:db/unique :db.unique/identity}}) ;; ... (let [conn-a (pdt-ds/datascript-conn a "pdt" "graph" schema) conn-b (pdt-ds/datascript-conn b "pdt" "graph" schema) heard (atom [])] (d/listen! conn-b :test #(swap! heard conj %)) ;; ... (d/transact! conn-a [{:person/name "Ada" :person/email "ada@example.org"}]) ;; ... (is (await-truthy 20000 #(= "Ada" (:person/name (d/entity @conn-b [:person/email "ada@example.org"])))))
What the conn does for you:
- A transaction's datoms ride on the head as its tail, so the other members apply them within a gossip round.
d/listen!callbacks hear a change another member made, with:agentspaces.datascript/remotein its:tx-meta. - Past 128 tail datoms, or 30 s after the last fold (
:fold-every), the conn folds the tail into the indexes and writes only the changed paths.(pdt-ds/fold! conn)folds now. - A peer that restarts over a pack store opens the conn from the head and answers its first query after a handful of node reads. Pass
{:await-head "30s"}to wait for the head at open. (pdt-ds/stats conn)returns the node reads, the root, and the tail length.(pdt-ds/close! conn)stops the fold timer and the watch.
The ref is linear: one writer at a time. When another member moves the ref between your read and your write, d/transact! throws an ex-info whose data holds :agentspaces.datascript/moved, and you retry. For several writers, add :refs {"graph" {:mode :multi}} to the :pdt block. Two heads then merge by datoms, and a clash on a cardinality-one attribute settles on the later head on every member.
Python, TypeScript, and Ruby peers read the same database through their DbReader (lookups, entities, and datoms, with no Datalog). Read a database on a ref for the rules every port follows.
A store for the fleet: store-pin! and challenge!
A content store is a member that holds bytes for the group, so a value outlives the peer that wrote it. A :store block turns a system into one, and any member asks it to hold a root with pdt/store-pin!:
;; pdt_store_test.clj a (fleet/start (config "clj-pdt-store" port-a nil {:store {:name "site-a" :capacity "64MiB" :accept-requesters :open}})) ;; ... (let [facts (pdt/ref b "facts" :map) value (pdt/swap! facts assoc "invoice-1" "paid" "invoice-2" "open") root (pdt/root value)] ;; ... (let [pinned (pin-when-a-card-arrives b root {:copies 1 :lease "1h"})] ;; ... (let [result @(pdt/challenge! b root store-peer)]
store-pin!picks stores from their cards and writes one signed pin naming them. It throws when no store fits yet, for example before the store's card has arrived, so the test retries.(pdt/store-status system root)shows each store's receipt: the store, the bytes it holds, and the lease's end.challenge!makes a store send random pieces of the root and returns a future with:passed,:picks, and:proven.:accept-requesters :openlets every member store. The default,:grant, needs an authorizer, and a store without one waits and takes no pins.
Read a store for the fleet for the store's keys, blind stores, and what happens after a crash.
The REPL workflow
Agents bind and unbind at run time, so you can grow a fleet from the REPL. Start a REPL with clj in the project directory, after the records are in classes/. Then:
- Require the namespaces from the fulfiller's
nsform, and(import '(shop Order Shipment)). - Start a peer and keep its system map in a var:
(def peer (fleet/start config)). - Evaluate a
defagent, then bind it and keep the handle:(def bound (agents/bind! peer (->Fulfiller))). - Look around.
(agents/card bound)shows the card, and(space/read-all (fleet/space peer "orders") Shipment)lists every shipment. - Change the agent. Call
(agents/unbind! bound), edit and re-evaluate thedefagent, and bind it again. - Call
(fleet/stop! peer)when you are done, which frees the port.
unbind! can still claim one more entry. Wait a second or two before you write the next test entry, as the crash example does.For pure data work, space/local makes a space with full lease semantics and no network. The same verbs and the same :where maps work on it:
;; REPL (def work (space/local "work")) (def h (space/write! work TaskEntry {:topic "indexing" :priority 3} {:lease "10m"})) (space/read work TaskEntry {:where {:topic "indexing"} :timeout "1s"}) (space/read-all work TaskEntry {:where {:priority [:gte 3]} :limit 50}) (space/renew! h "10m") (space/cancel! h)
A :where map matches plain values by equality. A vector names an operator, such as [:gte 3], [:in "us" "eu"], or [:contains "risk"]. Any Clojure function, such as odd?, works as a predicate.
renew! extends a lease to at least the given time from now, and it never shortens one (SPEC ยง7.2):
- A renewal for less than the lease has left succeeds and changes nothing.
- To end an entry sooner,
cancel!it. To keep it with a shorter lease, cancel it and write it again. - Only the writer of an entry renews it, and only while the entry is still there.
In the console
The AgentSpaces Groovy Console is a desktop notebook for small fleet scripts, and its cells take Clojure as well as Groovy. It ships in agentspaces-groovy, and each notebook runs its own peer in a child JVM with Clojure 1.12 embedded.
- New Clojure notebook makes a notebook of Clojure cells, and New Clojure File opens one
.cljeditor. A cell's Language menu switches it between Groovy and Clojure. - A cell runs only when you press Run and returns its last form's value. Definitions persist across cells in a namespace private to that notebook, and Reset Context clears it.
- With the notebook's peer started,
aspace-groupandaspace-spacereturn the peer's group and spaces, and the normal Java space API works on them. - The Recipe Book has Clojure recipes for spaces, data, REST calls, and charts.
A first cell needs no peer:
;; cell.clj (def shipments [{:id "S1" :slack 6} {:id "S2" :slack 30}]) (filterv #(< (:slack %) 12) shipments)
Clojure def values stay in Clojure: they do not become Groovy variables, and Groovy imports are not Clojure imports. The console guide covers install, cells, the fleet explorer, and export.
Runs on the Java binder
The library reimplements nothing. defagent writes an annotated Java interface, and agents/bind! hands the object to the Java AgentBinder. A Clojure peer therefore has everything a Java peer has:
- Every verb in the table above, including the ordered join and reduce.
- A seat in the ordered log. A Clojure peer can be one of the log's voting members.
- Every capability, the content swarm, agent keys, admission rules, and content keys.
Interop stays one step away: import records like any Java class, build one with (Label. ...), and call Java methods on the system map, such as (.allMembers (.membership (:runtime peer))).
Transports work like this:
:transport :tcpand:transport :tlsselect the two built-in transports, and the profile picks one for you. A:tlsmap with a trust store and CRLs switches on enterprise CA mode.:transportalso accepts any JavaTransportobject. The QUIC, DTLS, and WebSocket bindings ship as separate Java artifacts (agentspaces-transport-quic,agentspaces-transport-dtls,agentspaces-transport-http). Add the one you need todeps.ednand construct it yourself. The library's own tests cover TCP and TLS only.
Three choices differ from the Spring starter. One system serves one group, so start one system per group and share an identity through :identity. Spaces write as the agent clj, where the starter writes as app, so set :group {:agent "app"} when admission rules name the starter's agents. OIDC wiring is yours to add.
Groups: found, join by id, or use multicast
A config identifies its group in exactly one of three ways. fleet/start refuses a config that mixes them before it binds a port.
:founding "shop-v1": every member derives the same group id from the text. This is the simplest choice when members share configuration. Nobody can join such a group by id.:found true: this peer signs the group's founding document, and the id is the hash of that document.fleet/group-urireturns theaspace://address to hand out.:join "aspace://...": the peer fetches the founding document from a seed, checks that it hashes to the id, and only then joins.
;; founder.clj (def founder (fleet/start {:bind "127.0.0.1:7590" :group {:name "research" :found true :spaces [{:name "tasks"}]}})) (fleet/group-uri founder) ;=> "aspace://zB3YQ..." hand this out
A joining peer's :group repeats the :name, gives the address, and names at least one seed: {:name "research" :join (fleet/group-uri founder) :seeds ["127.0.0.1:7590"] :spaces [{:name "tasks"}]}. Add :security to both configs, as everywhere else.
On a LAN, :multicast true lets peers find each other with no seeds. Each peer sends its signed advertisement to 239.255.42.99:7787 when it joins, then on a slow schedule of 1, 2, 10, and 20 minutes that repeats, and a receiver verifies it before it dials. {:multicast {:group "239.255.42.99:7787" :interval "2s"}} changes the address or the interval. Finding the group covers seeds, locators, and beacons in depth.
Installing from a clone
The 0.7.0 bindings are not on Clojars, which has 0.6.0. Install them from a clone in one of two ways:
clojure -T:build installin the clone putsagentspaces-clj0.7.0 into~/.m2, and{:mvn/version "0.7.0"}resolves from there. Use it for applications. The jar holds source only, with no AOT, so it runs on whatever Clojure your project brings.:local/rootpointing at the clone, when you work on the library itself or need a commit newer than the release.
Either way the library consumes the Java artifacts by Maven coordinates, never by a path into a Java build. The 0.7.0 Java artifacts are on Maven Central. To try a Java core built from source, run mvn install in its clone so the artifacts land in ~/.m2. The library's test suite runs real fleets over loopback in about fifteen seconds:
git clone https://github.com/badmonkeyai/agentspaces-clj.git cd agentspaces-clj clojure -M:test
Babashka: read a fleet from a shell
Babashka is a Clojure scripting runtime that starts in milliseconds. agentspaces-bb gives it one command, bb as, with two halves:
- Queries run in Babashka itself.
bb asreads a fleet console's HAL+JSON API under/api/v1and prints one JSON value per command. A query needs no JVM. - Hosting.
bb as servestarts a small JVM peer that holds one replicated space, with a console in front of it. This half needs Java 21 or newer, the Clojure CLI, and the AgentSpaces 0.7.0 jars.
Neither half speaks the AgentSpaces wire from Babashka. A query is an HTTP request to a console, and a host is a Java program that the command starts.
Install Babashka (the library is tested with 1.12.217) and clone the repository. Run bb as from the clone's root, or put its bin directory on PATH and run agentspaces-bb from anywhere. bb as --help lists every command.
git clone https://github.com/badmonkeyai/agentspaces-bb cd agentspaces-bb bb as serve orders --entry '{"orderId":"o-1","item":"kite"}'
That host keeps running. From another terminal in the clone, list the spaces and read the order back:
bb as spaces bb as entries entries '{"item":"kite"}'
serve ordershosts the spaceordersin the group founded from the textagentspaces-bb-v1. It listens on TCP port 7701, and its console on port 8080, both on loopback.--group,--port, and--console-portchange them.--entrywrites one document when the host starts, leased for one hour.- In
entries entries, the first word is the command and the second is the host's built-in panel. The JSON map keeps only the records whose top-level fields equal it.
A second host on the same machine replicates the space. Give it its own ports and the first host as its seed, then point a query at its console:
bb as serve orders --seed 127.0.0.1:7701 --port 7702 --console-port 8081 AGENTSPACES_URL=http://127.0.0.1:8081 bb as entries entries
To query any fleet that runs a console, set AGENTSPACES_URL to the console's base URL. The default is http://127.0.0.1:8080.
| Command | What it prints |
|---|---|
bb as overview, peers, ads, spaces, or panels | the console's document of that name |
bb as space NAME | the console's statistics for one space |
bb as panel ID | one panel's data |
bb as entries PANEL [JSON-FIELD-MAP] | the panel's records whose top-level fields equal the map |
A host checks its TTLs at start. A --lease under 60 s logs a warning, and --ttl strict refuses to start instead unless --lease-reason TEXT says why. bb as health prints the host's loop state (OK, DEGRADED, or DOWN) with its reasons, and exits 1 when the loop is down, so a supervisor can use it as a liveness check. --watchdog exit makes the host stop itself when the watchdog escalates.
Each command prints one JSON value on standard output, so a shell script or a CI job can read it. An error goes to standard error with exit status 1, and an empty match prints []. The console's sign-in gates only its command routes, so these reads need no token.
A console shows a space's records only through a panel. Register one on the peer that holds the space. This Java program, the repository's example, exposes a space of Order records:
// examples/OrdersConsole.java // Register this panel on an existing host to expose its own space. var panel = new ConsolePanel() { public String id() { return "order-entries"; } public String title() { return "Orders"; } public Object data() { return orders.readAll(Template.of(Order.class), 100); } }; try (var console = FleetConsoleServer.builder(view).panel(panel).build()) {
Start it with cd examples and java -cp "$(clojure -Spath)" OrdersConsole.java. Then bb as entries order-entries '{"item":"kite"}', run from the clone's root, prints [{"orderId":"o-1","item":"kite"}]. Under the Spring starter, a ConsolePanel bean adds the same document to the starter's console.
From a Babashka script, put the clone's src on the classpath and call the client. Each call returns the parsed JSON, with string keys:
(require '[agentspaces.bb.client :as as]) (as/query "http://127.0.0.1:8080" :spaces) (as/entries "http://127.0.0.1:8080" "order-entries" {"item" "kite"})
What it does not do:
- It writes nothing from Babashka. It cannot write, take, or complete an entry, so a
bbscript cannot be a worker. The one write is the--entrydocument a host writes at start. For agents, usefleet/startanddefagenton the JVM. - A query sees only what a panel exposes. The host's built-in panel lists up to 100 records of its own document type. Records of other types in the same space do not show, and the field filter runs in Babashka after the fetch.
- A host is for development. It binds loopback only, over plain TCP, takes a fresh identity at every start, and keeps records in memory until every replica stops or the lease ends. Its group is founded from a text, so another peer joins it with that text and a seed, never by an
aspace://id. - Hosting resolves the 0.7.0 jars through the Clojure CLI, from Maven Central.
The two libraries fit together: agentspaces-clj runs the agents, and agentspaces-bb lets a shell script or a CI job look at the fleet they work in.
Examples
The three examples come from tested programs. Each starts its peers on loopback ports 7701 to 7703 with the peers/start helper from Run two instances, so they all use the dev-local profile. Calls to wait/... are test plumbing that polls with a deadline. To run one, start a REPL as in The REPL workflow with peers.clj and the shop records on the path. Then evaluate the forms, start the peers, and call the function.
Crash recovery: a lease brings the order back
This example shows the heart of the model. Peer B takes an order and stops before it completes the take. Its lease lapses, the order reappears, and peer A ships it. No code on A handles the failure.
;; step05.clj ;; the fulfiller's language model (a fixed one here; see model.clj) (def model (model/fixed-model)) (defn shipment-for [order by] (let [prompt (str "Write a one-line packing note for: " (:item order)) note (model/chat model prompt)] {:orderId (:orderId order) :item (:item order) :by by :note note})) (defagent FulfillerA {:name "fulfiller" :description "Ships orders on peer A"} (take ship [^Order order] {:space "orders" :lease "30s"} ^Shipment (shipment-for order "A"))) (defagent FulfillerB {:name "fulfiller" :description "Ships orders on peer B, slowly on o-7"} (take ship [^Order order] {:space "orders" :lease "3s"} ^Shipment (do (when (= "o-7" (:orderId order)) (Thread/sleep 60000)) ; B never finishes o-7 (shipment-for order "B")))) (defn crash [peer-a peer-b bound-a] (let [orders (fleet/space peer-a "orders")] (agents/unbind! bound-a) ; only B's fulfiller is left (Thread/sleep 1500) ; A's last 1 s poll ends (space/write! orders Order {:orderId "o-7" :item "tent"} {:lease "10m"}) (wait/until-taken orders "o-7") ; B's fulfiller holds o-7 (fleet/stop! peer-b) (agents/bind! peer-a (->FulfillerA)) ; A's fulfiller is back (when-let [s (space/read orders Shipment {:where {:orderId "o-7"} :timeout "20s"})] (println (:orderId s) "shipped by" (:by s) "after peer B stopped") s)))
How it works:
- B's fulfiller holds each order under a 3 second lease and sleeps forever on
o-7. crashunbinds A's fulfiller, so only B can takeo-7.wait/until-takenpolls untilo-7is no longer readable.fleet/stop!stops peer B while it holds the order. Three seconds later the lease lapses ando-7reappears.- A's fulfiller, bound again, takes
o-7and writes the shipment.
To run it, start (def peer-a (peers/start 7701)) and (def peer-b (peers/start 7702 {:seed 7701})), bind (->FulfillerA) on A and (->FulfillerB) on B, and call crash with A's handle. It prints o-7 shipped by A after peer B stopped. The full program first ships six orders through both fulfillers, each exactly once.
The library's repository runs the same kill test with two fulfiller processes in its quick start: agentspaces-clj.
A vote across three peers
Three peers provide the vote capability. Each councillor asks its own language model, a fixed one here: the models on A and B answer yes, the one on C answers no and arrives late, and a clerk prints the decision once.
;; step09.clj ;; every peer registers the space votes and starts with this under :capabilities (def capabilities {:vote {:space "votes"}}) ;; each councillor holds its own model: A and B answer yes, C answers no (def models {"A" (model/fixed-model "yes") "B" (model/fixed-model "yes") "C" (model/fixed-model "no")}) (defn ask-model [who p] (let [prompt (str "Proposal " (:proposalId p) ": " (:question p) " Reply yes or no.") answer (str/lower-case (str/trim (model/chat (models who) prompt)))] (println (str "councillor " who ": model answered " answer)) answer)) (defagent CouncillorA {:name "councillor" :description "Asks its model about each release"} (ballot judge [^VoteCapability$Proposal p] {:space "votes" :prefix "release-"} ^String (ask-model "A" p))) ;; ... (defagent CouncillorC {:name "councillor" :description "Asks its model, then answers slowly"} (ballot judge [^VoteCapability$Proposal p] {:space "votes" :prefix "release-"} ;; a quorum of 2 closes on the first two ballots; C's no arrives after that ^String (let [answer (ask-model "C" p)] (Thread/sleep 3000) answer))) (defagent Clerk {:description "Announces each release decision"} (on-decision announce [^VoteCapability$Decision d] {:space "votes" :prefix "release-"} (println (str "decision " (:proposalId d) ": " (:winner d))))) (defn hold-vote [peer-a peer-b peer-c] (agents/bind! peer-a (->CouncillorA)) (agents/bind! peer-b (->CouncillorB)) (agents/bind! peer-c (->CouncillorC)) (agents/bind! peer-a (->Clerk)) (vote/propose! peer-a {:id "release-1.0" :question "Ship 1.0?" :options ["yes" "no"] :quorum 2})) (def vote-peer {:spaces [{:name "votes"}] :extra {:capabilities capabilities}})
How it works:
:prefix "release-"limits each clause to proposals whose id starts withrelease-.CouncillorB, elided above, isCouncillorAwith"B".- A ballot body returns the chosen option as a string, here the model's answer. The return hint goes on the body's first form.
vote/propose!opens the vote with a quorum of 2. The two yes ballots close it before C's no arrives.on-decisionruns once for the closed vote. The proposal and decision arrive as maps, so(:winner d)works.
To run it, start (peers/start 7701 vote-peer), then (peers/start 7702 (assoc vote-peer :seed 7701)) and the same on 7703. Wait until all three see each other, and call hold-vote. The clerk prints decision release-1.0: yes, and (vote/decision peer-a "release-1.0") returns the tally. The same vote runs as a test in layer4_test.clj.
Exactly once through the ordered log
The ordered log sends every take through a replicated log the members agree on, so each entry is handled exactly once even across a network split. Here three payers on three peers pay one payment exactly once. The full program also averages the peers' loads with the push-sum aggregate, elided here; Capabilities gives its settle rule.
;; step10.clj ;; the ordered log names its members up front, so A, B, and C get their identities first (def identities (vec (repeatedly 3 #(PeerIdentity/generate)))) ;; each peer starts with these under :capabilities; n is 0, 1, 2 for A, B, C (defn capabilities [n] {:aggregate true :ordered {:space "payments" :members (mapv #(.peerId %) identities) :seed (inc n)}}) ; its own election-timer seed (defagent Payer {:description "Pays each payment exactly once"} (ordered-take pay [^Payment p] {:space "payments"} ^Paid {:paymentId (:paymentId p) :cents (:cents p) :by "payer"})) ;; ... (defn pay-once [peer-a peer-b peer-c] (doseq [peer [peer-a peer-b peer-c]] (agents/bind! peer (->Payer))) ; three payers, one log (let [payments (fleet/space peer-a "payments")] (space/write! payments Payment {:paymentId "p-1" :cents 2500} {:lease "10m"}) (when (wait/exactly-one? payments Paid) (println "paid p-1 exactly once") true))) (defn -main [& _] ;; ... (let [start (fn [n port seed] (peers/start port {:seed seed :spaces [{:name "payments"}] :extra {:identity (identities n) :capabilities (capabilities n)}})) peer-a (start 0 7701 nil) peer-b (start 1 7702 7701) peer-c (start 2 7703 7701)] ;; ... ;; ... (wait/check! (pay-once peer-a peer-b peer-c) "p-1 was not paid exactly once") (run! fleet/stop! [peer-c peer-b peer-a])) (wait/done!))
How it works:
- The log runs over a fixed member list, so the program generates the three identities first. Each peer starts with its own identity under
:identityand the same member list under:ordered. :seedgives each member its own election timer, so the members elect a leader quickly.- All three peers bind a payer. The log hands
p-1to exactly one of them, which writes onePaid.
To run it, evaluate the forms and the start function from -main in the REPL, start the three peers, and call pay-once. It prints paid p-1 exactly once. The ordered and aggregate tests in layer4_test.clj do the same over two peers. For how the log decides a take, read the ordered log.