aspace://guide/quick-start

Quick start

AgentSpaces is a Java library that lets agents in different processes coordinate through shared spaces. Its coordination layer, which this guide calls the fabric, is a library inside your application, so you deploy no broker, no registry, and no scheduler.

In this quick start you write two plain classes and run them as a two-peer fleet. One is a worker that tolerates being killed mid-task. The other is an auditor that reacts to every result. They coordinate through one shared space.

The quick start uses these terms:

  • Peer: one running process (your application) with the AgentSpaces library inside it. Each peer has its own identity, a key pair.
  • Group: the set of peers that find each other and work together. Every member computes the same group id from the group's founding text.
  • Space: a named, shared collection of entries. Every peer in the group that registers the space keeps a full copy of it.
  • Entry: a typed record, such as a Java record, written into a space. Its writer signs it.
  • Lease: the time an entry, or a claim on it, stays valid. When a lease runs out, the entry is removed, or a claimed entry becomes available to another worker.
  • Take: claim an entry so that only one worker processes it.
  • Agent: an ordinary class whose annotated methods react to entries, such as @SpaceTake and @SpaceNotify.

The architecture guide helps you decide how to shape a system, and the workflow guide walks through common patterns step by step.

1. Add the starter

Add one dependency to your build. It brings in the starter, the fabric and the annotation binder.

  • Where to get it. The release artifacts are on Maven Central under the group ai.badmonkey.agentspaces, version 0.7.0 (central.sonatype.com). Maven and Gradle resolve Maven Central by default, so you need no repository configuration.
  • Source. The source lives at github.com/badmonkeyai/AgentSpaces.

In Maven:

<!-- pom.xml -->
<dependency>
  <groupId>ai.badmonkey.agentspaces</groupId>
  <artifactId>agentspaces-spring-boot-starter</artifactId>
  <version>0.7.0</version>
</dependency>

To manage versions in one place, import the bill of materials (BOM), agentspaces-dependencies, once. Then leave the version off every core AgentSpaces dependency, whether the starter or individual modules.

  • Bridges carry their own version. The bridge projects for Spring AI, Micronaut, and LangChain4j are not in the BOM.
  • Plain Java. A plain-Java application depends on agentspaces-agent, which brings the fabric with it.

Add the BOM under dependencyManagement:

<!-- pom.xml: dependencyManagement -->
<dependency>
  <groupId>ai.badmonkey.agentspaces</groupId>
  <artifactId>agentspaces-dependencies</artifactId>
  <version>0.7.0</version>
  <type>pom</type>
  <scope>import</scope>
</dependency>

In Gradle, import the same BOM as a platform dependency. Kotlin DSL:

// build.gradle.kts
dependencies {
    implementation(platform("ai.badmonkey.agentspaces:agentspaces-dependencies:0.7.0"))
    implementation("ai.badmonkey.agentspaces:agentspaces-spring-boot-starter")
}

Groovy DSL:

// build.gradle
dependencies {
    implementation platform('ai.badmonkey.agentspaces:agentspaces-dependencies:0.7.0')
    implementation 'ai.badmonkey.agentspaces:agentspaces-spring-boot-starter'
}
  • Spring Boot projects still import the BOM. Import it even if your project inherits from spring-boot-starter-parent or applies the Spring Boot Gradle plugin. Without it, write 0.7.0 on each dependency.
  • What is on Maven Central at 0.7.0. AgentSpaces 0.7.0 was released on 2026-11-28. The core libraries and the BOM, agentspaces-runtime, agentspaces-springai, agentspaces-micronaut, agentspaces-langchain4j, embabel-agentspaces, agentspaces-groovy (with -concurrent and the console), agentspaces-card-contract, agentspaces-example-cards and agentspaces-model-wire are all at 0.7.0.
  • Modules that stay at 0.6.0. The bootstrap family, agentspaces-beacon, agentspaces-connect-celld and agentspaces-commerce did not change for 0.7.0 and were not re-released, so 0.6.0 is their current version. Import the 0.7.0 BOM so the core libraries they pull resolve at 0.7.0. agentspaces-a2ui 0.7.0 builds from its repository, because Central's 0.6.0 writes A2UI v0.9.1, which 0.7.0 does not read.
  • Building from source. No snapshot repository is published. Run mvn install -DskipTests in a clone, then resolve from the local repository (mavenLocal() under Gradle).

The appendix lists what the BOM manages and why Spring Boot projects need it.

2. Describe the fleet, once

The starter reads one YAML block. It names three things:

  • An identity keystore (keystore).
  • A group. Every member computes the same group id from the group's founding text.
  • The spaces the group shares.

To make a fleet, start a second JVM with the same block. Give it its own advertise address and a seed address.

# application.yml
agentspaces:
  keystore: ./peer-keys
  bind: 0.0.0.0:7500
  advertise: peer1.example:7500   # the address other peers dial
  groups:
    - name: orders-fleet
      founding: orders-fleet-v1
      seeds: ["hq.example:7500"]     # omit on the first peer
      spaces: [ { name: work } ]

3. Write the agents

The worker takes orders under a lease and returns shipments. The auditor reacts to every shipment and returns a receipt. Both are complete as shown.

quickstart: orders-fleet
@SpaceAgent(description = "Ships orders from the shared space")
public class Fulfiller {

    @SpaceRef
    private Space space;                    // injected at bind time

    @SpaceTake(lease = "10m")              // crash => order reappears
    public Shipment ship(Order order) {
        space.write(new Progress(order.orderId(), "picking"),
                    Lease.of(Duration.ofMinutes(5)));
        return new Shipment(order.orderId(), order.item(), "fulfiller");
    }
}
✓ binds on startup · worker loop + subscription running · AgentCard published

4. Put work in

spaces.group("orders-fleet").space("work")
      .write(new Order("ord-1", "kite"), Lease.of(Duration.ofMinutes(10)));

Here is what you now have:

  • Every peer sees the order. The space copies it to every peer in the group.
  • One fulfiller takes it. The default strategy is LEASE_RACE. A network split can briefly let two fulfillers work the same order, so make shipping safe to repeat.
  • The results are entries too. The shipment and the receipt appear as signed entries.
  • Crashes are covered. If you kill the working JVM mid-task, its lease runs out and the order reappears for another fulfiller.

Two runnable projects in the repository show the same ideas:

  • examples/example-11-quickstart is the plain-Java form of this pair: two in-process TCP peers, an AgentBinder, no Spring.
  • integration-tests/spring-boot-it boots a smaller application through the starter: one @SpaceTake researcher over a tasks space and a findings space, alone and as a two-application fleet over TCP.
No Spring requiredThe same annotations bind anywhere. Create an AgentBinder, register spaces with binder.space("work", space), and call binder.bind(new Fulfiller()). The starter automates what plain Java does in these three lines.
aspace://guide/architecture · choose your starting point

One fabric, several ways to build

This chapter helps you pick a starting shape for your application. Make two choices: who decides the next step, and how that step is claimed.

AgentSpaces supplies typed entries, leases, discovery, identity, and replication. On top of those, the next step can be decided in three ways:

  • Your application coordinates through the entries directly.
  • An Embabel planner composes typed actions.
  • A Spring AI model chooses fleet tools.

A worker can itself use Spring AI, however its task was created.

The same process may host several roles. Splitting them into separate peers changes how you deploy them and what fails together. It does not require rewriting the request and result types. Do three things from the start:

  • Keep the request and result types in a shared domain artifact.
  • Name your spaces explicitly.
  • Carry a request id through every stage.
Plain Java and Spring agents, Embabel planners, and Spring AI clients share the AgentSpaces fabric. Worker peers, model servers, and data connectors serve entries through separate spaces.
Architecture. Each peer hosts the fabric library. The center represents shared replicated state; there is no central broker. Cards describe capabilities; entries carry the work.
ONE PEER: THE LIBRARY INSIDE YOUR PROCESS@SpaceTake @SpaceNotify @Ballot @SpaceJoin ...annotations, AgentBinder, the AgentSpaces facade (chapters 1 to 4)Layer 4 capabilitiesvote, aggregate, ordered log, gossip learning, semantic discovery, key wrap (chapter 12); large data (chapter 13)Layer 3 spacestyped, leased, signed entries; LEASE_RACE, AUCTION; admission (chapter 10)Layer 2 discoverysigned, TTL-leased cards in a per-group ad cache that gossip keeps fresh (chapter 11)Layer 1 peeringgroups, SWIM membership, gossip; TCP, TLS, QUIC (chapter 14)Layer 0 identityEd25519 peer keys, self-certifying PeerId and GroupId, agent certificates (chapters 13, 14)one loop per peer: each job runs when it falls due, with no fixed tickHOSTS AND CLIENTSJVM hosts: bind annotated objectsSpring Boot + Spring AIchapters 5, 7Embabelchapter 6Micronautchapter 8LangChain4j on any hostchapter 9bindthe same wire, in another languagePythonagentspaces-python, 20.1TypeScriptagentspaces-typescript, 20.2Clojurebinds over the Java artifacts, 20.3
The stack. Five layers inside one peer, the programming model on top of them, and the hosts and clients beside: a JVM host binds annotated objects into the model, the Python and TypeScript peers speak the wire directly, and Clojure and Groovy (20.3, 20.5) bind over the Java artifacts. Each layer registers its jobs with the peer's loop, and each job runs when it falls due, so an idle peer sleeps.

Match the coordination pattern to the job

Use this table to find the pattern that fits your job. Each row links to the section that shows how to build it.

PatternUse it forCore shape and boundary
Competing workersIndependent jobs; horizontal worker pools@SpaceTake on LEASE_RACE. One loop per bound method. A crash releases the work when its lease runs out. Make external effects safe to repeat.
Pipeline / choreographyStable stages with no central plannerA returned entry feeds the next typed take or notify. Use takes for stages that need retries, and notify for broadcast reactions.
Fan-out / ensembleIndependent specialists inspect the same input@SpaceNotify broadcasts. @SpaceJoin joins the branches once per key; its mode picks once per joiner, once per lease, or once fleet-wide. Use @SpaceRef to write explicit tasks when each branch needs retry. within fires nothing, so use the deadline pattern below for a timeout that must act.
ForkOne cue produces several entries, each its own next stepReturn Entries from any bound method and list the element types in produces. From a take, the binder completes once, then writes each element.
RouteOnly some entries of a type belong to this workerwhere filters on a field before a take claims. A sealed return type declares the branches a method chooses between.
GatherA stage waits for several entries of one kind about one case@SpaceJoin with @Part(atLeast), @Part(countedBy) for a count another part declares, or settle for a number nobody knows. Joined.all(type) hands them over.
Running totalA per-case figure that must be exact, current after every entry, and survive a restart@SpaceReduce keeps the running figure in an accumulator entry beside its elements. Its lease is the idle timeout. For a bounded set per case, use the gather. For a fleet-wide figure, use the aggregate.
DeadlineSomething must happen if nothing happens in time@SpaceNotify(on = EXPIRED) over a leased reminder. Every peer holding the reminder sees it lapse, so return a Motion or write an entry the next stage dedups on.
Settled estimateAct once the fleet's figure has stopped moving@OnEstimate fires once per epoch when the fleet's estimate holds within a tolerance for a run of settle steps. A settle rule does not detect a poisoned contribution.
Auction / specializationWorkers differ by price, load, skill, or locality@BidFunction plus @SpaceTake on AUCTION. One bidder per space per peer. Use one comparable cost unit.
Panel / approvalSeveral authorized judgments must agree@Propose or a Motion return opens the vote; @Ballot and @OnDecision judge and record it. Your application chooses the proposal options, quorum, deadline, and voter granularity.
Ordered workA fixed quorum must agree on claim order@OrderedTake with OrderedTakes. Needs a quorum of members available. It does not transact with external services.
Goal-driven orchestrationThe route to a typed goal depends on available skillsEmbabel composes local and generated remote actions. Execution still happens through space entries.
Tool-driven orchestrationA model chooses which fleet skill to call nextFleetTools attached to a Spring AI ChatClient. Attach local tools alongside the fleet provider as needed.
Model serviceCentralize provider credentials or pool model capacityFleetChatModel + ModelServer. Prompts cross the group; tools execute in the caller’s tool loop.
Shared retrieval / RAGMany agents query one knowledge baseVectorStore connector + discovery data tools. Retrieval results are leased; this does not automatically inject context into prompts.
Fleet sensing / learningApproximate fleet statistics or decentralized modelsContribution / AggregateClient and GossipLearner. Estimates and learning rounds are not transactional decisions.
Hybrid / gatewayExpose a curated fleet boundary to another applicationCombine an Embabel planner, Spring AI workers, and an MCP or A2A edge. Declare each boundary’s access and routing rules.
Long-running business workflowsBuild a long-running workflow (a saga) from explicit request, success, failure, and compensation entries that carry the same business id. The fabric supplies coordination primitives. It has no automatic saga transaction, durable workflow history, or compensation engine. Keep business records outside short-lived entries when they must outlive the space’s leases.

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.

In Java each card is a record in ai.badmonkey.agentspaces.api.ad: AgentCard, AssetCard, ModelCard, and AppCard. The binder issues AgentCards for you. Cards, the ad cache, and the ads stream in chapter 11 shows how to issue the other three and how to find all four, and the language guides show the same cards in Python, TypeScript, Ruby, Groovy, Clojure, and Rust. The A2UI guide shows how an AgentCard and an AppCard declare the pages a fleet draws for people.

Upgrading from 0.6.0

AgentSpaces 0.7.0 is the current release, out on 2026-11-28. Most applications move to it by changing the version number. No frame kind and no wire version changes, and 0.6.0 and 0.7.0 members replicate together. Read this box before you move a fleet, and the sections it links for the details.

Upgrading from 0.6.0
  • Breaking: the QUIC setter. AgentSpacesProperties.Transport.setQuic(Listener) is gone, so code compiled against 0.6.0 that calls it fails to link. Call setQuic(Quic), or set agentspaces.transport.quic.* in configuration. getQuic() keeps its 0.6.0 signature and is deprecated; quicBlock() returns the block.
  • Breaking: two card fields are a flag day. A reader older than SPEC v0.1.38 drops an AgentCard that carries threads and an AppCard of kind dynamic. A 0.6.0 member does not see such an agent or app. Move every member to 0.7.0 before you publish either (threads and dynamic AppCards).
  • Breaking: A2UI 0.9.1 is no longer read. Pages, cards, and catalogs are A2UI 1.0 (A2UI 1.0 final).
  • Breaking: a renewal never shortens a lease. To shorten one, cancel the entry and write it again (replication by entry).
  • Deprecated. GroupRuntime.onTick and tickPeriod(), CapabilityProvider.requiresTick() and driverCadence, @OnEstimate(settleTicks), EmbabelBinder (marked for removal), and Rust PeerEvent::GaveUp. The deprecation table gives each replacement.
  • Changed meaning. agentspaces.tick-millis now paces only the deprecated onTick adapters. It no longer paces the node, which runs each job at its own deadline (time and the node loop).
  • Changed defaults. The member TTL, the multicast interval, Raft's timings, push-sum rounds, the default settle of @OnEstimate, and a warning for any TTL under 60 s (keys changed in 0.7.0).
  • New: a COMPLETED with no WRITTEN. A replica that first learns of an entry already completed raises COMPLETED and no WRITTEN. Do not count on a WRITTEN before every COMPLETED.
  • New: held proposals are heard. @Ballot and @OnDecision hear the proposals and decisions the replica already holds when they bind, as well as later ones, each once per binding.
  • New: a take that cannot win is refused. A take whose lease is not longer than the space's settle window throws IllegalArgumentException at once (take rules).
  • New: readiness follows membership. Under Spring, readiness turns REFUSING_TRAFFIC while the node is isolated in a group. Liveness is untouched (membership status).
  • New: seeds are redialed for ever. A peer never stops redialing its seeds (the redial table).
aspace://guide/annotations · chapter 1

Agents and the binder

An agent is an ordinary object with annotated methods. The binder reads the annotations and turns them into running behavior. The annotations sit at the top of the stack, and they are the whole API most applications need.

Fourteen annotations cover two layers:

  • Layer 3 (spaces): identity, work, choreography, routing, fan-in, economics, and access.
  • Layer 4 (capabilities): voting, settled estimates, exactly-once work, typed clients, and served capabilities.

Each annotation maps to protocol behavior that the layers below carry for you. This chapter covers the facade and the binder, the identity annotation, and the conventions every annotation shares. The next chapters cover the rest:

  • Chapter 2 covers work: take, notify, bid, and the space handle.
  • Chapter 3 covers decisions and fleet sensing.
  • Chapter 4 covers exactly-once work and fan-in.

The annotations go on ordinary objects. You extend no base class, implement no interface, and run in no container of ours. The binder inspects an instance you hand it, wires whatever annotations it finds, and leaves the rest of the class alone. Constructors, other Spring beans, JPA repositories, and your own fields all stay untouched.

Each annotation below says where it belongs and what else may sit beside it.

Where these liveOn any class you can get an instance of. Under Spring, annotate the bean (@SpaceAgent is @Component + @AgentSpec) and the post-processor enrolls it after initialization. Without Spring, call binder.bind(instance) or spaces.bind(instance) yourself. Either way you construct the object normally first; the binder never instantiates anything.
YOUR OBJECT@SpaceAgentclass Fulfiller@SpaceRef Space work@CapabilityRef VoteClient@SpaceTake ship(Order): Shipment@SpaceNotify audit(Shipment): Receipt@Ballot judge(Proposal): String@SpaceJoin(parts=...) assemble(Joined): Casea constructor, otherfields, other methodsTHE BINDERAgentBinder.bind(obj)or spaces.bind(obj): one card per group bound1 inject @SpaceRef, @CapabilityReffields first, before any loop2 wire @BidFunctionone per space per peer3 take loops@SpaceTake, @OrderedTake: a virtual thread each3 subscriptions@SpaceNotify, @Propose, @OnDecision, @OnEstimate3 join and reduce drains@SpaceJoin, @SpaceReduce: per-key state, tickets4 publish the AgentCardidentity + actions, TTL-leased, refreshedWHAT THEY BIND TOspace: workReplicatedSpace or LocalSpacespace: votesvote capability registered on itaggregatePushSumAggregateordered coordinatorOrderedTakes: the ORDERED verbstyped clientsVoteClient, AggregateClient, ...AgentCardname, description, goals, actions, certificatethe ad cachegossiped, verified, evicted by TTLNothing to extend: the binderreflects over the instance youbuilt and leaves the rest alone.
The binder. An annotated object goes in; the binder injects its handles, wires its bid, starts one loop or subscription per bound method against the spaces and capabilities the group registers (step 3 is one pass over the methods, so the loops, subscriptions, and drains start method by method in no promised order), and publishes one AgentCard per group. The failure model follows the verb: a take retries by lease, a notify is logged and dropped.

The facade and the binderAgentSpacesGroupContextAgentBinder

To start an agent, you hand it to a binder. Two objects can do that: AgentBinder, which you build by hand for one group, and the AgentSpaces facade, which sits over several groups.

AgentBinder: one group, by hand

AgentBinder serves one group. You build it from the peer identity, the GroupId, the group's discovery service (or null to publish no cards), and a clock. Register what it may bind to, then bind:

  • space(name, space) for each space.
  • vote(space, capability) for a vote capability.
  • aggregate(pushSum) for the aggregate.
  • ordered(space, coordinator) for an ordered space.
  • client(type, instance) for a typed client.
  • bind(instance) or bind(instance, name) to bind the agent. The name lets one class be several agents.

The AgentSpaces facade: several groups

spaces.group(name) returns a GroupContext. It holds:

  • the group's spaces (space(name));
  • its discovery service (discovery());
  • its typed capability clients (capability(VoteClient.class));
  • the registrations the Layer 4 annotations need: provide(capability), vote(space, capability), ordered(space, coordinator).

To bind through the facade, call one of these:

  • spaces.bind(instance) binds the object into every registered group whose spaces cover the spaces its annotations name, narrowed to the groups the annotations name. It returns one Bound per group.
  • group.bind(instance) binds into one group.

Under the Spring starter the facade is a bean, and the post-processor calls bind for every enrolled bean. The Micronaut enroller and the LangChain4j FleetRuntime.bind do the same.

// examples/example-11-quickstart: one group, hand-built
AgentBinder binder = new AgentBinder(identity, runtime.id(), null, InstantSource.system());
binder.space("work", space);
AgentBinder.Bound fulfiller = binder.bind(new Fulfiller());     // loops running; no card, because discovery is null

// the facade: several groups, one bind
AgentSpaces.GroupContext group = spaces.group("orders-fleet");
group.space("work", work).provide(vote).ordered("payments", ordered);
List<AgentBinder.Bound> bound = spaces.bind(new Clerk());          // one Bound per group the clerk's spaces live in

What binding does, in order

Binding runs in the same order whichever object does it:

  • 1. Fields. The binder injects @SpaceRef and @CapabilityRef fields first.
  • 2. Bids. Bid functions wire next.
  • 3. Methods. One pass over the public methods starts each method's take loop, subscription, join, or reduce. The methods start in the order reflection returns them, which the binder does not fix.
  • 4. Card. Last, the AgentCard publishes. The binder builds it from the identity annotation plus the bound method signatures.

The AgentCard is the agent's published description, which other peers discover. It names the agent, its description and goals, and its space bindings. It lists one action per bound method: what it consumes, what it produces, and the method's description. Under subordinate keys it also carries the agent's public key and certificate.

How the card stays current:

  • It is leased. The card is TTL-leased and republished on the card cadence (agentspaces.card-refresh-millis) wherever a host calls refreshCards().
  • Hosts refresh it for you. The Spring starter, the Micronaut lifecycle, and the LangChain4j runtime call refreshCards(). A hand-built binder or facade republishes only when its caller does.
  • A dead peer's card ages out. A peer that dies stops republishing, so its card ages out of every cache.
  • One card per group bound. An object bound into two groups publishes two.

The Bound handle answers agentId(), card(), and isRunning(). Its close() interrupts the loops and closes the subscriptions. The binder still lists a closed binding, so its card keeps being republished. To stop that, call binder.unbind(agentId) (which also closes it) or the binder's own close(). The card then lapses at its TTL.

Set a group's schema registry before that group's first bind, because the group refuses one after that. The facade's own schemaRegistry(...) only sets the default for groups registered afterward.

Keep in mindA binding is a runtime resource, and the binder never instantiates anything. Construct the object yourself, with whatever it needs, and hand it over. A bean naming a space no group registers fails at bind time, by name, so a configuration mistake shows up early.

@SpaceAgent and @AgentSpecSpaceAgentAgentSpec

Use @AgentSpec to declare an agent's identity on any class, with or without a framework. Binding publishes an AgentCard built from this identity plus the bound method signatures. Other peers can then discover what this agent consumes and produces, with no extra code.

  • Under Spring, prefer the @SpaceAgent stereotype. It is both a @Component and an @AgentSpec, so one annotation gives you component scanning and fleet enrollment.
  • Under Micronaut, use the stereotype of the same name, ai.badmonkey.agentspaces.micronaut.SpaceAgent. It is a bean-defining annotation (a singleton unless the class says otherwise) and also an @AgentSpec, so the enroller binds the bean at startup. It carries the same three attributes.
@SpaceAgent(name = "researcher", description = "Researches topics",
            goals = {"answer research questions"})
public class Researcher { ... }
attributedefaultmeaning
namedecapitalized class namethe agent's local name; the AgentId is the peer id plus this name; an anonymous class has no simple name to decapitalize, so name it here or in bind(agent, name)
description""for humans and semantic discovery; also feeds Embabel planning (Embabel)
goals{}goal statements published on the card
Composed stereotypesThe binder resolves @AgentSpec through one level of meta-annotation. Annotate your own annotation with @AgentSpec, give it name/description/goals attributes, and it works exactly like @SpaceAgent does.

Conventions they shareAgentBinderTagged

These rules hold for every binding annotation in this chapter and the next three. Read them once; the later sections assume them.

  • Space inference. Every space attribute is optional. For @SpaceTake, @SpaceNotify, and @SpaceRef, empty resolves to the group's sole registered space. Vote annotations infer the sole registered vote space; @OrderedTake infers the sole coordinated space. Name the space whenever that choice is ambiguous.
  • Durations. Every duration accepts Spring-style simple strings ("10m", "500ms", "30s", "2h", "1d") and ISO-8601 ("PT10M").
  • Tag filters. @SpaceTake, @SpaceNotify, and @OrderedTake accept tags = {"key=value", "key"}. Each filter requires the tag to equal the value, or to be present. A malformed filter is refused at bind time, naming the method. The appendix explains where the space checks tag filters.
  • Names. An agent's name comes from @AgentSpec (or the class). bind(agent, name) overrides it, so several instances of one class can be several agents: a council of seats, one class.
  • Cards for free. The binder collects consumed and produced types from the signatures and publishes them on the agent's card. The host refreshes the card on the card cadence: the starter, the Micronaut lifecycle, and the LangChain4j runtime do, and a hand-built binder waits for refreshCards().
  • Nothing is reserved. The binder reads the annotations and ignores everything else on the class. Other frameworks' annotations, other interfaces, and other methods and fields all keep working. That is why an Embabel @Action becomes a fleet worker when you add one annotation, with no rewrite.

Group selection

Every binding annotation takes an optional group, by application-facing name or GroupId value. A binder for a different group treats the member as not its own and skips it. So one bean can bind methods into several groups at once.

The facade's bind(...) binds the bean into every registered group whose spaces satisfy its bindings, narrowed to the groups its annotations name. It publishes one card per group bound.

When an annotation names a group this peer has not joined, the result depends on the annotation:

  • Refused by name: the facade refuses the unjoined group for @SpaceTake, @SpaceNotify, @BidFunction, @SpaceRef, @SpaceJoin, @Propose, and @OnEstimate.
  • Skipped: a @Ballot, @OnDecision, @OrderedTake, or @SpaceReduce naming one is skipped. When a ballot, an ordered take, or a reduce never binds, check the group name.

Method shape

Bound methods must be public and take exactly one parameter. For most annotations the parameter is the entry. Some take something else:

  • @Ballot takes the Proposal, and @OnDecision takes the Decision.
  • @OnEstimate takes the PushSumAggregate.Estimate.
  • @SpaceJoin takes the Joined bag of one key's parts.

The one exception to the one-parameter rule is @SpaceReduce. It takes two parameters: the key's accumulator (null on the first step) and one element.

What each method returns:

  • @BidFunction returns double.
  • @Ballot returns the option as a String; null abstains.
  • @Propose returns the question as a String; null asks nothing.
  • The others return the next entry, a Contribution to an aggregate epoch, a Motion that opens a vote, or void.

To write the entry with tags, a method may also return Tagged.of(entry, tags). The binder unwraps it before any other return handling, and the card declares the wrapped type. A same-space take result goes through complete(taken, entry, lease, tags), atomically with the completion.

Where the annotation may sit

The binder reads each binding annotation from the method itself, then from the same-signature method of each superclass, then of each interface. The first declaration wins, and the binder finds @AgentSpec the same way. So all of these bind as workers:

  • a java.lang.reflect.Proxy over an annotated interface;
  • an anonymous subclass of an annotated abstract class. Name it with @AgentSpec(name = ...) or bind(agent, name), since an anonymous class has no simple name and the binder throws when it must derive one;
  • a LangChain4j AiServices proxy whose interface carries @SpaceTake;
  • a Clojure reify of a generated interface.

Choosing between them

Three questions settle almost every case:

  • Should exactly one agent handle this entry? If yes, use @SpaceTake. If every interested agent should see it, use @SpaceNotify.
  • Are the candidate workers interchangeable? If not, put the space on AUCTION, add a @BidFunction, and let the cheapest one take it.
  • Does one trigger produce more than one entry, or entries elsewhere? Then add @SpaceRef and write them yourself. Do not contort a return value to do it.

Special cues have their own answers:

  • Is the cue a vote's proposal or its decision, or must an entry be completed at most once fleet-wide instead of once per lease? Then use @Ballot, @OnDecision, or @OrderedTake, and register the space's capability.
  • Does the cue decide only the question of a vote? Use @Propose.
  • Does it decide the options or the quorum? Return a Motion.
  • Does one stage wait for several entries of different types about the same case? Use @SpaceJoin, a method taking Joined. Its mode says whether each key fires once per joiner, once per lease, or once fleet-wide.
  • Does one cue produce several entries? Return Entries and list them in produces.
  • Should only some entries of the type reach the method? Filter them with where.
  • Is the cue an entry that lapsed? Use @SpaceNotify(on = EXPIRED).
  • Does a stage wait for several entries of one kind? Use a @Part with atLeast or countedBy, or a join settle period.
  • Is the cue a fleet estimate that has stopped moving? Use @OnEstimate.

Hold on to the two failure models, because they decide where risky work belongs:

  • @SpaceTake retries forever by default. A crash, a kill, or a thrown exception all let the lease lapse, and the entry comes back.
  • @SpaceNotify does not retry at all. A reaction that throws is logged and gone.
  • @SpaceJoin depends on its mode. In LOCAL mode it follows the notify model. In LEASED or ORDERED mode it follows the take model, because the ticket it fires from is a leased take.

Put work that must eventually happen behind a take. Put reactions that are nice to have behind a notify.

Execution, completion, and recoveryTakeContext

This section says how each binding runs and what happens when its method fails. Use it to decide where to put work that must not be lost.

  • A binding is a runtime resource. Plain Java constructs the object and calls bind. Spring enrolls initialized beans.
  • Fields arrive at bind time. Space and capability fields are injected during binding, before worker loops start. Keep constructor work independent of those fields.
  • Only public methods bind. Public inherited methods are visible to the binder. Private annotated methods are not worker entry points.
BindingExecution scopeFailure behavior
@SpaceTakeSequential loop per method, on a virtual thread; different methods and instances can run concurrently.An exception before completion leaves the claim to expire. null or void completes without a result. Return a failure record for a handled terminal error.
@OrderedTakeThe same loop, with each take submitted through the space's ordered-log coordinator; a take lost to a leader election is resubmitted on the next poll.The take model: an exception leaves the claim to lapse and the entry reappears, and the log guarantees at most one completion per entry generation, fleet-wide.
@BidFunctionCalled inside the claim path for each candidate entry on an AUCTION space, possibly many times per entry; one bid function per space per peer.No retry and no lease: keep it pure and quick, and keep side effects out of it. A LEASE_RACE space never calls it.
@SpaceNotifyA virtual thread per WRITTEN event; a bounded, in-memory entry-id dedup set per subscription.Exceptions are logged. There is no automatic reaction retry or durable dedup across rebinding/restart. Synchronize mutable bean state shared by concurrent reactions.
@BallotProposal-id dedup per binding; virtual-thread judgment; null abstains.A failed cast removes the local dedup marker so redelivery may retry. Abstention is not a scheduled reconsideration when more evidence arrives.
@OnDecisionOne reaction per qualifying proposal per subscription. Every subscribed agent can react.The hook is not a fleet-wide singleton or durable completion record. A failed reaction is logged; move must-run follow-up work into a take queue.
@OnEstimateOne firing per epoch per replica, on a virtual thread, the first time the settle rule holds after one of the aggregate's own rounds.A thrown reaction is logged and dropped, as a notify's is; the epoch does not fire again on this replica. Move must-run follow-up work behind a take.
@ProposeOne virtual thread per cue that passes the subscription's entry dedup and the per-agent proposal-id dedup; the open itself is idempotent per replica.A thrown reaction or a refused open is logged and the proposal id is released, so the next cue for that id asks again. The binder has no retry of its own and does not seed from cues that landed before the bind.
@SpaceJoinOne virtual thread per firing, once per key per the mode: LOCAL from an in-memory set, LEASED and ORDERED from a take of the key's JoinTicket.LOCAL: an exception is logged and the key is released with no retry; without settle, the next part event for that complete key fires the join again. LEASED and ORDERED: an exception leaves the ticket's TAKE lease to lapse, and the ticket reappears until its write lease runs out.
@SpaceReduceOne drain per key at a time, serialized by the key's JoinTicket; each element is taken under a lease and completed with the new accumulator in one atomic step.The take model: a method that throws ends the drain and the element reappears by its lease, to be folded once. null consumes the element and leaves the accumulator as it was.

Keep completion and side effects separate in your reasoning

When a take returns an ordinary entry into the same space, the binder calls complete(taken, result, resultLease). With a different resultSpace, it completes the input first and then writes the output separately. A crash between those calls can lose the output, because the input has already been completed.

  • For critical stages, prefer the same-space handoff.
  • For cross-space steps, implement reconciliation in your application.

Ordered claims make the peers agree on winners and completion. They cannot make a database write, a payment API call, or an email part of that commit. A worker can perform an external effect and then fail before it records completion. So make external effects safe to repeat:

  • Use the business request id as an idempotency key at the external service, so the service ignores a repeated request.
  • Use TakeContext.current().orElseThrow().entryId() as the key when it should follow this particular space entry through reassignment.

TakeContext exists around both take annotations only; notify and ballot handlers have none.

  • renew() extends the active claim.
  • It is thread-local. If you hop to a custom executor, propagate the context there and clear it afterward.
  • Async returns are not awaited. Returning a Future or Flux does not make the binder await it. Finish the work and return a domain result from the annotated method.

Layer 4: wire the capability before binding the behaviorAgentSpaces.GroupContext

A Layer 4 annotation binds a behavior to a capability, such as voting or an ordered log, that the peer must already hold. So register the capability first, then bind the agent. The table below says what each behavior needs registered before the agent is bound, and what to verify once it is.

The Layer 4 annotations are:

  • @Ballot, @OnDecision, @Propose, and @OnEstimate (chapter 3);
  • @OrderedTake, and @SpaceJoin and @SpaceReduce in ORDERED mode (chapter 4);
  • @CapabilityRef and @ProvidesCapability, with the Contribution and Motion return values beside them (chapter 3).

The signatures in those chapters are the checked-in 0.7.0 ones. There is no @Contribute and no learning annotation. Aggregation uses the Contribution return value, and you drive gossip learning through the capability API (gossip learning).

BehaviorAssembly requirementWhat to verify
Ballots, proposals, and decisionsRegister VoteCapability with group.provide(vote) or group.vote(name, vote). The starter can supply it. @Propose and a Motion return need the same registration; the binder refuses a declared Motion return at bind time without it.List the vote space under groups[].spaces (the starter's private vote space is not bindable) and name it on the annotation (vote on @Propose) when several exist. Choose proposal options/quorum and authorized voters. Subordinate identities let ballots be attributed to agents; the authorizer chooses the counting granularity.
Ordered workersConstruct OrderedTakes.over(...) with a fixed member set, then group.ordered(spaceName, ordered) before binding.The space writer and coordinator holder must agree; subordinate workers need a coordinator signing as that agent. The starter’s ordered-log=true switch still refuses automatic assembly: it cannot infer members.
Ordered joins and reducesThe same group.ordered(spaceName, ordered) registration, on the join's or the reduce's own space; a peer hosts one ordered log per group.Put an ORDERED join on the space that has the coordinator and name the parts' spaces on each @Part. A reduce's elements, accumulators, and tickets share one space, so that space carries the coordinator.
Typed clientsUse @CapabilityRef for VoteClient, AggregateClient, SemanticClient, or a registered custom client.Fields resolve by exact client type; name group on shared beans to avoid another binding overwriting the field. Use explicit vote-space registration for multiple vote spaces.
ContributionsRegister the local PushSumAggregate; the binder recognizes Contribution.to(epoch, value).The return starts an AVG contribution rather than writing an entry. A missing aggregate fails when the return is processed. A take is completed before its contribution is applied; these are separate operations.
Aggregate readsCall AggregateClient.awaitEstimate(epoch, timeout) or estimate(epoch); call awaitSettled(epoch, Settle, timeout) or bind an @OnEstimate method for an estimate that has held still.Await returns when an estimate is present, before convergence or any accuracy threshold is proven; a settle rule says the estimate stopped moving on this replica, and nothing more. Registered capabilities run on the peer's loop; do not add a client polling loop.
Served capabilitiesA @ProvidesCapability class implementing CapabilityProvider, registered as a bean, through spaces.bind(bean), or with group.provide(provider).The provider's own capabilityType() governs registration; the annotation's value is for discovery tooling. The runtime starts it, advertises it, and runs it when due; nothing else to schedule.
Provider wrappersA @ProvidesCapability wrapper advertises the provider. Typed binder wiring, though, recognizes the concrete VoteCapability and PushSumAggregate instances; forwarding capabilityType() and describe() does not make a wrapper into either. For annotated voting or contributions, register the concrete delegate. A custom gossiping wrapper must also forward the run contract (DueCapabilityProvider, or the older tick()).

A rule the binder enforcesConstraintGate

A group may publish rules as entries in its constraints space (v0.1.24, the agentspaces-constraints module): a Vocabulary of named situations and Constraint entries in four templates, always A before B, never A and B for one key, after A, always B within a time, and at most n A for one key. A binder given a ConstraintGate reads the newest complete version and consults it twice:

  • Before a claim. The take loop looks at the candidates, asks the gate which keys the rules admit, and takes with the template narrowed to an admitted key. A refused entry stays for a peer whose marking admits it.
  • Before a result. A result the rules refuse is not written; the take lapses and a ConstraintViolated entry records the refusal once per unit, key, and entry.

The gate fails open: no rules, or a gate that cannot read them, means the binder behaves as before. A key's enablement comes from the MarkingEngine, a state machine per template over the key's events in issue order. Install it with binder.constraintGate(ConstraintGate.attach(space, authorizer, scope, clock, by)), or with the starter's agentspaces.rules.gate=true, which also advertises rules.gate=true as a resource hint so a console can tell an enforced rule from a monitored one.

A flow manifest the reconciler appliesFlowReconciler

A FlowManifest entry in a group's flow-control space names lanes, bindings (an agent or a step from a package or library, its instance, the peers it runs on, its lane, attribute overrides, and asset references), the stages to drain, and the drain policy. A peer that reconciles reads the newest complete version for its group, drains the named stages, rebinds the bindables its AgentSpaces.catalogue() registered with the overrides applied to their verb annotations, resolves asset references through discovery, and advertises flowVersion and flowConformance. Template.whereType(name) lets a step take a record it has no class of, by the wire type's name.

Turn it on with FlowReconciler.attach(...), or the starter's agentspaces.flows.reconcile=true. A console that manages the group writes the manifests; nothing in the peer calls the console.

aspace://guide/work · chapter 2

Work: take, notify, bid, ref

This chapter covers the Layer 3 annotations: the four most applications need, and nothing else.

  • @SpaceTake claims work under a lease.
  • @SpaceNotify reacts to what appears.
  • @BidFunction prices work on an AUCTION space.
  • @SpaceRef hands a method a space when a return value is not enough.

All four follow the shape chapter 1 set out. The parameter is the cue, the return is the next entry, and the binder carries the discipline.

@SpaceTake: the kill-tolerant workerSpaceTake

To run a worker that survives crashes, use @SpaceTake. It turns a method into a loop that takes entries under a lease.

  • The parameter type is the template. The loop takes entries of that type.
  • A normal return completes the take. For an ordinary result in the same space, the binder writes the result atomically with the completion.
  • A thrown exception skips completion. The lease lapses and the task reappears for another worker. You write no extra code for the failure path.
// agentspaces-partybus -- Scouts.FlightScout: one of eight scouts, each a class with one take method
@AgentSpec(name = "flight-scout",
        description = "Finds flights and rail for the outbound and return legs of a trip",
        goals = {"find transport for a trip"})
public static final class FlightScout {
    private final Sources sources;           // an ordinary constructor dep

    public FlightScout(Sources sources) {
        this.sources = sources;
    }

    @SpaceTake(space = SPACE, lease = "2m", pollTimeout = "500ms")
    public FlightOptions scout(FlightRequest request) {
        List<Link> web = sources.search("flights " + request.from() + " to " + request.to()
                + " " + request.departureDate() + " return " + request.returnDate(), 8);
        FlightOptions found = sources.structured("flights", RESEARCHER + "\n"
                + "Propose up to three itineraries from " + request.from() + " to " + request.to()
                + ". Preference: " + request.preference() + ".\n"
                + digest("Search results", web), FlightOptions.class);
        return new FlightOptions(request.tripId(), request.topic(), found.options(),
                found.note(), "flight-scout");          // the result entry: completes the take
    }
}

Use @SpaceTake whenever work is a queue of units that exactly one worker should do. Examples are research requests, document conversions, booking orders, or anything you would otherwise put on a job queue.

  • Scaling needs no configuration. Start a second process with the same class, and the same queue drains twice as fast, because both race for the same entries.
  • The lease handles failure. Kill a scout mid-search and its TAKE lease lapses. The request reappears, and a sibling picks it up.
Where it livesOne method on a class that may hold anything else. The parameter type is the queue, so one class can carry several @SpaceTake methods over different entry types, or you can give each worker kind its own class, as the partybus scouts do. Constructor dependencies are yours to supply: the binder binds an instance you already built.
attributedefaultmeaning
space"" (inferred)the space to take from; empty means the group's sole registered space
group"" (any)the group this binding belongs to, by name or GroupId; empty means any group whose spaces satisfy it
lease"10m"the TAKE lease; how long a crash takes to show as reappearance
pollTimeout"1s"how long each poll waits before looping
resultLease"1h"write lease for the returned result entry
resultSpace"" (same space)where the result entry is written
tags{}tag filters, "key=value" or "key" (present), compiled onto the template and judged before the payload is decoded; a malformed filter is refused at bind time
where{}field filters, "field op value" with =, !=, <, <=, >, or >=, or "field in a,b,c"; numeric when both sides parse as decimals, string order otherwise, and a null field matches only !=; compiled onto the template and judged before the take claims; the binder refuses an unknown field at bind time
produces{}the entry types the card lists when the return type does not say: the elements of an Entries fork; a sealed return type lists its permitted subclasses without this
description""what this one action does (v0.1.13): the card declares each bound method as an action with its own description, so planners and semantic discovery see per-action text rather than the agent's alone; @SpaceNotify and @OrderedTake take it too

How the method runs, and what to return:

  • One entry at a time. The method body runs on the binder's worker thread for that method, one entry at a time. A slow method slows the takes down; no queue grows behind you. To go faster, add another process.
  • Return null to write nothing. Returning null, or declaring void, completes the take and writes nothing.
  • A throw means a retry. If the method throws, the binder deliberately does not complete. The lease lapses and the entry comes back, so a task that always throws is retried forever. Catch what you can handle, and write a failure entry for what you cannot.
Keep in mindKeep the method's own work shorter than lease. Otherwise the entry reappears while you are still working on it, and two workers finish the same task.

Route by field

To make a worker take only some entries of a type, use where. It narrows the take to entries whose fields hold given values. Each filter takes one of two forms:

  • "field op value", where op is =, !=, <, <=, >, or >=;
  • "field in a,b,c" for a list.

Values compare as follows:

  • Numbers. When the field's string form and the value both parse as decimals, the comparison is numeric, so 3.0 equals 3.
  • Strings. Otherwise the comparison follows string order.
  • Nulls. A null field matches only !=.

The space judges the filters before this worker claims anything. A task addressed to another shop is never leased here, and it stays in the space for the worker it names. The appendix explains how the binder applies field filters.

The binder checks every filter at bind time against the parameter type. It refuses a filter that names a missing component, or one it cannot parse, and names the method. Example 18 deploys one shop class per region, and each takes only its own tasks.

// examples/example-18-agentic-workflow -- Quotes.NorthShop: one class per shop, each taking its own tasks
@AgentSpec(name = "north-shop", description = "Quotes repairs in the north", goals = {"quote"})
public static final class NorthShop {
    @SpaceTake(space = Intake.SPACE, where = "shop=north", lease = "30s", pollTimeout = "300ms",
            resultLease = "1h")
    public RepairQuote quote(QuoteTask task) {
        return Quotes.quote(task, "north", 1.1);
    }
}

Sealed returns

To let a method choose between result types, declare a sealed interface as its return type. The binder writes whichever permitted subclass the method returns. The card lists every permitted subclass as produced, so a planner reading the card sees both branches of a decision the method makes per entry.

Example 18's registrar returns one of two records: a registered claim that cues every specialist, or a rejection that the ledger closes.

// examples/example-18-agentic-workflow -- Claims.Registration, and the Intake.Registrar take that returns it
public sealed interface Registration permits RegisteredClaim, Rejected {
}

@SpaceTake(space = SPACE, lease = "3s", pollTimeout = "300ms", resultLease = "1h")
public Registration register(Claim claim) {
    hook.beforeRegistering(name, claim);
    // The vocabulary's constraints, checked where the data enters: a claim
    // that fails them is quarantined as a Rejected entry, which the ledger
    // closes, rather than thrown away.
    if (claim.claimedAmount() <= 0) {
        return new Rejected(claim.claimId(), "claimedAmount must be positive");
    }
    if (claim.policyId() == null || claim.policyId().isBlank()) {
        return new Rejected(claim.claimId(), "a claim names its policy");
    }
    return new RegisteredClaim(claim.claimId(), claim.policyId(), claim.claimant(),
            claim.description(), claim.claimedAmount(), name);
}

One take may also return several entries at once. The binder completes the take once, then writes each element of an Entries return as if the method had returned it alone. The fork, under @SpaceNotify, covers that return and the produces attribute that tells the card what is inside it.

@SpaceNotify: choreography as a returning methodSpaceNotify

To react to entries without consuming them, use @SpaceNotify. The binder calls the method for every matching entry written to the space. It writes a non-void return value back as the next entry in the flow. React to X, produce Y, and Y is some other agent's cue.

The binder carries the discipline, so the method body never has to:

  • No duplicates. Delivery is deduplicated per entry, within a bounded in-memory dedup window for this subscription.
  • Its own thread. Each reaction runs on its own virtual thread, so slow work never holds the fabric's delivery thread.
  • Null writes nothing. A null return writes nothing.
// agentspaces-partybus -- Dispatcher: reacts to one brief by fanning out a dozen
// requests. It writes requests and never answers them. (Two of the twelve research
// requests shown, then a day slot per day through the third @SpaceRef.)
@AgentSpec(name = "dispatcher",
        description = "Turns a travel brief and the events of a trip into the fleet's research requests",
        goals = {"research a trip"})
public final class Dispatcher {
    static final Lease REQUEST_LEASE = Lease.of(Duration.ofHours(6));

    @SpaceRef(Scouts.SPACE)   Space research;      // the bag the scouts take from
    @SpaceRef(Party.TRIP)     Space trip;          // where briefs and events arrive
    @SpaceRef(Planners.SLOTS) Space slots;         // the day auction

    @SpaceNotify(space = Party.TRIP, lease = "12h")
    public void dispatch(TravelBrief brief) {
        String id = brief.tripId();
        double nightly = brief.dailyBudget() / 2.0;
        research.write(new FlightRequest(id, "flights " + brief.from() + " to " + brief.to(),
                brief.from(), brief.to(), brief.departureDate(), brief.returnDate(),
                brief.transportPreference()), REQUEST_LEASE);
        research.write(new HotelRequest(id, "hotels " + brief.to(), brief.to(),
                brief.departureDate(), brief.returnDate(), nightly, needs), REQUEST_LEASE);
        // ... ten more research requests, one per remaining specialist ...
        List<String> interests = List.of(brief.brief().split("[,;.]\\s*"));
        int day = 0;
        for (String date : brief.days()) {
            slots.write(new DaySlot(id, date, brief.to(), interests, day == 0 ? "EASY" : "FULL", 0),
                    REQUEST_LEASE);
            day++;
        }
    }
}

Use @SpaceNotify when the trigger is "something appeared". When the trigger is "there is work to claim", use @SpaceTake. Nothing is consumed, so every interested agent sees the same entry. That suits fan-out, derived records, and side effects such as audit and notification.

Returning a value is the compact form of a pipeline. An agent that returns Y from an X has declared one edge of a flow, and the next agent's @SpaceNotify on Y is the next edge. Nobody wires the graph; it exists because of what each agent consumes and produces.

The example above shows both halves of the common shape. It reacts with @SpaceNotify. Then it writes through @SpaceRef handles, because one reaction needs to produce many entries, or entries in other spaces, beyond the single entry a return value can express.

Where it livesSame freedom as @SpaceTake, and the two mix in one class: most partybus planners carry a @BidFunction, a @SpaceTake, and a @SpaceRef together. A class with only @SpaceNotify methods is a perfectly good agent; the pet-clinic flagship coordinates entirely this way, with no take anywhere.
attributedefaultmeaning
space"" (inferred)the space to watch
group"" (any)the group this binding belongs to, by name or GroupId
lease"1h"the subscription lease; the binder renews it at half-lease intervals while bound, so it bounds how long a stale subscription outlives a crashed agent
resultSpace"" (same space)where a returned entry is written
resultLease"1h"write lease for a returned entry
tags{}tag filters, "key=value" or "key" (present), compiled onto the template and judged before the payload is decoded
where{}field filters, "field op value" with =, !=, <, <=, >, or >=, or "field in a,b,c"; numeric when both sides parse as decimals, string order otherwise, and a null field matches only !=; compiled onto the template and judged before the method runs; the binder refuses an unknown field at bind time
produces{}the entry types the card lists when the return type does not say: the elements of an Entries fork; a sealed return type lists its permitted subclasses without this
on{WRITTEN}the event kinds the method reacts to; EXPIRED turns a leased entry into a timer; each entry is delivered once per kind; the binder refuses an empty set at bind time
description""what this one action does, published on the card (v0.1.13); empty means the agent description stands in

Two rules prevent the usual mistakes:

  • Do not react to a type by writing the same type. Every bound agent sees every matching entry, including entries this same process wrote. A method that reacts to X by writing another X is an infinite loop. Make the reaction produce a different type, or filter on a field.
  • Make the method safe to re-enter. Reactions run on their own virtual thread per entry, so two entries can be in flight at once. The binder deduplicates redeliveries of the same entry only; two different entries both arrive.
Keep in mindA reaction that throws is logged and dropped. There is no lease to lapse, and nothing will retry it. This is the opposite of @SpaceTake, and the most common surprise when you move logic between the two.

Route by field

where takes the same filters as @SpaceTake, "field op value" or "field in a,b,c", with the same comparison rules. The method sees only the entries that pass, and a != filter lets everything but one value through.

where also breaks the loop warned of above, when the reaction cannot change the type: filter on a field the reaction never produces. The binder checks every filter at bind time against the parameter type. It refuses a filter that names a missing component, or one it cannot parse, and names the method.

// examples/example-18-agentic-workflow -- Quotes.SeniorReviewer: severe assessments only
@AgentSpec(name = "senior-reviewer", description = "Reviews severe claims", goals = {"review"})
public static final class SeniorReviewer {
    @SpaceNotify(space = Pricing.SPACE, where = "severity=HIGH", resultSpace = Settlement.LEDGER,
            resultLease = "24h")
    public SeniorReview review(ClaimAssessment assessment) {
        return new SeniorReview(assessment.claimId(), "severe: damage " + assessment.damageEstimate()
                + " against a limit of " + assessment.coverageLimit());
    }
}

The fork

To produce several entries from one reaction, return them together as Entries. Build it with Entries.of(Object...) or Entries.of(List). The binder dispatches each element in order exactly as if the method had returned it alone: a plain entry, a Tagged entry, a Motion, or a Contribution.

  • No nesting and no nulls. The binder refuses a nested Entries and a null element.
  • One completion from a take. From a @SpaceTake or @OrderedTake, the binder completes the take once, before the first element.
  • List the types in produces. The card cannot see inside the collection, so the annotation's produces lists the element types. @SpaceTake, @OrderedTake, and @SpaceJoin carry the same attribute.

Example 18's quote desk forks one assessment into a request that says how many quotes to expect, plus one task per shop. The shops above route on those tasks.

// examples/example-18-agentic-workflow -- Quotes.QuoteDesk: one assessment, four entries
@AgentSpec(name = "quote-desk", description = "Asks every repair shop for a quote", goals = {"quote"})
public static final class QuoteDesk {
    @SpaceNotify(space = Pricing.SPACE, resultSpace = Intake.SPACE, resultLease = "1h",
            produces = {QuoteRequest.class, QuoteTask.class})
    public Entries ask(ClaimAssessment assessment) {
        return Entries.of(new QuoteRequest(assessment.claimId(), SHOPS.size()),
                new QuoteTask(assessment.claimId(), "north", assessment.damageEstimate()),
                new QuoteTask(assessment.claimId(), "east", assessment.damageEstimate()),
                new QuoteTask(assessment.claimId(), "south", assessment.damageEstimate()));
    }
}
Keep in mindA fork from a take is one completion followed by several writes. A crash between two elements leaves the first written and the task reappearing under its lapsed lease, and the next worker forks it again. Give forked entries the input's id, as the quote tasks carry the claim id, and let the stage downstream dedup on it.

A method whose declared return is a sealed interface needs no produces: the card lists its permitted subclasses.

The deadline

To act when nothing happens in time, react to an entry's lease running out. on names the event kinds the method reacts to, WRITTEN by default. With on = SpaceEvent.Kind.EXPIRED, a leased entry becomes a timer. Write a reminder with the lease you are willing to wait. When it lapses, the reaction fires with the entry that expired. A cancel of the reminder raises EXPIRED too, so a reaction that must not run after the outcome arrives checks for the outcome first and returns null.

  • Any set of kinds is allowed. The binder delivers each entry once per kind, so {WRITTEN, EXPIRED} sees the write and the lapse as two deliveries.
  • REAPPEARED is a dead worker's signal.
  • COMPLETED says the work finished elsewhere.
  • An empty set is refused. The binder refuses it at bind time as a method that reacts to no event kind.

Example 18's underwriter writes the reminder as it opens the vote, and an escalator reacts to its lapse.

// examples/example-18-agentic-workflow -- Decisions.Underwriter: the reminder is written with the vote
@Propose(space = Pricing.SPACE, vote = SPACE, prefix = PREFIX, key = "claimId",
        options = {Pricing.APPROVE, Pricing.DENY}, quorum = 3, lease = "10m")
public String open(PricedClaim priced) {
    // The deadline is a leased entry: when it lapses, the escalator below
    // reacts; when the panel decides first, the escalator finds the
    // decision and does nothing.
    decisions.write(new Reminder(priced.claimId()), reminderLease);
    return "Settle claim " + priced.claimId() + "? The adjuster recommends "
            + priced.recommendation() + " with a reserve of " + priced.reserve();
}

// Decisions.Escalator: the lapse is the cue; the motion opens once per claim
@AgentSpec(name = "escalator", description = "Escalates claims the panel has not decided in time",
        goals = {"escalate"})
public static final class Escalator {
    @CapabilityRef
    VoteClient votes;

    @SpaceNotify(space = SPACE, on = SpaceEvent.Kind.EXPIRED)
    public Motion escalate(Reminder reminder) {
        if (votes.decision(PREFIX + reminder.claimId()).isPresent()) {
            return null;                       // decided in time: nothing to escalate
        }
        return Motion.of("escalate:" + reminder.claimId(), "The panel has not decided claim "
                + reminder.claimId() + " in time; escalate to the chief underwriter?",
                List.of("escalate", "wait"), 1, Lease.of(Duration.ofMinutes(10)));
    }
}
Keep in mindEvery peer that holds the entry sees the lapse, so a reaction on EXPIRED fires once per bound agent on each of those peers. Make what it does safe to repeat. Return a Motion, which opens once per proposal id however many peers see the lapse, or write an entry the next stage dedups on.

The escalator above also reads the decision first, so a panel that decided in time escalates nothing.

@BidFunction: the price of workBidFunction

To let workers compete for work by price, put the space on AUCTION and give each worker a @BidFunction. On an AUCTION space, every take carries a bid, and the lowest bid takes the entry.

The bid is a plain method over the entry, so cost models are ordinary code. Denominate the bid in dollars, tokens, or queue depth, and let your cost team (FinOps) tune it.

// agentspaces-partybus -- Planners.DiningPlanner: bid, worker, and space handle in
// one class. The bid decides whether this planner gets the day at all, and the
// take method is what it does once it has won.
@AgentSpec(name = "dining-planner",
        description = "Plans a day around the table: markets, long lunches, a reserved dinner",
        goals = {"fill a day with food"})
public static final class DiningPlanner {
    @SpaceRef(Scouts.SPACE)
    Space research;

    @BidFunction(space = SLOTS)                 // the lowest bid takes the day
    public double bid(DaySlot slot) {
        double bid = 90;
        if (interested(slot, "food", "wine", "eat", "cook")) {
            bid -= 35;                          // this is our kind of day
        }
        if (slot.pace().equals("REST")) {
            bid += 20;                          // ... but not on a rest day
        }
        return bid + slot.round() * 5;          // a strike barely touches a lunch
    }

    @SpaceTake(space = SLOTS, lease = "1m", pollTimeout = "500ms")
    public ScheduledActivity plan(DaySlot slot) {
        String table = research.readAll(Template.of(RestaurantOptions.class)
                        .where("tripId", eq(slot.tripId())), 20).stream()
                .filter(r -> r.location().equalsIgnoreCase(slot.location()))
                .flatMap(r -> r.restaurants().stream()).map(r -> r.name()).findFirst()
                .orElse("a table the scouts are still finding");
        return new ScheduledActivity(slot.tripId(), slot.date(), slot.location(), "DINING",
                "Market morning, long lunch, dinner at " + table, bid(slot),
                "dining-planner", slot.round());
    }
}

Keep the bid function, the worker, and the space handle in the same object, as this example does. A bid needs the same state the work needs: the model it would call, the queue it is already sitting on, the region it runs in. The appendix explains why they belong together.

Use AUCTION when workers are not interchangeable and you want the fleet to sort that out without a router. Several planners bid on every day of a trip. The one whose day it should be bids lowest and takes the day, and no rule anywhere says who plans what. Change a bid function, and you have re-tuned the whole allocation.

The same shape also does:

  • Cost-aware model routing. Cheap capacity sweeps easy work, and the expensive model takes the hard entries.
  • Locality routing.
  • Load shedding, by bidding your own queue depth.
Where it livesIn the same class as the @SpaceTake it prices, on an AUCTION space. One bid function per space per peer, whatever the bean. The binder wires bids before starting worker loops, so a bid is always in place before the first claim.

Follow these rules when you write a bid function:

  • Use one unit per space. The lowest bid takes the entry, and the number is yours to denominate (dollars, tokens, queue depth, estimated seconds). Every bidder on that space must use the same unit, because the space compares the bids directly.
  • Pair it with a take. A bean with a bid function but no take method is legal and useless: it prices work it will never do.
  • Keep it pure and quick. It runs inside the claim path, on candidate entries, possibly many times. Do not call a model, hit a database, or block in it.
  • One bid function per space per peer. A space consults one cost function. Two agents with a @BidFunction on the same space on one peer are refused at bind time, by name; the second does not silently replace the first. example-04-auction runs one bidder per peer, and its AuctionFleetFlowTest pins the refusal.
Keep in mindOnly spaces built with ConflictStrategyType.AUCTION consult bids at all. On a LEASE_RACE space a @BidFunction is silently never called. When an auction seems broken, check first that the space is configured for AUCTION.
attributedefaultmeaning
space"" (inferred)The sole registered space when omitted; configure AUCTION to use the bid.
group"" (any)Group name or GroupId; other group binders skip the method.

@SpaceRef: a handle when you need oneSpaceRef

To write to a space from inside a method, inject a handle with @SpaceRef. The binder injects a Space into the field at bind time. Use it for mid-method writes such as progress markers and side outputs.

  • Periodic agents. Under Spring, @Scheduled plus a @SpaceRef field is the idiomatic periodic agent. AgentSpaces ships no scheduler of its own.
  • What arrives. The field holds the registered space itself. When the fleet runs with agentspaces.identity.agent-keys=subordinate, it holds this agent's view of the space instead.
  • Writes are attributed to the agent. Through that view, everything the agent writes, takes, or completes is signed with the agent's own certified key. It is attributed to the agent itself as well as its host peer (agent certificates).
  • Your code stays the same. The field's type and your code do not change either way.
@SpaceRef("findings")
private Space findings;                  // injected at bind time

// Several are normal: the partybus dispatcher holds three, one per space
@SpaceRef(Scouts.SPACE)   Space research;
@SpaceRef(Party.TRIP)     Space trip;
@SpaceRef(Planners.SLOTS) Space slots;

// The idiomatic periodic agent under Spring: our scheduler is Spring's.
// (Illustrative: no checked-in example uses @Scheduled; the API calls are real.)
@SpaceAgent(description = "Publishes a backlog reading every thirty seconds")   // already a @Component
public class BacklogReporter {
    @SpaceRef("metrics")
    private Space metrics;
    private final BlockingQueue<Order> queue;

    public BacklogReporter(BlockingQueue<Order> queue) {
        this.queue = queue;
    }

    @Scheduled(fixedDelay = 30_000)
    public void report() {
        metrics.write(new Backlog(queue.size()), Lease.of(Duration.ofMinutes(2)));
    }
}

Use it whenever one invocation has to produce more than the single entry a return value can express:

  • progress markers mid-task;
  • fan-out like the dispatcher's;
  • side outputs into a different space;
  • reads that inform the work, as when the dining planner reads what the scouts found before it writes a schedule.

The field is a fully-featured Space with every verb of the Space API.

It is also how you get a space into code that is not a bound method, such as a @Scheduled method, an HTTP controller method, or a message-listener callback. Annotate the field, and as long as the enclosing bean is enrolled, the handle is there. AgentSpaces ships no scheduler, no HTTP layer, and no inbox of its own, because your framework already has them.

Where it livesA field on the agent class, or on any superclass of it, since the binder walks the hierarchy. Declare the field as Space: a field of any other type fails at bind time, before first use. Fields need not be public.
Keep in mindInjection happens at bind time, so the handle is null in the constructor and in any @PostConstruct. Do first-write-on-startup work from a @SpaceNotify, a scheduled method, or an ApplicationReadyEvent listener, never in the constructor.
attributedefaultmeaning
value"" (inferred)The space name; omitted only when exactly one space is registered.
group"" (any)The group whose handle is injected. Name it on a multi-group bean so another binding does not overwrite the field.
aspace://guide/decide · chapter 3

Decide and sense

This chapter covers the Layer 4 annotations for group votes and fleet-wide estimates, plus two that reach any capability. A capability is an extra service the peers run among themselves, such as votes or estimates. Use these annotations when agents must agree on a choice, or when you need one number computed across the whole fleet.

  • @Ballot casts a vote.
  • @OnDecision reacts once when a vote closes.
  • @Propose opens a vote.
  • @OnEstimate fires when a fleet-wide estimate settles.
  • @CapabilityRef injects a typed client.
  • @ProvidesCapability serves a capability of your own.

Each annotation binds a behavior to a capability the peer must already hold, so read Layer 4 assembly first. Chapter 12 covers the services themselves.

@Ballot: one signed vote per proposalBallot

To let an agent vote on a proposal, put @Ballot on a method. The method receives the proposal and returns the option this agent backs. This is the first Layer 4 annotation, and the others follow its shape: the method's parameter is the cue, and the binder acts on the return value.

  • The cue is the vote's own Proposal entry.
  • The return value is the option this agent backs. The binder casts it through the group's vote capability, using the bound agent's identity with subordinate keys.
  • A null return abstains.
  • Repeats are dropped. The binder deduplicates proposals within this binding.
  • The ballot is never refused as "unknown proposal". The cue is the proposal record.

The appendix explains what this replaces in a hand-written panelist.

// agentspaces-example-apps/agentspaces-audit-fleet -- AuditFleet.Panelist
@Ballot(space = VOTES, lease = "2h")
public String judge(VoteCapability.Proposal proposal) {
    Finding finding = peer.audit().read(Template.of(Finding.class)
            .where("findingId", eq(proposal.proposalId())), Duration.ofSeconds(10)).orElse(null);
    if (finding == null) {
        return null;                                   // nothing on the record: abstain
    }
    double weighted = finding.confidence() * trust(peer.discipline(), finding.discipline());
    return weighted >= CONFIRM_THRESHOLD ? "CONFIRMED" : "DISMISSED";
}

Two settings shape which proposals a method sees and how votes count:

  • Narrow by prefix. One vote space usually carries several decisions, so prefix limits a method to the proposals whose id starts with it. The Party Bus keys them advisory: and next:.
  • Count each agent. Under agent-keys=subordinate, the ballot is the agent's own attested record. Several agents on one peer then count as several voters wherever the authorizer counts per agent (security).
attributedefaultmeaning
space"" (inferred)the vote space; empty means the binder's sole registered vote space
group"" (any)the group this binding belongs to, by name or GroupId
prefix"" (all)only proposals whose id starts with it
lease"1h"the ballot's write lease; outlive the proposal's decision window
Where it livesAny bound class. The vote space must be registered with the group, with a vote capability registered for it. Binding fails fast otherwise, and the error names the call that is missing.

Register the vote capability in one of three ways:

  • group.provide(vote) registers it and advertises the capability.
  • group.vote("votes", vote) registers it without advertising.
  • binder.vote(...) is the hand-built form.

Return one of the proposal's options. castBallot refuses any other option. The binder logs the refusal and treats the agent as not yet voted, so a redelivery of the proposal may retry.

@OnDecision: react once when a vote closesOnDecision

To react when a vote closes, put @OnDecision on a method. It is the partner of @Ballot. In this chapter, a replica is one peer's copy of a space.

  • Its input is the Decision.
  • It runs once per proposal per subscription. It fires the first time this replica's tally meets the quorum, the number of ballots that close the vote.
  • A non-null return is written as the next entry in the flow, as with @SpaceNotify.
  • Late peers still fire once. A replica that learns of a vote late fires on its first qualifying ballot.

The appendix explains how the binder tracks a decision.

// examples/example-05-quorum -- QuorumFleet.Supervisor
@OnDecision(space = "votes", prefix = "scale", resultLease = "10m")
public ScalingDecision record(VoteCapability.Decision decision) {
    return new ScalingDecision(decision.proposalId(), decision.winner(),
            decision.tally().toString(), decision.granularity().name());   // which counting rule closed it
}
Where it livesThe same class as the @Ballot, or a different one. The audit flagship's lead reacts to closed votes and never casts.
  • Choose where results go. resultSpace defaults to the vote space. The Party Bus's safety lead writes the advisory into trip.
  • Plain Java without the binder has the same hook: vote.onDecision(proposals, listener, lease), which returns a leased Subscription.
attributedefaultmeaning
space"" (inferred)the vote space; empty means the binder's sole registered vote space
group"" (any)the group this binding belongs to, by name or GroupId
prefix"" (all)only proposals whose id starts with it
lease"1h"the subscription lease; renewed at half-lease while the agent stays bound
resultSpace"" (vote space)where a returned entry is written
resultLease"1h"write lease for a returned entry

@Propose: opening a vote as an annotationProposeMotionKeys

To open a vote when a cue entry arrives, put @Propose on a method. Use it for a lead, the agent that opens the vote, whose options, quorum, and lease are fixed and whose cue decides only the question.

  • The method takes the cue and returns the question as a String.
  • A null return asks nothing.
  • A Motion return gives one cue a shape of its own (the Motion return).

The proposal id is the prefix plus the cue's key. Set the key in one of two ways:

  • key names fields read from the cue and joined by :.
  • keyTag names a cue tag whose value is the key.

One of the two is required unless the method returns a Motion carrying its own id. @Ballot and @OnDecision filter on the same prefix. Together, the three annotations describe one vote across the classes that open it, judge it, and record it.

// agentspaces-example-apps/opscenter -- RiskPanel.Lead
@Propose(space = OpsFleet.EVIDENCE, vote = OpsFleet.REVIEWS, prefix = PREFIX, key = "incidentId",
        options = {"approve", "reject"}, quorum = QUORUM, lease = "12h", subscriptionLease = "12h")
public String open(RemediationProposal proposal) {
    return "Approve remediation for " + proposal.incidentId() + ": " + proposal.action()
            + ". Reversible: " + (proposal.reversible() ? "yes" : "no")
            + ". Rationale: " + proposal.rationale();        // the question; the shape sits on the annotation
}

// agentspaces-partybus -- SafetyPanel.Lead: a composite key, tripId:location:wave
@Propose(space = Watchers.SIGNALS, vote = ADVISORIES, prefix = PROPOSAL_PREFIX,
        key = {"tripId", "location", "wave"}, options = {"GO", "CAUTION", "AVOID"}, quorum = 3,
        lease = "12h", subscriptionLease = "12h")
public String open(DangerAssessment assessment) {
    waves.putIfAbsent(Safety.proposalId(assessment.tripId(), assessment.location(),
            assessment.wave()), assessment);
    return "Travel advisory for " + assessment.location() + " (" + assessment.wave() + ")";   // every channel's assessment of one wave maps to one id
}

The binder handles the rest:

  • It watches the cue as @SpaceNotify does, under a leased subscription renewed at half-lease, with the same bounded per-entry dedup.
  • It asks each question once. It invokes the method once per proposal id per bound agent. Several cues that map to one id, such as every channel's assessment of one wave, ask one question.
  • It opens each proposal once per replica, as the bound agent. It skips a motion whose proposal is already visible on the vote space.
  • It lists the action on the agent's card as kind propose. Nobody can invoke it remotely.
  • It checks the key at bind time. The key rule is the one Template.where and @SpaceJoin use (Keys): a record component, or a getX, isX, or plain x() accessor. A missing field fails the bind, and the error names the type.

The appendix lists what @Propose replaces in a hand-written lead.

Where it livesAny bound class, on a peer whose group registers the cue space and the vote space. Register the vote capability as @Ballot needs it (group.provide(vote) or group.vote(name, vote)). Binding fails fast otherwise, naming the registration.
  • The lead usually records the result too. It carries the @OnDecision that records the result, as the opscenter's risk lead and the Party Bus safety lead do.
  • A class may both propose and vote on one space. Attribution and the authorizer decide what counts. The binder's propose tests bind one such proposer that also sits on the panel.
  • Plain Java without the binder opens the same idempotent way with VoteClient.propose(Motion).

Plan for these cases as well:

  • Two leads on two peers may both open the same id. The open is idempotent per replica, so this is harmless while the shape is static and the question comes from the cue alone. Both replicas then write the same proposal. Derive the question from the cue alone. Do not use local state the other lead lacks.
  • A null return releases the id, so a later cue for the same id may ask.
  • A failed open releases the id too. A thrown reaction, or a proposal the capability refuses, is logged, and the next cue retries it. The binder has no retry of its own.
Keep in mindBind the lead before the stage that writes its cues. The binder does not seed from cues that landed before the lead was bound: a cue already in the space when bind runs opens nothing. Otherwise, open from a @SpaceTake that returns a Motion, since a take consumes cues already in the space.
attributedefaultmeaning
space"" (inferred)the cue's space; empty means the binder's sole registered space
group"" (any)the group this binding belongs to, by name or GroupId
vote"" (inferred)the vote space; empty means the binder's sole registered vote space
prefix""the proposal id's prefix, which @Ballot and @OnDecision filter on
key{}the cue fields whose values, joined by :, complete the proposal id; several fields make one composite key
keyTag""the cue tag whose value completes the proposal id instead of fields; exclusive with key
options(required)the options, two or more
quorum(required)the ballots that close the vote, positive
lease"1h"the proposal's write lease; ballots must outlive it
subscriptionLease"1h"the cue subscription's lease, renewed at half-lease while the agent stays bound
tags{}tag filters on the cue, "key=value" or "key", judged before decode
where{}field filters on the cue, "field op value" or "field in a,b,c", as on @SpaceTake
description""what this one action does, published on the card

@OnEstimate: react once when an estimate settlesOnEstimatePushSumAggregate.Estimate

To act once when a fleet-wide estimate stops changing, put @OnEstimate on a method. The peers compute the estimate together from the values each one contributes with a Contribution return. @OnEstimate is the read side of that return, and the estimate's counterpart to @OnDecision. Each estimate belongs to an epoch, named by an epoch id.

  • Its input is a PushSumAggregate.Estimate: a record of the epoch id, the operator, the value, and the rounds this replica has run since it learned of the epoch.
  • It fires once per epoch, the first time this replica's estimate has stayed within tolerance for the settle span, such as settle = "PT40S" or "40s". The default is 8 s. The tolerance is relative, of the larger of one and the last value.
  • settle = "PT0S" fires on the first estimate present.
  • settleTicks = n is the older form, deprecated, and means n seconds. Name one of the two; naming both is refused at bind time.
  • A non-null return is written as the next entry in the flow, or opens a Motion, as any bound method's return does.

The span is counted in gossip rounds, one exchange of values with other peers each second (PushSumAggregate.ROUND_PERIOD), rounded up. An epoch that goes quiet settles at its last change plus the span, with no further exchange needed.

The appendix explains how the settle rule runs.

// examples/example-18-agentic-workflow -- Settlement.Supervisor: a forty-second settle, one report
@AgentSpec(name = "supervisor", description = "Reports the fleet's average reserve once it settles",
        goals = {"report reserves"})
public static final class Supervisor {
    private final String name;

    public Supervisor(String name) {
        this.name = Objects.requireNonNull(name, "name");
    }

    @OnEstimate(prefix = "reserve:", settle = "PT40S", tolerance = 0.01, resultSpace = LEDGER,
            resultLease = "24h")
    public ReserveReport report(PushSumAggregate.Estimate reserve) {
        return new ReserveReport(reserve.epochId(), reserve.value(), name);
    }
}
Where it livesAny bound class, on a peer whose group has an aggregate registered (group.provide(aggregate)). The binder refuses the bind otherwise, naming that call. The card declares one action of kind on-estimate that nobody can invoke remotely.

Plain Java has the same hook, shown below:

  • PushSumAggregate.onEstimate(epochs, Settle, listener) registers a listener and returns the handle that removes it.
  • AggregateClient.awaitSettled(epochId, Settle, timeout) is the blocking form, for code that wants the settled value in line.
  • Settle.after(span, tolerance) builds the rule from a Duration, and Settle.FIRST fires on the first estimate present. Settle.after(ticks, tolerance) is the older form, with ticks read as one-second rounds.
// agentspaces-capabilities -- PushSumAggregate: the estimate, the rule, and the listener
public record Estimate(String epochId, Mode mode, double value, int ticks) {
}

public record Settle(int ticks, double tolerance) {
    public static final Settle FIRST = new Settle(0, 0);
    ...
    public static Settle after(Duration span, double tolerance) {
        ...                                        // rounds of ROUND_PERIOD (1 s), rounded up
    }
}

public AutoCloseable onEstimate(Predicate<String> epochs, Settle settle, Consumer<Estimate> listener) {
    ...
}

// agentspaces-agent -- AggregateClient: the blocking form
public OptionalDouble awaitSettled(String epochId, PushSumAggregate.Settle settle,
                                   java.time.Duration timeout) {
    ...
}
Keep in mindSettled means only that this replica's estimate has stopped moving under the rule. It does not prove the estimate is right, and it does not detect a wrong value. A member that contributes a wrong number moves every replica's estimate. Size settle for the spread of your contributions, and put a vote behind any estimate that commits the fleet to an action.
  • Every bound supervisor fires, once per replica per epoch. Bind one, or return a Motion, which opens once per proposal id, or write an entry the next stage dedups on.
  • A late watch starts afresh. A watch registered after an epoch settled starts counting again and fires once the rule holds again.
  • Allow for real time. A driven peer runs one gossip round a second, so example 18's settle = "PT40S" is forty seconds.

The appendix explains why the estimate trusts every contribution.

attributedefaultmeaning
prefix"" (all)only epochs whose id starts with it
settle"" (8 s)the span the estimate must stay within tolerance to count as settled, as a duration ("PT40S" or "40s"), counted in the gossip rounds this replica takes part in after it first heard the epoch, about one a second under a driven peer; "PT0S" fires on the first estimate present
settleTicks-1 (unset)deprecated, the older form: n settle steps of about a second each; name settle or settleTicks, not both
tolerance0.001the relative change, of the larger of 1 and the last value, that still counts as unchanged
group"" (any)the group this binding belongs to; empty means any group whose aggregate satisfies it
resultSpace"" (inferred)where a returned entry is written; empty means the binder's sole registered space
resultLease"1h"write lease for a returned entry
description""what this one action does, published on the card

@CapabilityRef: a typed client, injectedCapabilityRefContributionMotion

To give an agent a capability client without passing it to a constructor, put @CapabilityRef on a field. It is the Layer 4 sibling of @SpaceRef. The binder injects the field at bind time from the group's typed clients.

The field's type can be any typed client:

  • VoteClient
  • AggregateClient
  • SemanticClient
  • anything registered with binder.client(type, instance)

Constructor injection still works and is still fine. Use @CapabilityRef when the agent should not have to be handed its capabilities by whoever constructs it.

// agentspaces-agent tests -- AgentBinderLayer4ClusterTest.Sensor, with the typed-client
// injection of AgentBinderTest.Sensor added
@AgentSpec(name = "sensor", description = "Contributes readings", goals = {"sense"})
public class Sensor {
    @CapabilityRef AggregateClient aggregate;       // injected by field type at bind time
    @SpaceRef("readings") Space readings;

    // A push-sum contribution is a return value; the binder starts the epoch.
    @SpaceNotify(space = "readings")
    public Contribution feel(Reading reading) {
        return Contribution.to(reading.topic(), reading.value());
    }
}

// Assembly (plain Java; the starter does this from agentspaces.capabilities.*):
group.provide(aggregate);              // registers the aggregate for Contribution returns and AggregateClient
group.bind(new Sensor());

The vote has the same kind of return value: a Motion, the vote-side sibling of Contribution. Any bound method may return it to open a vote. This is the dynamic form of opening, for a lead whose options or quorum come from the cue. When only the question does, @Propose says the same thing as one annotation.

  • Motion.of(id, question, options, quorum, lease) names the sole registered vote space.
  • Motion.in(space, ...) names a particular one.
  • Each proposal opens once. The binder opens it as the bound agent, once per proposal id per replica, and skips a motion whose proposal is already visible.
  • A take completes first. For a take, the binder completes the taken entry first, so a failed open never makes a finished task reappear.

Plain code opens the same idempotent way through VoteClient.propose(Motion).

A method that declares a Motion or Contribution return type fails at bind time when its capability is missing, naming the registration. So the gap shows before the first value comes back. A declared Motion return also puts VoteCapability.Proposal on the card as what the action produces.

// agentspaces-partybus -- Party.Lead: the options come from the cue, so the method returns the Motion
@SpaceRef(DECISIONS)
Space decisions;

@SpaceNotify(space = Scouts.SPACE, lease = "12h")
public Motion open(NextDestinationIdeas ideas) {
    String proposalId = "next:" + ideas.tripId();
    List<String> options = new ArrayList<>();
    for (Destination idea : ideas.ideas()) {
        options.add(idea.name());
    }
    if (decisions.read(Template.of(NextDestinationProposal.class)
            .where("proposalId", eq(proposalId))).isEmpty()) {
        decisions.write(new NextDestinationProposal(ideas.tripId(), proposalId,
                "Where next after this trip?", options, "party-lead"), Lease.of(Duration.ofHours(12)));   // the human-readable announcement, a second entry through the handle
    }
    return Motion.in(DECISIONS, proposalId, "Where next after this trip?", options, partySize,
            Lease.of(Duration.ofHours(12)));                     // the binder opens it once per proposal id
}
Where it livesA field on the agent class or a superclass. Binding fails fast when no client of the field's type can be resolved, naming the registration that would supply it.

Returning a capability value needs that capability registered. The binder checks both cases when it binds the method:

  • A Contribution returned from a @SpaceNotify, @SpaceTake, @OrderedTake, @OnDecision, or @SpaceJoin method needs the peer's aggregate registered (group.provide(aggregate)).
  • A Motion needs the vote capability registered (group.provide(vote) or group.vote(name, vote)).

Read the fleet's estimate back with AggregateClient.awaitEstimate(epoch, timeout), or with awaitSettled(epoch, Settle, timeout) once it has stopped moving. There is no manual tick anywhere.

attributedefaultmeaning
group"" (any)the group whose client to inject; empty means any binding group, the last one to bind winning, so an agent that spans groups names the group

@ProvidesCapability: serving a capabilityProvidesCapabilityCapabilityProvider

To serve a capability from your peer, put @ProvidesCapability on a CapabilityProvider implementation. It marks the class as a service the fleet should advertise. When you bind it through the facade, the binder registers it on the group's CapabilityRuntime, which then:

  • starts it;
  • signs and publishes its CapabilityAdvertisement;
  • keeps that advertisement fresh on every card refresh, the same TTL-leased freshness every other card gets.

Consumers reach it through a typed client (capability services).

// agentspaces-spring-boot-autoconfigure tests -- AgentSpacesAutoConfigurationTest.EchoCapability, trimmed
// A capability type of your own, served by this peer and advertised to the group.
@Component
@ProvidesCapability("aspace:cap/echo")
public class EchoCapability implements CapabilityProvider {
    private final PeerId self;

    public EchoCapability(PeerIdentity identity) {
        this.self = identity.peerId();
    }

    @Override public String capabilityType() { return "aspace:cap/echo"; }

    @Override public CapabilityAdvertisement describe(GroupId group) {
        return new CapabilityAdvertisement("aspace://" + group.value()
                + "/cap/echo/" + self.value(), self, group, Instant.now(),
                Duration.ofMinutes(15), "aspace:cap/echo", "0.1",
                "pipe", Map.of(), Map.of());
    }
    // start() is an interface default. A protocol that keeps its own deadlines implements
    // DueCapabilityProvider instead (custom capabilities); overriding tick() is the older form.
}

You need this only when your peer is the one serving a capability. Most peers consume capabilities instead, which needs no annotation at all; see the capability services. With the starter you rarely write this either: agentspaces.capabilities.* already registers the aggregate, vote, semantic-discovery and key-wrap providers for you.

Write the bean in these cases:

  • A capability the starter leaves off, such as the ordered log, which needs a member set the starter cannot guess.
  • A capability configured differently, such as a gossip learner with a real training step.
  • A capability of your own that you are publishing.
Where it livesA class implementing CapabilityProvider, registered by spaces.bind(bean) or by being a Spring bean. It is not an agent, so by itself it gets no card, no worker loop, and no @SpaceRef injection.

A capability is constructed by its own constructor with whatever it needs. The shipped ones take a space, or the group's pipes and sampler, as above.

If you also put @AgentSpec or a bound method on the class, it becomes both. The facade registers the capability and binds the agent, and then @SpaceRef fields are injected too. Mixing is legal but usually less clear than two classes.

Keep in mindThe annotation's value is documentation for discovery tooling. The provider's own capabilityType() is what actually governs registration. A mismatch between them is confusing, though not fatal.

The runtime calls start() once before the first advertisement, and refreshes the advertisement on every card refresh. It runs registered providers on the peer's loop, each when its round falls due. In a hand-built runtime without that lifecycle, the host must drive the rounds; the capability model covers the assembly boundary.

attributedefaultmeaning
valuenone (required)the capability type URI, e.g. aspace:cap/vote; informational for discovery tooling, the provider's own capabilityType() governs registration
group"" (all)the group to advertise into; empty means every registered group that has a capability runtime
aspace://guide/exactly-once · chapter 4

Exactly once and fan-in

This chapter covers three annotations for promises a plain lease race cannot make on its own. In a lease race, workers race to claim an entry under a lease, as @SpaceTake does. Use these annotations when an entry must be handled at most once across the fleet, or when several entries must come together into one result.

  • @OrderedTake completes an entry at most once fleet-wide, through the ordered log.
  • @SpaceJoin fires once per key when every part of a case has arrived. Its mode says once per joiner, once per lease, or once fleet-wide. @Part describes each part.
  • @SpaceReduce folds a stream of entries per key into an accumulator that is itself an entry.

The ordered forms need the coordinator of the ordered log registered on the group. The ordered log is a capability that provides strong consistency, for ordered operations, exactly-once delivery, and similar designs.

@OrderedTake: the exactly-once workerOrderedTake

To complete each entry at most once across the whole fleet, use @OrderedTake. It keeps @SpaceTake's contract: take the entry, act on it, then complete it or let its lease lapse. The take goes through the space's ordered-log coordinator instead of the space's own claim race, so each entry is completed at most once, fleet-wide.

The binder owns the loop the coordinator asks of a caller. A take lost to a leader election is resubmitted on the next poll. The appendix explains how the ordered log decides a take.

// examples/example-12-exactly-once-desk -- ExactlyOnceDesk.Clerk
@OrderedTake(space = PAYMENTS, lease = "30s", pollTimeout = "2s", resultLease = "1h")
public PaymentReceipt confirm(PaymentOrder order) {
    return new PaymentReceipt(order.orderId(), order.payee(), order.cents(), peer.name(),
            peer.raft().commitIndex());                        // completes the take with the receipt, once
}

// ExactlyOnceDesk.startClerk(...): the coordinator and its log, built together and registered
OrderedTakes ordered = OrderedTakes.over(new CapabilityPipes(runtime, codec), codec,
        identity, name, members, InstantSource.system(), seed, payments);
group.ordered(PAYMENTS, ordered);      // the log runs on the peer's loop; role=leader is discoverable
Where it livesAny bound class, on a peer whose group has a coordinator registered for the space (group.ordered(space, coordinator)). Binding fails fast otherwise. It also fails when the coordinator takes as a different agent than the space handle writes as.

The member set is fixed, and you supply it. OrderedTakes.over(...) wires the log to its coordinator.

attributedefaultmeaning
space"" (inferred)the coordinated space; empty means the binder's sole coordinated space
group"" (any)the group this binding belongs to, by name or GroupId
lease"30s"the TAKE lease; the action completes within it or the entry reappears
pollTimeout"2s"how long one poll of the coordinator waits before looping
resultLease"1h"write lease for a returned result
resultSpace"" (take space)where a returned result is written
tags{}tag filters, "key=value" or "key", judged before the coordinator is asked for the entry
where{}field filters, "field op value" or "field in a,b,c", as on @SpaceTake, checked at bind time against the parameter type
produces{}the entry types the card lists when the return type does not say (the elements of an Entries fork)
description""what this one action does, published on the card (v0.1.13)

@SpaceJoin: fan-in as one annotationSpaceJoinPartJoined

To act once when all the pieces of a case have arrived, use @SpaceJoin. A fan-out splits one case into several entries, and the join collects them back into one method call. The method takes a Joined bag and returns the next entry. The binder invokes it once per key when every required @Part of that key is present in the space.

A part names its entry type (value). Where the defaults do not fit, a part can also set:

  • space: the space it lives in.
  • key or keyTag: the field or the tag that carries the case's key.
  • tags: filters that narrow it, the way tags narrows a @SpaceTake.
  • optional: the join should fire without it.

The join's own space is the default space for its parts. In the fleet-wide modes it is also where the join's tickets live; a ticket is a JoinTicket entry the binder writes when a key completes. The join's key is the field every part carries unless a part says otherwise.

// agentspaces/examples/example-18-agentic-workflow -- Intake.Assembler
@SpaceJoin(space = SPACE, key = "claimId", resultSpace = Pricing.SPACE, resultLease = "1h",
        parts = {@Part(RegisteredClaim.class), @Part(FraudFinding.class), @Part(CoverageFinding.class),
                 @Part(value = Instance.class, keyTag = "claimId",       // keyed by a tag, written with Tagged
                       tags = "rdf:type=" + Claims.NAMESPACE + Instance.DAMAGE_FINDING)})
public ClaimAssessment assemble(Joined j) {
    RegisteredClaim claim = j.get(RegisteredClaim.class);
    Instance damage = j.get(Instance.class);
    return new ClaimAssessment(j.key(), claim.claimant(), claim.claimedAmount(),
            damage.number("estimate"), damage.string("severity"),
            j.get(FraudFinding.class).fraudScore(), j.get(CoverageFinding.class).covered(),
            j.get(CoverageFinding.class).coverageLimit(), name);   // written to the assessment space
}

How many times one key fires is the mode:

modeone key fireshow
LOCAL (default)once per bound joinerfrom an in-memory set of fired keys; nothing is written to the space before the result
LEASEDonce per lease race, per ticketthe binder writes a JoinTicket entry when the key completes, withdraws it when an older ticket for the key already exists, and fires from a take of the ticket under a TAKE lease through the space's own claim race
ORDEREDonce, fleet-widethe ticket is taken through the space's ordered-log coordinator; every member records the committed claims in one order, and the first committed ticket per key is the only one that fires

The binder does the bookkeeping a hand-written join would need:

  • Earlier parts count. It subscribes to each part and seeds its per-key state from the space on bind, so parts that landed earlier still count.
  • Forgotten keys come back. It seeds again for any key it meets for the first time, so a key it forgot is picked up from what the space still holds.
  • The method gets the newest parts. When a key completes, it re-reads the parts by key and hands the method the newest entry of each type.
  • Stale keys are dropped. It forgets a key whose parts stop arriving after within.
  • Open keys are capped. It keeps at most maxOpen keys open, evicting the least recently touched beyond that.

Read the parts from the Joined bag:

  • key() returns the key.
  • get(type) returns the newest part of a type, and throws when the part is absent.
  • find(type) reads an optional part.
  • all(type) returns every matching entry, newest first.
  • has(type) tells you whether a part is present.
  • entry(type) returns the entry itself, for when the issuer, tags, or lease of a part matter.

The method returns like every other binding: the next entry, a Tagged entry, a Contribution, or null.

The gather: several entries of one type

A part may need more than one entry of its type before the key is complete. This is a gather. Choose how the gather knows it has enough:

  • @Part(atLeast = n) waits for n of them.
  • @Part(countedBy = "SimpleTypeName.field") reads the count from an int field of another part of the same key, whenever that part lands, before or after the entries it counts. A fork can declare how many it emitted, and the gather waits for exactly that many.
  • @SpaceJoin(settle = "300ms") ends a gather of an unknown number. The key fires once it has been quiet that long and every minimum holds.

A join with a single part is allowed when that part gathers or the join sets settle, even with atLeast = 1. The method reads what the key collected with Joined.all(type). Example 18's gatherer waits for as many quotes as the quote desk's request declared and keeps the lowest.

// examples/example-18-agentic-workflow -- Quotes.QuoteGatherer: as many quotes as the request declared
@AgentSpec(name = "quote-gatherer", description = "Keeps the lowest of the quotes asked for",
        goals = {"gather quotes"})
public static final class QuoteGatherer {
    @SpaceJoin(space = Intake.SPACE, key = "claimId", resultSpace = Settlement.LEDGER, resultLease = "24h",
            parts = {@Part(QuoteRequest.class),
                     @Part(value = RepairQuote.class, countedBy = "QuoteRequest.expected")})
    public RepairEstimate pick(Joined j) {
        List<RepairQuote> quotes = j.all(RepairQuote.class);
        RepairQuote lowest = quotes.stream().min(Comparator.comparingDouble(RepairQuote::amount)).orElseThrow();
        return new RepairEstimate(j.key(), lowest.shop(), lowest.amount(), quotes.size());
    }
}

// agentspaces-agent tests -- AgentBinderGatherTest.Settled: an unknown number, ended by quiet
@SpaceJoin(space = "quotes", key = "claimId", settle = "300ms",
        parts = {@Part(value = Quote.class, atLeast = 1)})
Where it livesAny bound class, on a peer whose group registers the join's space and every part's space. The card declares one action of kind join that nobody can invoke remotely.

In ORDERED mode the join's space also needs a coordinator registered for it (group.ordered(space, coordinator)), as @OrderedTake does. A peer hosts one ordered log per group. So an ORDERED join lives on the space that has the coordinator, and its parts may live anywhere.

  • Example 18's Intake.OrderedAssembler puts the join on payments, where the fleet's log is, and names space = "intake" on each of its four parts.
  • The Party Bus plan assembler is a cross-space join too: a brief in the trip space and five research results in the research space, with the party roster as an optional part.
Keep in mindDo not guard a join by reading for your own result. The next stage's take consumes that result, so the guard then sees nothing and the join fires again. Use the mode as the guard.
  • In LOCAL mode every bound joiner fires for every key. Bind one joiner, or make the method idempotent (safe to run twice) against its downstream result. The fleet-wide modes exist for the case where several peers run the same joiner.
  • A method that throws in LOCAL is logged, and the binder releases the key without a retry. Without settle, the next part event for that complete key fires the join again.
  • A method that throws in LEASED or ORDERED lets the ticket's TAKE lease lapse, and the ticket reappears for the next poll. A method that always throws retries until the ticket's write lease (ticketLease) runs out.
  • Parts must be visible to the joiner's replica. A tag shard that excludes a part's tags hides it from the join as well.
attributedefaultmeaning
space"" (inferred)the join's space: the default for parts and where tickets live; empty means the binder's sole registered space
group"" (any)the group this binding belongs to, by name or GroupId
key(required)the field (record component or getX/isX accessor) carrying the case's key on every part, unless a part names its own key or keyTag
parts(required)@Parts, two or more, or one that gathers or a join that sets settle: value, space, key, keyTag, tags, where, atLeast, countedBy, optional
modeLOCALhow often one key fires: LOCAL, LEASED, or ORDERED
name"" (agent.method)the join's name on tickets and cards; joiners of one class on several peers share tickets because they share this name
within"1h"forget a key whose parts have stopped arriving after this long
settle"" (none)fire a complete key only after no new part has arrived for this long, so a gather of an unknown number has an end
maxOpen10000the most keys kept open at once; the least recently touched is evicted beyond it
lease"1h"the part subscriptions' lease, renewed at half-lease while the agent stays bound
ticketLease"10m"LEASED and ORDERED: the ticket's write lease
takeLease"30s"LEASED and ORDERED: the ticket's TAKE lease; the method completes within it or the ticket reappears
pollTimeout"1s"LEASED and ORDERED: how long one poll for a ticket waits before looping
resultSpace"" (join space)where a returned entry is written
resultLease"1h"write lease for a returned entry
produces{}the entry types the card lists when the return type does not say: the elements of an Entries fork; a sealed return type lists its permitted subclasses without this
description""what this one action does, published on the card

@Part: one entry type the join waits forPart

Each element of parts is a @Part. It says which entry type a key needs, where that type's key is read from, and how many of it the key needs.

  • The key comes from a field (the join's key by default, or the part's own) or from a tag (keyTag). A tag lets a type that does not carry the key as a component still join, an ontology instance for one.
  • Filters narrow the part the way tags and where narrow a @SpaceTake.
attributedefaultmeaning
value(required)the part's entry type
space"" (the join's space)the space this part lives in
key"" (the join's key)the field carrying the key
keyTag""the tag carrying the key instead of a field; exclusive with key
tags{}tag filters, "key=value" or "key", all of which an entry must satisfy
where{}field filters, "field op value" or "field in a,b,c", as on @SpaceTake, all of which an entry must satisfy
atLeast1how many entries of this part a key needs before it is complete; the method reads them with Joined.all(type)
countedBy"""SimpleTypeName.field": take the count from a field of another part present for the key, so a fork can declare how many it emitted; overrides atLeast once that part is present
optionalfalsewhether the join fires without this part; an optional part is included when present

@SpaceReduce: the persistent accumulatorSpaceReduceReductions

To keep per-key state in the space itself, such as the PetClinic scheduler's slot book below, use @SpaceReduce. It folds an unbounded stream of entries per key into an accumulator, the running result for that key, and the accumulator is itself an entry. Any peer or client can read it as an entry.

Each step works like this:

  • The method takes the key's current accumulator (null on the first step) and one element, and returns the new accumulator.
  • The binder takes the element under a lease, invokes the method, and completes the element with the new accumulator as the result in the same space. This is one atomic step, so an element is never folded twice.
  • The binder then retires the previous accumulator.

Pick the mode for how strict the per-key order must be. Only ORDERED guarantees that two reducers never fold one key at once. Under LEASED, the check that keeps them apart is exact within one process and best effort across replicas. The appendix explains how tickets keep the steps of one key apart.

Set accumulatorLease as the key's idle timeout. The binder rewrites the accumulator under that lease on every step, so a quiet key lapses. The lapse is an EXPIRED event, which a @SpaceNotify(on = EXPIRED) on the accumulator type can treat as "the session closed". Each step also retires the accumulator before it by a cancel, which raises EXPIRED as well. So the reaction first checks that the key has no newer accumulator, with Reductions.current(space, type, name, key), and returns null when it has one.

// agentspaces-example-apps/agentspaces-petclinic-fleet -- PetClinicFleet.Scheduler: the slot book lives in the space
@SpaceReduce(space = CLINIC, name = "slot-book", lease = "30s", accumulatorLease = "7d",
        produces = Appointment.class)
public Entries book(SlotBook book, Triage triage) {
    SlotBook current = book == null ? new SlotBook(0, 0) : book;      // null on the first step
    boolean urgent = triage.acuity().equals("EMERGENCY")
            || triage.acuity().equals("URGENT");
    String vet = urgent ? ON_CALL : VETS.get(current.routineTurn() % VETS.size());
    String slot = urgent ? "immediate" : slotLabel(current.nextSlot());
    SlotBook next = urgent ? current
            : new SlotBook(current.routineTurn() + 1, current.nextSlot() + 1);
    return Entries.of(next,                                              // the accumulator, written atomically with the take
            new Appointment(triage.requestId(), triage.petName(), vet, slot, triage.acuity()));  // the side output, after it
}

The PetClinic scheduler above keeps its slot book in the space. The appendix tells what it replaced and how its test checks it.

The method can return one of these:

  • The accumulator.
  • A Tagged accumulator. Its tags merge beneath the binder's.
  • An Entries fork holding exactly one accumulator and any side outputs. The binder writes it after the atomic step, the way a fork's elements are written.
  • null, which consumes the element and leaves the accumulator as it was.

The key is a field of the element (key) or one of its tags (keyTag). With neither, every element folds into one accumulator, which serializes them all through one ticket.

The accumulator lives beside its elements, since the atomic completion needs one space. A stage that wants it elsewhere reacts to it and writes a copy.

attributedefaultmeaning
space""where the elements, the accumulators, and the tickets live; empty means the sole registered space
group"" (any)the group this binding belongs to; empty means any group whose spaces satisfy it
name""the name the tickets and the accumulator's reduce tag carry; <agent>.<method> by default; may not equal a @SpaceJoin's name on the same agent
key""the element's field carrying the key; empty with an empty keyTag folds every element into one accumulator
keyTag""the element's tag carrying the key instead of a field; exclusive with key
tags{}tag filters on the element, "key=value" or "key", as on @SpaceTake
where{}field filters on the element, "field op value" or "field in a,b,c", as on @SpaceTake
modeLEASEDLEASED takes the key's ticket through the space's claim race; ORDERED takes it, the elements, and the retired accumulators through the space's ordered-log coordinator, so two reducers never fold one key at once
lease30sthe take lease on an element and on the ticket; the drain renews the ticket before every step and stops when a renewal fails, so one step must fit inside it
pollTimeout1show long a take waits for an element, and how often untaken elements are swept
accumulatorLease24hthe accumulator's and the ticket's write lease: the key's idle timeout; refused when shorter than lease
subscriptionLease1hthe element subscription's lease, renewed at half-lease
maxOpen10 000the bound on remembered keys
produces{}the side-output types of an Entries return, for the card; the accumulator type is always declared
description""what this one action does, published on the card
Keep in mindWrite a commutative fold, one whose result does not depend on order, or carry a sequence in the element. The fold takes a key's elements in the order the space hands them out. That order is first in, first out only in a LocalSpace; a ReplicatedSpace promises no order.
  • Two accumulators can be visible for a moment. Readers see one accumulator per key, except between a successor's write and the predecessor's retirement. That window is normally microseconds, and after a crash it lasts until the next drain (the reducer's next pass over the key). A plain read returns the older one.
  • Use Reductions.current(space, type, name, key) where a step of staleness after a crash would matter. It returns the newest by its steps tag.
  • Busy keys cost more. Each step costs one take and one completion and leaves two tombstones (markers that record a removal). A key that folds thousands of elements an hour wants the gather over a window instead.
  • A method that throws ends the drain, and the element reappears by its lease, the @SpaceTake retry.
  • Some tags are plaintext. The tags reduce, key, and steps are plaintext under content encryption, as a join's ticket tags are.
aspace://guide/spring-boot · chapter 5

The Spring Boot starter

The starter (agentspaces-spring-boot-starter) sets up AgentSpaces inside a Spring Boot application. Use it when your application runs on Spring Boot and you want to configure the peer in application.yml.

  • It wires the peer from properties.
  • It enrolls annotated beans through an ordinary bean post-processor.
  • It uses the Spring you already run. It deliberately declares no Spring dependency of its own. It compiles against provided-scope stubs and binds to the Spring your application already runs.

PropertiesAgentSpacesProperties

The table lists every property the starter reads. The default column shows what you get when you leave a property out.

propertydefaultmeaning
agentspaces.keystore(ephemeral)directory persisting the peer's Ed25519 identity; omit for a fresh identity per run
agentspaces.bind(dial-only)host:port to listen on; omit for a NAT-restricted, dial-only peer
agentspaces.roles[]topology roles this peer volunteers for, e.g. RENDEZVOUS, RELAY
agentspaces.tick-millis250the pace of the deprecated GroupRuntime.onTick work only; the ordered log's election timeout is 1.25 to 2.25 s whatever it says, and the node itself runs each job when it falls due (the node loop)
agentspaces.peer-ad-interval-millis30000how often the node re-floods its own peer advertisement; between refreshes a newcomer receives it directly
agentspaces.coalesce-millis20the frame coalescing window: rumors and pipe frames to one peer batch into one signed frame, toward peers that advertise it; 0 turns it off
agentspaces.lazy-pushtruerumors ride a self-pruning tree toward members that understand it; off, the node gossips with random fan-out only
agentspaces.card-refresh-millis300000how often bound agents' cards republish
agentspaces.groups[].namenoneapplication-facing group name
agentspaces.groups[].foundingnonefounding text; every peer that receives the same text derives the same GroupId from it. The group has no signed founding, so a peer cannot join it by id: give every peer the same text. Exactly one of founding and join identifies the group; neither set means the group name doubles as the founding text
agentspaces.groups[].joinnonejoin an existing self-certifying group by aspace://<groupId> (or bare GroupId): the signed founding advertisement is fetched from the seeds and verified against the id before joining. Some seed must hold a signed founding: a group started from founding text has none, and the join then times out. A join group also needs at least one seeds entry or BeaconLocator bean, or startup fails (finding the group)
agentspaces.groups[].join-timeout-millis10000how long the join-by-GroupId fetch waits for a verified answer
agentspaces.groups[].seeds[]existing members to dial, host:port
agentspaces.advertisethe bind addressthe address carried in this peer's self-advertisement, host:port or scheme://host:port: a pod's routable address, a NAT's public side
agentspaces.groups[].membershipopenopen or invite: under invite a candidate presents a founder-issued or delegated join credential; with founding, the founder is founder or this peer
agentspaces.groups[].foundernonethe founder's PeerId of an invite group founded from a string; required on every member but the founder
agentspaces.groups[].join-credentialnonethe aspace:join credential this peer presents, as JoinCredentials produces
agentspaces.groups[].founding-documentnonea signed founding advertisement this peer joins with (base64 CBOR); exclusive with founding and join
agentspaces.bootstrap.*, agentspaces.groups[].bootstrap.*nonethe locator chain (agentspaces-bootstrap project): domain, order, dns-srv, url, k8s.*, accept-group-id-from, beacon-peer, the URL guards
agentspaces.bootstrap.refresh-min, refresh-maxPT30S, PT10Mhow often at least and at most the node re-asks the group's locators while its view is empty (the chain's LocatePolicy; PeerNode.Builder.locateInterval node-wide)
agentspaces.bootstrap.requirefalsefail startup, naming the group, when the first locate answers no endpoint and no founding
agentspaces.bootstrap.tracefalselog every locate's rows at INFO; off, the first locate and every re-ask that changed the endpoints are logged, the rest at DEBUG; the console's traffic panel carries the last hint and trace per group
agentspaces.relay.budget-bytes-per-daynonewhat this peer forwards as a RELAY per group per day, through RelayPolicy.dailyBudget when no RelayPolicy bean is defined; the counters are on the traffic panel
agentspaces.groups[].content-keynonethe group content key for payload encryption (epoch 0 of the group's ring); also what the key-wrap capability serves
agentspaces.groups[].content-key-rotation.*nonerotate-every (unset: never rotates on its own; needs the founder or a key-rotator grant), cutover-delay (two gossip periods plus 30s), writer-grace (1h); members follow rotations whenever content-key is set (content encryption)
agentspaces.groups[].spaces[].namenonea replicated space to attach
agentspaces.groups[].spaces[].strategyLEASE_RACELEASE_RACE or AUCTION; ORDERED is not a space strategy but a coordinator over the ordered-log capability (space admission)
agentspaces.groups[].spaces[].settle-window-millis200the take settle window
agentspaces.groups[].spaces[].admissiongroupgroup, allowlist, credential, or authorizer (space admission)
agentspaces.groups[].spaces[].allowed-agents[]the admitted agents under admission: allowlist
agentspaces.groups[].spaces[].credential-issuerthis nodeunder admission: credential, the PeerID whose signed credentials admit agents; only that node may grant and revoke
agentspaces.security.profilemtlsdev-local, mtls, mtls-oidc, zero-trust; selects transports, channel mode, and who answers authorization
agentspaces.identity.agent-keyspeerpeer signs every bound agent's records with the peer key; subordinate gives each bound agent a peer-certified Ed25519 key of its own, renewed at half-life, so its records, claims, and transitions are AGENT_ATTESTED, its card carries the key and certificate, and its @SpaceRef handles are per-agent views (content encryption)
agentspaces.identity.agent-keystorenonedirectory persisting subordinate agent keys (and their X25519 keys) across restarts; needs agent-keys: subordinate
agentspaces.identity.agent-certificate-ttl24heach agent certificate's lifetime; certificates re-issue at half-life and are judged at signing time
agentspaces.security.oidc.*noneissuer, audience, jwks-url (all required under the OIDC profiles), plus this node's own token or token-file
agentspaces.security.grants.*(any member)under the membership profiles, PeerID or AgentID (peer/name) lists narrowing one operation: raft-voter, raft-client (submit to an ordered log without voting), directive-issuer, connector-serve, key-holder, space-write, space-take, vote, model-serve; v0.1.13 adds key-rotator, which nobody holds by default, and which every member must list identically
agentspaces.transport.channel-auth(from profile)signed signs every frame's envelope; attested negotiates unsigned frames over channels the transport authenticated; session acts as attested where the transport attests, and on a channel it cannot attest, one signed hello per connection sets a session key and frames carry a MAC under it. The profile picks the default: session for dev-local, attested for mtls and mtls-oidc, signed for zero-trust
agentspaces.transport.tls.enabled(from profile)switch the TCP listener and dialer to TLS with this peer's identity-endorsed channel certificate
agentspaces.transport.dtls.enabledfalseregister the DTLS binding (needs agentspaces-transport-dtls); with bind it listens and advertises after agentspaces.bind's endpoint, at priority, at advertise if set
agentspaces.transport.dtls.attestationidentityidentity attests with the channel certificate (CA mode when a trust store is set); none encrypts only and is refused under require-attestation
agentspaces.transport.dtls.connection-idtrueRFC 9146 Connection ID, so an association survives NAT rebinding
agentspaces.transport.dtls.mtu / window / idle-timeout1200 / 64 / 60sdatagram budget, PDUs in flight, silence before an association fails
agentspaces.transport.dtls.max-half-open / hello-rate-per-source1024 / 8listener flood limits; raise the hello rate for many peers behind one NAT address
agentspaces.transport.dtls.protocols[DTLSv1.2]DTLS versions offered; DTLS 1.3 joins when BouncyCastle negotiates it
agentspaces.transport.ws.enabled / bind / advertise / priority / pathfalsethe WebSocket listener block (needs agentspaces-transport-http); path defaults to /aspace; follows the tcp rule: any profile, refused under require-attestation
agentspaces.transport.ws.allowed-origins[]browser origins admitted on upgrade and on the exchange (403 otherwise); empty refuses every browser, * any
agentspaces.transport.wss.* / https.*falsethe same blocks inside TLS, with the tls binding's key and trust stores; a certificate-less dialer (a browser) is admitted as unattested
agentspaces.transport.http.enabled / bind / pathfalsethe HTTP exchange of the design's appendix C; path defaults to /aspace/h, also for https; may share ws's bind, one port for both
agentspaces.transport.ws / wss / http / https: idle-timeout, ping-interval, long-poll, opens-per-source-per-second60s / 30s / 25s / 4a connection or exchange session silent for idle-timeout closes; a WebSocket idle for writing sends a ping every ping-interval; an exchange download request is held long-poll when it has nothing to send; opens-per-source-per-second limits how many exchange sessions one source address opens each second, and sets no cap on sessions
agentspaces.transport.webrtc.enabled / priorityfalsethe WebRTC acceptor (needs agentspaces-transport-webrtc): advertises (webrtc, "sig", priority) after every stream endpoint; attests by signed fingerprint, so it satisfies require-attestation
agentspaces.transport.webrtc.ice-servers[]STUN and TURN servers (urls, username, credential); empty gathers host and mDNS candidates only
agentspaces.transport.webrtc.dial-timeout / offers-per-peer-per-minute / candidates-per-session / max-signal-bytes15s / 6 / 64 / 65536the dial bound and the per-peer signalling rates; none caps the number of sessions or connections
agentspaces.transport.webrtc.offload.frames-per-minute / retry-after30 / 5mthe relay offload: once more than this many frames crossed a relay to or from one member in a sliding minute, the node dials that member's webrtc endpoint from its loop (never from a send) and sends directly once open; a failed dial is retried no sooner than retry-after. Settings, not caps
agentspaces.transport.quic.enabled / bind / advertise / priorityfalsethe QUIC listener block (needs agentspaces-transport-quic), attesting with the TLS material
agentspaces.transport.udp.enabled / allow-plaintextfalse / falsebare plaintext UDP; registers only under dev-local or with allow-plaintext
agentspaces.multicast.sealfalseseal each group's beacon datagram under its content-key, so bystanders read nothing
agentspaces.transport.tls.trust-storenonesetting it switches to enterprise-CA mode: peers attest only when their chain validates to these anchors
agentspaces.transport.tls.key-storenonethis node's CA-issued credential (PKCS#12/JKS), with key-store-password / trust-store-password
agentspaces.transport.tls.crls[]cached CRL documents
agentspaces.transport.tls.revocation-strictfalsefetch OCSP and CRL distribution points live instead of relying on the cached CRLs
agentspaces.transport.tls.key-store-password, .trust-store-passwordunsetpasswords for the key store and trust store files when they are protected
agentspaces.transport.tls.crl-refresh5mhow often the crls files are re-read; a replaced CRL re-judges every live connection
agentspaces.transport.tls.revocation-validatorfounderfounder-or-ca also accepts a peer revocation the CA's CRL proves, carried as evidence, and makes this node issue one when its CRLs revoke a connected peer (content encryption)
agentspaces.transport.tls.require-attestationfalserefuse every frame not arriving on a channel attested for its sender, which is how CA revocation becomes a fleet-wide eject. Any attesting transport satisfies it: TLS, or an enabled DTLS (identity attestation), QUIC, WSS, or WebRTC block. Startup refuses when none of them is enabled, and refuses ws, http, https, udp, and DTLS with attestation: none, which cannot attest
agentspaces.crypto.signature-providerjdkthe Ed25519 implementation by SignatureProvider name; every provider is pinned to the golden signature vectors
agentspaces.multicast.enabledfalseLAN bootstrap beacon: announce endpoints on multicast.group (default 239.255.42.99:7787) and dial peers heard, so a LAN fleet needs no seeds. A node announces when it joins a group, then after 1, 2, 10, and 20 minutes, and again from 1 minute; hearing a new peer starts the list again
agentspaces.multicast.interval-millis60000the beacon's first wait after a join; the later waits are 2, 10, and 20 times it
agentspaces.ttl.strictfalserefuse to start on a configured TTL, lease, or expiry under 60 s with no expert override; off, it logs a warning (the TTL floor)
agentspaces.ttl.expert-overridesnonekey to reason: a key named here may be under 60 s; write a dotted key in brackets, such as "[agentspaces.relay.path-ttl]"
agentspaces.watchdog.escalationreportwhat happens when the watchdog escalates a loop: report (ERROR log, health DOWN, liveness BROKEN) or exit (close and exit with status 70) (the node loop)
agentspaces.watchdog.hold-limitunsetstop renewing an @OrderedTake handler's take after it has held the entry this long, so another member takes it; unset, a handler keeps its entry while it runs
agentspaces.watchdog.connector-hold-limitunsetthe same limit for a connector's held operation: an AssetInvocation held this long is no longer renewed and lapses to another replica
agentspaces.watchdog.period-millis, grace-millis, slow-millis, wedge-millis2000 / 250 / 100 / 5000the process's watchdog: how often it checks each loop, the grace for a missed timer or wake, a run counted as slow, and a run treated as stuck (its job is fenced and the loop restarted)
agentspaces.watchdog.escalate-after, escalate-window-millis, fence-limit-millis3 / 600000 / 120000when the watchdog escalates: this many restarts of one loop inside the window, or a job fenced for this long
agentspaces.loop.pool-max, pool-idle-millis0 / 60000the loop pool's most threads (0 means min(8, max(2, cores / 2))) and how long an idle pool thread lives
agentspaces.loop.grow-lateness-millis, stretch-lateness-millis, stretch-cap20 / 100 / 4the lateness that grows the pool by a thread, the lateness at the pool's maximum that slows local work, and how far it may slow (1 to 4)
agentspaces.retirement.enabled, retirement.aftertrue / 24hlost members are retried on a fixed table and retire after this long unanswered; off, a lost member is retried for ten minutes and forgotten (membership status)
agentspaces.post-retirement.enabledfalsewhen a group's view has been empty for two minutes and nothing else brought anyone back, introduce this node to retired members' last addresses
agentspaces.health.refuse-traffic-when-isolatedtruereadiness turns REFUSING_TRAFFIC while this node is isolated in a group, and back once none is; liveness is never touched
agentspaces.gossip.audit, audit-sessions, audit-budgettrue / 4 / 1048576repair spaces by entry toward members that advertise wire.ae=2; audit sessions per asker (1 to 4); the bytes one answer may hold (4096 to 4194304) (replication by entry)
agentspaces.gossip.probe-hash-streams32a probe carries a hash per stream up to this many streams, then the root alone (0 to 256)
agentspaces.space.horizonper-entryper-entry advertises wire.horizon=1, so a withdrawn entry is collected ten minutes after its own lease expiry once the whole view carries the hint; legacy keeps twice the longest lease
agentspaces.space.renew-shortening-logtruelog once per space, at INFO, the first renewal that asks for less than its lease has left; the renewal keeps the longer lease
agentspaces.transport.quic.dial-timeout, transport.dtls.dial-timeoutunset (10 s)the bound on a dial's handshake, 1 ms to 10 min; unset, the transport's own default
agentspaces.capabilities.enabledtruethe capability runtime as a whole (capability services)
agentspaces.capabilities.*see noteper-capability toggles: aggregate, vote, semantic-discovery, key-wrap default on; gossip-learn defaults off, and true wires the default weight-averaging learner. ordered-log=true always fails startup, because the Raft log needs a fixed member set the starter cannot infer; register a @ProvidesCapability bean that wraps RaftLog with the members instead
agentspaces.capabilities.votes-spacevotesthe space the vote capability runs over; when the group configures no space by that name the starter builds a private one, which does not count for single-space inference and which @Ballot and @OnDecision cannot bind to: list the vote space under groups[].spaces when agents vote
agentspaces.console.enabledfalseserve the fleet console (the fleet console)
agentspaces.console.port7590console HTTP port
agentspaces.console.fleet-name""the fleet name the console displays
agentspaces.console.command.enabledfalsecommand-and-control routes; requires a token or a configured identity provider
agentspaces.console.command.token""static operator secret gating the command routes; when set it always takes precedence over the identity provider
agentspaces.console.command.required-scopeaspace:console:operatewith the token blank and security.oidc.* set, the scope each operator's bearer JWT must carry
agentspaces.console.command.control-spacefleet-controlthe space directives are written to; workers subscribe here
agentspaces.console.command.audit-spacec2-auditthe space each command's audit record is written to, under a 24-hour lease; the starter writes no record unless the group declares this space
agentspaces.a2a.enabledfalseserve the A2A gateway over the fleet's AgentCards (bind 127.0.0.1, port 7594, group, space, external-base-url); a routable bind fails at startup without a token or a configured security.oidc.*, whose bearer JWTs must then carry required-scope (default aspace:a2a:client)
agentspaces.a2a.token, .fleet-name, .provider, .allowed-webhook-hosts, .task-lease-millis, .result-lease-millis"", "", AgentSpaces, [], 600000, 3600000the static bearer token (takes precedence over OIDC when set), the names the gateway's agent card reports, the hosts push notifications may target, and the leases on the task written and the result kept
agentspaces.springai.*see Spring AIthe Spring AI integration, from the separate agentspaces-springai library: fleet tools, take-lease renewal, chat memory in a space, the model service, embeddings, usage, and MCP export
agentspaces.embabel.remote-actions-enabledtrueexpose discovered cards to the Embabel planner (Embabel)
agentspaces.embabel.remote-action-timeout-millis30000how long a generated planner action waits for its result
agentspaces.embabel.auto-deploytrueredeploy the generated remote-action agent onto the platform whenever the set of remote actions changes
agentspaces.embabel.deploy-poll-millis2000how often the deployer checks the registry for arrivals and expiries
agentspaces.embabel.remote-agent-descriptionCapabilities other fleet members advertise through AgentCardsdescription on the generated planner agent
agentspaces.embabel.remote-agent-nameremoteFleetthe name of the generated agent
agentspaces.embabel.* (second generation)see the second generationgroups, card-name, serve-actions, action-space, action-lease, advertise-unserved, remote-action-retry, on-timeout, remote-action-default-cost, carry-conditions, the deployer's timings, take-mode, and served-max-run

Keys changed in 0.7.0AgentSpacesProperties

This section lists what a 0.6.0 configuration meets in 0.7.0. The table above has every key with its default.

New keys

  • Time and the loop: agentspaces.watchdog.* and agentspaces.loop.* (time and the node loop).
  • The TTL floor: agentspaces.ttl.strict and ttl.expert-overrides (the TTL floor).
  • Replication by entry: agentspaces.gossip.probe-hash-streams, gossip.audit, gossip.audit-sessions, gossip.audit-budget, agentspaces.space.horizon, and space.renew-shortening-log (replication by entry). An unknown key under agentspaces.gossip or agentspaces.space refuses to start, so a typo never passes for the default.
  • Lost members: agentspaces.retirement.enabled, retirement.after, post-retirement.enabled, and health.refuse-traffic-when-isolated (membership status).
  • Dial bounds: agentspaces.transport.quic.dial-timeout and transport.dtls.dial-timeout.
  • Embabel: the second generation's agentspaces.embabel.* keys (the second generation).

Changed defaults

  • agentspaces.multicast.interval-millis: 5,000 to 60,000. It is the first wait of the beacon's table.
  • The member TTL: 30 s to 45 s, or the larger of 45 s and 1.5 times the quiet probe cycle for a member heard only through probes (the member TTL).
  • Raft: on a started node the election timeout is 1.25 to 2.25 s and the leader's heartbeat 250 ms, whatever tick-millis says.
  • Push-sum: a round every second, and @OnEstimate settles over 8 s unless you name a settle.
  • TTLs: a configured TTL, lease, or expiry under 60 s logs a warning at start, and refuses to start under agentspaces.ttl.strict.
  • The quiet probe may stretch to 16 times its base period (4 times before), still bounded so every member is heard twice inside its TTL.
  • Redials: seeds are redialed on a fixed table that never gives up, and lost members on a fixed table until they retire (the redial table).

Changed meaning

agentspaces.tick-millis (250) now paces only the deprecated GroupRuntime.onTick work and the providers that override tick(). A deployment that set it to another value runs the protocol's timers at their 250 ms values.

Which keys bind from YAML

  • Every agentspaces.loop.* and agentspaces.watchdog.* key binds from YAML, under the Spring starter, under Micronaut, and in the FleetRuntime that LangChain4j and Groovy hosts use.
  • The same names also work as JVM system properties (-Dagentspaces.loop.pool-max=4). A key set in YAML wins.
  • One key is a system property alone: agentspaces.watchdog.held-report-millis (60000), how long an @OrderedTake handler holds its entry before the watchdog names it.
  • They are per process. One watchdog and one loop pool serve every node in a JVM.
agentspaces:
  loop:
    pool-max: 4                 # 0 (the default) means min(8, max(2, cores / 2))
  watchdog:
    escalation: exit            # a host with no liveness probe
    hold-limit: 10m
  space:
    horizon: per-entry          # the default; legacy keeps twice the longest lease
  retirement:
    after: 24h

Finding the group: agentspaces.bootstrap and the node seams

This section shows how a peer finds its group, and how to replace each step with a bean of your own. With only seeds (addresses of peers to dial) configured, the starter dials the list and expands names that resolve to several addresses.

For more ways to find a group, add ai.badmonkey.agentspaces:agentspaces-bootstrap-spring-boot-autoconfigure:0.6.0 beside the starter. The bootstrap family did not change for 0.7.0, so 0.6.0 is its current release. Then:

  • The agentspaces.bootstrap.* keys build each group's chain, the ordered list of ways to find it, from the locators.
  • A group's own bootstrap block overrides the fleet-wide block, key by key.
agentspaces:
  bootstrap:                               # fleet-wide defaults
    domain: auto                           # the host's search domain
    timeout: PT3S
  groups:
    - name: research-fleet
      founding: research-fleet-v1          # a group started from a text
      bootstrap:
        order: [ seeds, dns-sd, url ]      # this group's chain
        url: https://agentspaces.corp.example/.well-known/agentspaces/beacon.json
    - name: partner-fleet
      join: aspace://q9c2b...              # a group with a signed founding
      bootstrap:
        order: [ url ]                     # no seed list: the document names the seeds
        url: https://partner.example/.well-known/agentspaces/beacon.json
        beacon-peer: z6Mk...partnerBeacon  # the PeerId that must sign it

Every step is a bean the application may define, and each default yields to yours. The core starter collects the BeaconLocator, Transport, PeerNodeCustomizer, and PeerNodeConfigurer beans. The bootstrap module adds a DnsResolver and a BootstrapChainFactory:

beandecidesdefault
BeaconLocatoran extra way to find a group, for every group or, through appliesTo, for one; @Order ranks themnone
DnsResolverhow the DNS locators resolvethe JDK's JNDI resolver
BootstrapChainFactoryhow each group's chain is composed from the seeds locator and the other locatorsChainComposer over the properties, or the core's plain chain when no bootstrap key is set
PeerNodeCustomizerthe node builder's tunables (advertisement TTL, rate limits, channel trust) before build()none
PeerNodeConfigurerthe built node, after the transports register and before any group joinsnone
@Configuration
class FleetBootstrapConfig {

    /** An extra locator for every group; @Order ranks it among the others. */
    @Bean @Order(10)
    BeaconLocator cloudMapLocator(DnsResolver dns) {
        return new SrvLocator(
                "_aspace._tcp.agentspaces.corp.internal", "tls", dns);
    }

    /** Replace the resolver: DNS over HTTPS and DNSSEC. */
    @Bean
    DnsResolver dnsResolver() {
        return DnsJavaResolver.builder()
                .doh("https://dns.corp.example/dns-query").dnssec(true).build();
    }

    /** The locators arrive as [seeds, beans...]; compose them as you like. */
    @Bean
    BootstrapChainFactory firstWins() {
        return (group, locators) ->
                BootstrapChain.builder().firstWins().addAll(locators).build();
    }

    /** Touch the node builder without replacing the node. */
    @Bean
    PeerNodeCustomizer tenMinuteAds() {
        return builder -> builder.peerAdTtl(Duration.ofMinutes(10));
    }
}
Where it livesBootstrapProperties and BootstrapAutoConfiguration in the bootstrap module, which runs before AgentSpacesAutoConfiguration; BootstrapChainFactory, PeerNodeCustomizer, and PeerNodeConfigurer in the core starter. The Micronaut chapter lists the same seams as beans.
Keep in mindA group with join: needs something to ask: a seed, a locator under agentspaces.bootstrap.order with its key set, or a BeaconLocator bean. The starter checks the composed chain before it joins and refuses at once, naming the chain and the three remedies, when the chain has nothing to ask. A join that has something to ask keeps asking inside join-timeout-millis: it dials again every endpoint that refused, asks the chain again while nothing is connected, and reports the attempts when the time runs out. A group started from a founding: text has no signed founding and cannot be joined by id; the report says so when the seeds it reached sent nothing. An order that leaves out seeds while the group lists some logs one warning at startup, and the seeds stay out.

The starter builds each group's chain in this order:

  • A BootstrapChainFactory bean wins over everything else.
  • Otherwise, the seeds locator comes first, when order names seeds.
  • Then the property locators, the ones the properties name in order.
  • Then your BeaconLocator beans. Under bean-locators-first, they come before the property locators.

A misconfigured block fails the context at startup and names the property. Two examples are an unknown name in order, and a plain-DNS locator in accept-group-id-from without insecure-group-id.

A group started from a founding: text does not need that seed. It also cannot be joined by id, because it has no signed founding.

Security profiles and authorizationAuthorizersAuthorizer

Use this section to choose how peers prove who they are and who may do what. One property sets the whole posture: agentspaces.security.profile. It does two jobs:

  • It picks the transports and channel mode a fleet forms over. The default, mtls, means a fleet comes up over TLS with attested channels and no further configuration.
  • It picks who answers the one question every privileged operation asks: authorizer.permits(peer, operation, scope).

The answerer depends on the profile:

  • Under dev-local and mtls, the answerer is membership-rooted: one authorizer per group over the group's admitted members, narrowed by the optional grants lists. A grant never outlives admission.
  • Under mtls-oidc and zero-trust, the answerer is your identity provider. Scopes of the form aspace:<operation>[:<scope>] decide.

In the two OIDC profiles:

  • Each peer carries its JWT inside its own signed self-advertisement.
  • The token's agentspaces_peer claim binds it to one PeerID.
  • Membership still counts. A token is valid in every group a node joins, so each group's authorizer also requires the peer to be a current member of that group. It also refuses a peer or agent the group has revoked. The scopes decide only after those two checks pass.
  • Mistakes show early. Incomplete OIDC configuration fails at startup, before any request is refused.

The agentspaces-auth-oidc module supplies that answerer. Its OidcAuthorizer validates each peer's bearer JWT against the issuer's JWKS. It is the Authorizer the MTLS_OIDC and ZERO_TRUST profiles install.

# application.yml
agentspaces:
  security:
    profile: mtls-oidc
    oidc:
      issuer: https://idp.example.com
      audience: agentspaces-fleet
      jwks-url: https://idp.example.com/.well-known/jwks.json
      token-file: /var/run/secrets/aspace-token   # re-read each card refresh
  groups:
    - name: research-fleet
      spaces:
        - name: tasks
          admission: authorizer    # aspace:space-write:tasks / aspace:space-take:tasks
        - name: vault
          admission: credential   # issuer-signed SpaceCredential entries admit

The starter passes the authorizer to these parts for you:

  • the key-wrap provider;
  • spaces admitted by authorizer;
  • the vote tally;
  • the DirectiveGates bean workers use to obey the console.

Pass the Authorizer bean, or Authorizers.forGroup(name), to a RaftLog, DataQueryClient, or ConnectorRuntime you wire yourself.

What the starter does with your beansAgentSpacesBeanPostProcessorAgentSpaces

The starter turns your annotated beans into agents without extra code. After initialization, any bean declaring an agent identity or carrying bound methods enrolls automatically, in this order:

  • @SpaceRef and @CapabilityRef fields inject first.
  • Then bid functions wire, worker loops start, and subscriptions register.
  • Then one card publishes per group the bean bound into.

Group selection is by space coverage, narrowed by any group attribute the annotations carry:

  • A bean binds into each configured group whose spaces cover the spaces it names.
  • A bean naming a space no group registers fails at startup, which is when a configuration mistake should show.
  • A @ProvidesCapability bean registers on the group's capability runtime the same way.
  • A SchemaRegistry bean, when you declare one, is applied to every space the starter builds and to every card it publishes. Records and cards then name each type the same way (the schema registry section shows NamespaceSchemaRegistry).
  • Plain beans pass through untouched.

The facade bean is there when you outgrow the annotations: AgentSpaces navigates groups and spaces Embabel-style, with the typed verbs of the Space API as terminal operations.

// Ordinary application code that happens to need the fleet: inject the facade.
@RestController
public record OrderIntake(AgentSpaces spaces) {

    @PostMapping("/orders")
    public void submit(@RequestBody Order order) {
        spaces.group("orders-fleet").space("work")
              .write(order, Lease.of(Duration.ofMinutes(10)));
    }
}
Where it livesAnywhere Spring can inject a bean. A controller, a scheduled job, a message listener, a service: none of them need to be agents, and none of them get cards. The facade is also how you reach discovery (group.discovery()) and typed capability clients (group.capability(...)), which is why the Space API and the capability services both start from it.
Keep in mindWhen you add a space to an annotation, add it to the YAML too. Group selection happens at enrollment, from what a bean's annotations name. A bean whose spaces no configured group covers fails at startup, so a typo shows at once and the bean never sits quietly unused.

Rules and flows a console publishes

Two properties, off by default, let a managed peer obey what a platform console publishes into its group without any call to the console:

  • agentspaces.rules.gate=true installs a ConstraintGate on every binder (chapter 1) and advertises rules.gate=true.
  • agentspaces.flows.reconcile=true installs a FlowReconciler (chapter 1) and advertises flowVersion and flowConformance.

Both read entries the group already replicates (constraints, flow-control), so a peer without a console sees nothing new, and a peer the console manages needs no credential for it.

aspace://guide/embabel · chapter 6

Embabel integration

Embabel is a JVM agent framework whose planner chains actions toward a goal. The embabel-agentspaces extension connects an Embabel application to the fleet, and it works in both directions:

  • Outbound. Your Embabel agents become discoverable to the fleet.
  • Inbound. The fleet's discovered skills become actions for your planner.

The extension activates only when Embabel is on the classpath.

Outbound: cards from your @Agent beansAgentSpaces

Use the outbound direction to let other peers find your Embabel agents. An AgentCard is the description of an agent that a peer publishes to its group. Every Embabel @Agent bean's metadata becomes one published AgentCard automatically, named by @Agent(name) (the second generation):

  • its description,
  • its @AchievesGoal statements,
  • its @Action input and output types.

Worker loops still come from @SpaceTake on the action, so an Embabel action joins the fleet with one added annotation:

// embabel-agentspaces -- EmbabelBinderTest.SpaceBoundEmbabelWorker, trimmed
@Agent(name = "spaceWorker", description = "Takes tasks from the work space")
public class SpaceBoundEmbabelWorker {

    @Action
    @SpaceTake(space = "work")                     // lease defaults to "10m"
    public FindingEntry research(TaskEntry task) {
        return new FindingEntry(task.topic(), "done");   // your action body: ordinary code
    }
}

Inbound: remote actions for the plannerEmbabelRemoteActionsRemoteActions

Use the inbound direction when your planner should use work that other peers' agents serve. The remote-actions bridge turns eligible foreign AgentCard actions into typed actions you can invoke. An action is eligible when:

  • its input and output classes resolve locally, and
  • its task space can be selected.

Invoking an action does not call the remote peer directly. The bridge works through the space, as a choreography of entries:

  • It writes the input entry where the remote workers take that type from.
  • It waits for a result entry that correlates with the request. By default that means equal values on every record component name the input and result share. A Finding carrying its ResearchTask's topic already follows this convention.
  • Crashes are covered. A remote worker that crashes mid-step lets its lease lapse. Whoever finishes, the awaited result still arrives.
  • Unserved calls time out. An invocation nobody serves times out empty, with the entry still leased in the space.

Since v0.1.13 a card declares its actions. Each declared action pairs what one bound method consumes with what it produces, and carries that method's description. The bridge offers exactly those pairs, and falls back to every consumed-by-produced combination only for older cards. RemoteAction.declared() exposes the declared action.

// agentspaces-agent -- RemoteActionsTest, trimmed; ResearchTask and Finding are the records below
RemoteActions fleet = RemoteActions.over(spaces.group("research-fleet"), peerId)
        .route(ResearchTask.class, "tasks")      // one-space groups need no routes
        .resultsIn(Finding.class, "tasks");

// Cards arrive by gossip, so the list is empty until a worker's card has landed.
RemoteAction research = fleet.producing(Finding.class).stream().findFirst().orElseThrow();
Finding f = research.invoke(new ResearchTask("req-1", "agentic memory"),
                Finding.class, Duration.ofSeconds(30))
        .orElseThrow();                          // empty means nobody answered in time

For the GOAP (goal-oriented action planning) planner, EmbabelRemoteActions generates a class annotated @Agent. The class has one real typed @Action method per remote action, and card goals become @AchievesGoal.

Tests prove the effect on planning: an agent whose local actions cannot chain to a goal type finds no plan alone. Once the fleet's cards are bridged in, it finds and executes the multi-hop plan through remote specialists. Cards are TTL-leased (they expire unless their owner refreshes them), so the planner's action space tracks the live fleet.

Where it livesWire the bridge once at startup, outside any agent. Build the RemoteActions registry as a @Bean (or in assembly code), declare the routes, and hand it to EmbabelRemoteActions.

The partybus does exactly this in one method, looping over its request and result types to register routes. Individual agents stay unaware of the bridge. They are on the serving side, taking the entries the bridge writes.

Keep in mindCorrelation is by convention. The default matches equal values on every record component the input and result share. Records with no shared component names, and non-record types, accept the first candidate result. That can associate concurrent requests with the wrong answer. Keep an id field on both, or supply your own Correlation.

Because invocation goes through the space, a timeout means "nobody produced a correlated result in time". The input entry is still in the space under its lease, and a worker that shows up late will still do the work.

Deployment keeps itself current. With agentspaces.embabel.auto-deploy on (the default), a deployer watches the bridge's registry on a virtual thread. It redeploys a freshly generated agent whenever the set of actions changes:

  • the first time cards arrive,
  • when a new card brings a new capability,
  • when an expired card takes one away.

A card refresh that changes nothing but the issue time does not redeploy.

A vanished action leaves after a grace. An action whose card disappears stays for absence-grace-millis (30 s), so a late refresh does not flap the planner, and is then absent from the next generated agent. When every action has lapsed, a vacant generation replaces the last one. Each deploy is read back: if the platform kept more than one generation under the bridge's name, the deployer logs an ERROR and the earlier generations stay reachable until the platform restarts. Invoking a vanished action times out and throws, which the planner treats as the action failing.

The appendix explains why the bridge generates a class and why old generations stay registered.

Sizing the timeoutA generated action that gets no correlated result within remote-action-timeout-millis throws, which the planner treats as the action failing. Set it above your workers' realistic completion time rather than to your patience.

Set up the planner boundary deliberatelyEmbabelAgentSpacesAutoConfiguration

This section covers the dependency to add and the rules for what crosses between Embabel and the fleet.

Add ai.badmonkey.agentspaces:embabel-agentspaces:0.7.0 (a module of the core repository) alongside the AgentSpaces starter and your Embabel application dependencies. The extension reads Embabel annotations reflectively. It does not install an Embabel platform. Automatic deployment requires the application's AgentPlatform bean.

Describing work and doing work are separate

The metadata path and the execution path have different jobs:

  • Metadata. @Agent, @Action, and @AchievesGoal describe capabilities. They do not start workers that take from a space.
  • Execution. Add a one-argument @SpaceTake or @SpaceNotify method.
  • No context argument. An Embabel action taking OperationContext as a second argument cannot also be a bound space method. Move the reusable work behind an injected service and expose a single-domain-argument adapter.

Use domain types at the boundary

Use records or domain classes at the fleet boundary. Embabel metadata excludes these from domain schemas:

  • infrastructure parameters in com.embabel.*,
  • primitives,
  • String.

A multi-input planner action may describe several domain types, but the remote bridge generates one-input actions. Adapt such work to one request record. Do not expect it to ship an Embabel execution context.

Groups and cards

  • Outbound cards publish into every configured group.
  • One card per bean. The core binder makes the one card. A bean with @AgentSpec or its @SpaceAgent stereotype uses that annotation's name; any other @Agent bean is named by @Agent(name).
  • The default inbound bridge uses the first configured group, unless agentspaces.embabel.groups names others, and excludes this peer's cards. Local actions remain the local planner's responsibility.
  • Another group or custom routing. Replace the EmbabelRemoteActions bean.
// Application configuration; ResearchTask and Finding are shared domain types.
@Bean
EmbabelRemoteActions researchFleetBridge(AgentSpaces spaces, PeerIdentity identity) {
    RemoteActions remote = RemoteActions.over(
            spaces.group("research-fleet"), identity.peerId())
        .route(ResearchTask.class, "tasks")
        .resultsIn(Finding.class, "findings");
    return new EmbabelRemoteActions(remote, Duration.ofSeconds(60),
            "researchFleet", "Remote research specialists");
}

Declare both spaces in that group on the caller and on the workers. Two properties control the bridge:

  • agentspaces.embabel.auto-deploy=false switches to manual deployment through bridge.deployTo(platform).
  • remote-actions-enabled=false disables the default inbound bridge, while outbound card publication remains available. This lets a worker-only application advertise capabilities without importing the fleet into a planner.

The second generation: one card, implied takes, workers inside EmbabelAgentBinderRemoteActionAgentDeclarationReaderTakeInvokerEmbabelDeclarationReader

0.7.0 ships the bridge's second generation. Your Embabel code does not change. What changes is how the bridge reads it and how a planner calls the fleet.

One card per bean

  • The core binder makes the card. It reads an Embabel bean through the AgentDeclarationReader SPI, which embabel-agentspaces ships as EmbabelDeclarationReader. The card is named by @Agent(name) and carries framework=embabel.
  • EmbabelBinder is deprecated, for removal. Bind the bean through AgentSpaces.bind(bean). The starter does so for every @Agent bean.
  • Names are unique per class. A different class bound under a name already bound refuses at startup. A second instance of the same class may bind.
  • agentspaces.embabel.card-name is agent (the card is named by @Agent(name)) or class (by the class, as before).

Actions the binder serves for you

  • An implied take. An @Action with no space annotation that takes one entry and returns one gets a take of its own, on the group's sole space or action-space, under action-lease (PT1M). Turn this off with serve-actions: false.
  • An action the binder cannot serve is advertised by advertise-unserved: local (the default; listed, never invocable), invocable, or omit.
  • Several loops per method. @SpaceTake(concurrency = n) runs n take loops for one method, so slow work serves n entries at once.

Workers that run inside Embabel

  • A worker may take more than the entry. A claimed @SpaceTake method may take parameters after the entry, such as an Embabel context. The core TakeInvoker SPI runs such a method.
  • EmbabelTakeInvoker runs each taken entry as an Embabel process on the bean's own agent, aimed at one goal, the method's return type. It renews the take lease meanwhile, stops a run past served-max-run (PT10M), and completes with no result when no plan is found.
  • take-mode is auto (methods with a parameter after the entry run inside Embabel), platform, or direct.

Calling the fleet from the planner

  • Fire once. Generated actions carry Embabel's fire-once retry policy (remote-action-retry). A second call for one input inside one process waits for the same result.
  • A timed-out input is withdrawn unless a worker already holds it (on-timeout: withdraw, or leave). In code: RemoteAction.invoke(input, timeout, RemoteAction.OnTimeout.WITHDRAW). The planner sees a RemoteActionTimeoutException.
  • The contract comes along. A generated action carries the card's description, a cost from 0 to 1 (remote-action-default-cost, 0.5, when the card names none), and its pre terms. It carries post too under carry-conditions: pre-post.
  • Groups. agentspaces.embabel.groups lists the groups the bridge spans: empty for the first configured group, * for all. Each capability becomes one planner action, however many peers offer it, under a stable name.
  • The result space. A worker whose result space differs from its take space says so on its card, and RemoteActions waits there after an explicit resultsIn.
property (agentspaces.embabel.)defaultmeaning
groups[] (first group)the groups the bridge spans; * for every group
card-nameagentagent names the card by @Agent(name); class by the class
serve-actions, action-space, action-leasetrue / "" / PT1Mimplied takes for one-in, one-out actions, their space (empty: the group's sole space), and their lease
advertise-unservedlocallocal, invocable, or omit: what an action the binder cannot serve becomes
remote-action-retryfire-oncefire-once or default: the generated actions' retry policy
on-timeoutwithdrawwithdraw or leave: the input entry after a timeout
remote-action-default-cost0.5the cost a generated action carries when its card names none, 0 to 1
carry-conditionsprenone, pre, or pre-post: which contract terms the generated actions carry
deploy-debounce-millis, deploy-min-interval-millis, absence-grace-millis250 / 5000 / 30000quiet time before a changed action set deploys, the least time between two generations, and how long a vanished action stays
take-mode, served-max-runauto / PT10Mauto, direct, or platform: how a worker action runs; the longest a platform-served task may run

The Embabel guide walks through the bridge with a running example.

The remote action contract: shared by Embabel and Spring AICorrelation

These rules apply whenever an Embabel planner action or a Spring AI tool calls work through a card.

A card advertises a capability. It is not a private endpoint. A tool or planner action named after an agent writes a typed entry that any eligible worker may serve. Use a distinct request type or space admission when work must be restricted. Selecting a card by name alone does not pin the executor.

ContractImplementation behavior
Type visibilityThe caller must have compatible input and output classes on its classpath. Unresolvable schemas are omitted. Declared ballots and decision reactions are not invocable remote actions; legacy cards without action metadata use consumed/produced pairings.
Task routingExplicit route(type, space), then the declared action’s space, then the card’s type binding, then the sole local space. Multiple spaces with no applicable route omit the action.
Result routingDefaults to the task space. If the worker sets resultSpace, configure resultsIn(outputType, space) on the caller; the result route is not inferred from that annotation over the wire.
CorrelationDefault Correlation.sharedFields() compares every shared record component. No shared fields means any candidate matches. Share a unique request id and preserve it in the result; do not correlate concurrent requests by a topic alone.
TimeoutThe wait ends, but the written task retains its own lease (default ten minutes in RemoteActions). A timeout does not cancel it. Retry with an application idempotency policy.
TrustDescriptions become planner/model input. Card filtering controls what is offered; space admission controls who can act. An attested card alone does not turn tuple-space invocation into addressed execution.
// Put these public records in a shared domain artifact (one source file each).
public record ResearchTask(String requestId, String topic) {}
public record Finding(String requestId, String summary) {}

// Both sides preserve requestId. Only that component is shared here.
// For non-record types or a different correlation rule:
remote.correlation((request, result) ->
        ((ResearchTask) request).requestId().equals(((Finding) result).requestId()));
Caller subscribes for results, writes a leased task, worker claims it and completes with a result, and caller correlates the response. Worker crash allows reassignment after expiry; caller timeout does not cancel the task.
Invocation. Both adapters use this space round-trip. This diagram shows a same-space result; a cross-space result requires a separate write and explicit caller routing.

Data in a fleet: realms and the two worlds

The sections above move work between an Embabel planner and the fleet. This section is about the data that work is about: where its types come from, where it lives, and how agents share values that change.

The domain often comes as an Embabel realm, a package of meaning. The AgentSpaces + Realm site reads its parts this way:

  • types: the domain objects, with identity keys, typed fields, parent types, and references to other types;
  • producers: how the realm obtains each object, through an API operation, a SQL query, or another kind, such as a computation or a vector search;
  • APIs: the remote operations the producers call, each with its OpenAPI 3.x document;
  • apps: pages over the objects, which a world that installs the realm serves at /apps/<realm>/<name>.html;
  • prompts: each agent's prompt file, and examples for a world's chat.

The two worlds

A realm and a group answer different questions:

  • A realm answers what are the objects, and where do they come from. It knows nothing of peers, leases, takes, or who is on duty.
  • A group answers who works on the objects, and how: its spaces, its cards, its flows, and its rules. It knows nothing of a producer's SQL or an API's token until a configuration tells one of its agents.

An import joins the two. It reads the realm, drafts what the group will need, and carries what a person approves into the group. Data moves one way, from the realm into the group, and nothing writes back into the realm. AgentSpaces itself reads no realm: the group receives ordinary entry types and cards.

WHERE THE TYPES COME FROM: A REALM, CARRIED INTO A GROUP ONE WAYan Embabel realm: what the objects arean AgentSpaces group: who works on themtypes/the domain objectsproducers/how each object is obtainedapis/the remote operationsapps/pages over the objectsentry typesnamed by namespace + type (an IRI)AssetCardsa connector serves each producerflow manifestsa stage per API operationAppCardsorigin: the realman importdrafts; a person approvesthe realmapprovedrealm to group, never back; AgentSpaces itself reads no realmWHERE THE DATA LIVES: FOUR WAYS AGENTS SHARE ITentrieswork and results, leasedthe shared blackboardassetsdata stays at its sourcea connector answers queriesartifactsinputs and outputs over 4 MiBpieces from every holderpersistent valuesshared state that changesa change ships its deltaA realm import writes entry types, asset cards, flows, and app cards. Persistent values are a pattern you add:the import writes none.
Data in a fleet. A realm says what the objects are and where they come from; a group says who works on them and how. An import carries what a person approves one way, from the realm into the group. Agents then share the data as entries in a space, as assets a connector serves from the source, as content-swarm artifacts, and as persistent values on a ref.
Realm partWhat reaches the groupRead
typesentry types named by the realm's namespace and the type name, an IRI such as https://example.org/claims#Claimthe schema registry
producers of kind remote, api, or sqlan AssetCard per operation or query, published by a connector that serves it from the sourcethe connector SDK
producers of any other kindthe AgentCards of a fleet package that serves the agent kind <realm>/<producer>cards
APIsa flow manifest with one stage per operation, on a lane named after the APIflow manifests
appsan AppCard whose origin names the realm, which members find by discoveryan app card from a realm
promptsthe group's prompt set, carried as a configurationthe mapping

Where the data lives

Embabel keeps its blackboard in one JVM. An AgentSpace is the same idea spread across the fleet: a shared, leased blackboard that every member of the group replicates. Once a realm's types are entry types, the planner and the fleet's workers share data in four ways. Choose by size and by how often the data changes:

  • Entries in a space hold work items and results: small, typed, signed, and leased. A planner's remote actions write their inputs and read their results here (the Space API).
  • Assets keep data at its source. A connector publishes an AssetCard and answers queries for it, so an agent queries the database or the API where it lives, and the client pulls each result once (the connector SDK, assets in Micronaut).
  • Artifacts of the content swarm carry large inputs and outputs. With agentspaces.content.enabled=true, a @SpaceTake input or a remote action's result above agentspaces.content.escalate-above (4 MiB) travels as an artifact and arrives whole on the planner's side. Nothing in the Embabel extension changes for it (the content swarm, large entries).
  • Persistent values hold shared state that changes: a map, a vector, a text, or a DataScript database behind a named ref. Every member reads the same value, and a change ships only the nodes a reader lacks (values that change, a database on a ref).

A realm import writes entry types, asset cards, flows, and app cards. It writes no persistent values. Keeping a realm's reference data on a ref, such as a catalogue every agent reads, is a pattern you build with the sections linked above.

The realm site's mapping page says how an import runs, and its worked example walks one realm from its import document to the cards a group serves. The appendix explains why data moves one way, and why a realm names no spaces.

aspace://guide/spring-ai · chapter 7

Spring AI integration

Spring AI gives an application a portable way to call models. agentspaces-springai lets those models and their tools work with the fleet, so your agents coordinate across machines while the application stays ordinary Spring AI code. The fleet gives a set of processes a shared space whose entries are leased, signed, and copied to every peer.

It is a separate library, in its own repository at github.com/badmonkeyai/agentspaces-springai, built on the published AgentSpaces artifacts. It plugs the fleet into Spring AI's own extension points:

  • tools and advisors,
  • chat memory,
  • ChatModel and EmbeddingModel,
  • observations, and MCP.

It needs no Embabel. The Embabel extension integrates at the level of a planned agent and its actions. This one integrates at the level of a model call and its tools. An application can use either or both.

It needs these beside it:

<!-- pom.xml: beside agentspaces-spring-boot-starter and a Spring AI model starter -->
<dependency>
  <groupId>ai.badmonkey.agentspaces</groupId>
  <artifactId>agentspaces-springai</artifactId>
  <version>0.7.0</version>
</dependency>
// build.gradle.kts; the Groovy form is implementation '...' without the parentheses
dependencies {
    implementation(platform("ai.badmonkey.agentspaces:agentspaces-dependencies:0.7.0"))
    implementation("ai.badmonkey.agentspaces:agentspaces-springai:0.7.0")
    implementation("ai.badmonkey.agentspaces:agentspaces-spring-boot-starter")
}

The library is on Maven Central with the core. It releases from its own repository on its own cadence, so it carries its version explicitly. The BOM of the quick start manages the starter's version.

The library has nine feature families, configured under agentspaces.springai. Fleet tools and the take-lease advisor are on by default. Everything that widens what a model can reach, or sends prompts across the fleet, is off until you turn it on.

  • Switches. Most families use an enabled switch. Discovery tools and capability tools have individual switches, and embeddings use embedder.type.
  • Spaces. Declare the spaces a feature uses under agentspaces.groups[].spaces like any other. A missing one fails at startup with the YAML that adds it.

Because you declare it, the space has the group's admission, encryption, and block exchange from the start.

featurebeanswhat it gives an application
Fleet toolsFleetToolsthe fleet's AgentCards as Spring AI tool callbacks; each request sees the live set
Discovery and data toolsFleetDiscoveryToolsfind_fleet_agents, list_fleet_assets, fetch_fleet_data, each enabled separately
Capability toolsFleetCapabilityToolspropose_vote, cast_ballot, read_tally, read_decision, contribute, and read_estimate over the group's vote and aggregate capabilities, each family enabled separately
Crash-safe workersTakeLeaseAdvisor, SpaceChatMemoryRepositorya take lease renewed on every model round-trip, and chat memory in a replicated space
Model serviceFleetChatModel, ModelServera ChatModel whose provider is the fleet: crash tolerance, routing by model or price, streaming
EmbeddingsSpringAiEmbeddersemantic discovery ranks with the application's EmbeddingModel
Fleet-wide usageFleetUsage, UsagePaneltoken usage from Spring AI's observations as per-peer totals and audit entries in a metrics space, and a console panel
MCP exportFleetMcpToolSyncnamed fleet agents published through Spring AI's MCP server, kept in step with list_changed
PatternsVectorStoreAssetProvider; the patterns modulea VectorStore as a fleet data asset; judges, token-priced auctions, extraction ensembles on the annotations

Workers: a ChatClient inside a takeTakeLeaseAdvisor

To run a worker that calls a model, write a @SpaceAgent bean with an injected ChatClient.Builder and a @SpaceTake method, exactly as @SpaceTake describes it. The space distributes the work, and the model does it.

What the library adds is the lease handling an agentic loop needs. TakeLeaseAdvisor runs inside Spring AI's tool loop, after the ToolCallingAdvisor. It renews the in-flight take lease once per model round-trip, and on an interval while a streamed round-trip runs.

  • A worker making progress keeps its claim, however long its loop takes.
  • A worker process that crashes stops renewing, and its task reappears when the take lease expires.
  • Leases can therefore be short, which makes recovery fast.
// agentspaces-springai/examples/springai-fleet (example 15): one of two workers
@SpaceAgent(name = "summarizer", description = "Summarizes a topic into a short briefing")
public class Summarizer {
    private final ChatClient chat;

    Summarizer(ChatClient.Builder builder) { this.chat = builder.build(); }

    @SpaceTake(space = "work", lease = "2m")      // renewed on every model round-trip
    public Summary summarize(Brief brief) {
        return new Summary(brief.topic(),
                chat.prompt().user("Summarize: " + brief.topic()).call().content());
    }
}

With memory.enabled, the worker's conversation lives in a replicated space too.

  • SpaceChatMemoryRepository is a Spring AI ChatMemoryRepository. It writes each save as the conversation's next leased snapshot and retires the older ones. An abandoned conversation leaves the space on its own, and a snapshot over 64 KiB travels content-addressed.
  • FleetChatMemoryAdvisor keys the conversation by the in-flight take's entry id by default (conversation-id: take; agent and explicit are the alternatives). A task that reappears after a crash resumes on another peer with the conversation it had.
# application.yml, every worker
agentspaces:
  groups:
    - name: springai-fleet
      founding: springai-fleet-example-v1
      spaces:
        - { name: work }
        - { name: conversations }        # the memory space; missing => fails at startup
  springai:
    memory:
      enabled: true
      conversation-id: take              # one conversation per task entry
Where it livesIn ordinary agent beans. Both advisors are added to every auto-configured ChatClient.Builder through Spring AI's ChatClientBuilderCustomizer. A bean that injects the builder gets them without naming them.

The lease advisor does nothing when no take is in flight, which is why it is safe on every client. A ChatClient you construct some other way takes the advisor beans explicitly.

Keep in mindMake tool side effects idempotent, or key them on the take's entry id. Spring AI does not store tool-call intermediate messages in chat memory. A resumed conversation replays the user and assistant turns, and tools run again if the model asks for them.

Progress renews the lease, and time alone does not. A model call that blocks longer than lease with no round-trip completing lets the task reappear. Size the lease to the slowest single round-trip you expect. The whole job may take longer.

Fleet tools: cards as tool callbacksFleetToolsFleetDiscoveryTools

Use fleet tools to let a model call the fleet's agents as Spring AI tools. Every AgentCard in the group declares the actions its bound methods consume and produce (the binder). FleetTools turns each action into a Spring AI ToolCallback:

  • Input schema: the action's consumed type.
  • Description: the method's description.
  • Name: the prefix, the agent, and the input type (fleet_summarizer_Brief).

Calling the tool writes the input as a leased task entry and awaits the correlated result. The remote-actions bridge of the Embabel chapter performs the same round trip. The provider resolves the set for each request, with a snapshot cache (default tools.cache-ttl=1s). Arrivals and expiries become visible after that cache refresh, and a FleetToolsChangedEvent announces each change.

// agentspaces-springai/examples/springai-fleet -- SpringAiFleet.Orchestrator, trimmed
public class Orchestrator {
    private final ChatClient chat;

    Orchestrator(ChatClient.Builder builder, FleetTools fleet) {
        this.chat = builder.defaultTools(fleet.toolCallbacks()).build();
    }

    public String ask(String question) {        // the model calls agents on other peers from its own tool loop
        return chat.prompt().user(question).call().content();
    }
}

// Three Spring Boot applications: two list the first one's address as a seed,
// and no application names another. The workers' cards are the tool catalog.
String answer = orchestrator.ask("Brief me on tuple spaces, in French too");

Which cards become tools is a deployment decision. Choose with any of these:

  • include-agents and exclude-agents lists;
  • require-attested, to admit only agents signing with a certified key of their own (agent certificates);
  • a FleetToolFilter bean for a rule of your own.

ToolNamingStrategy is the other replaceable default. A tool call waits tools.timeout for its result. On expiry it returns an explanation to the model (on-timeout: result) or throws (throw).

Three more tools let the model look around without acting. FleetDiscoveryTools offers find_fleet_agents, list_fleet_assets, and fetch_fleet_data over the discovery and connector layers of discovery and the connector SDK. Each is switched on separately because each widens what the model can reach.

To share a knowledge base, set vector-store.enabled. It serves the application's own Spring AI VectorStore as a fleet data asset through the connector SDK. Any agent in the fleet then queries the shared knowledge base with leased, pull-once results. An identical question inside the freshness window reads the answer from the space instead of searching again.

Where it livesFleetTools, FleetDiscoveryTools, and FleetCapabilityTools are plain beans. Attach them to a ChatClient yourself, through toolCallbacks().

They are deliberately not ToolCallbackProvider beans. Spring AI's MCP server auto-configuration publishes every ToolCallbackProvider in the context to outside MCP clients. The fleet crosses that boundary only through the MCP export below, which exposes nothing until named.

Keep in mindA tool routes by entry type. The tool writes its input as a task, and whichever agent takes that type does the work. The card names one agent that does, and the description says so, but that does not pin the work to that agent.

To keep an agent's work private, do one of these:

  • Give it a request type of its own.
  • Restrict who may take from the space with admission: authorizer and the space-take grant (space admission).

Tool descriptions are model input. Filter which cards become tools before you trust what they say.

Model access as a fleet serviceFleetChatModelModelServer

To let peers without API keys call a model, use the fleet model service. FleetChatModel is a Spring AI ChatModel whose provider is the fleet. The caller needs no API key and no provider dependency.

Each round-trip works like this:

  • The round-trip becomes a ModelRequest entry in the model space.
  • A ModelServer on a peer that holds the credentials takes it, stamps the attempt, and calls its provider.
  • The server completes the take with the response, so the answer and the request's removal land together.

The service also covers crashes, routing, and streaming:

  • Crashes. A server that dies mid-call lets its lease lapse, and another serves the request with the next attempt number. The response metadata carries agentspaces.servedBy and agentspaces.attempt.
  • Routing. Requests route by model name, or by price when the model space runs AUCTION and each server bids its prices.<model>.
  • Streaming. A streamed request writes the provider's deltas as short-leased chunk entries, assembled in order on the caller. Cancelling the Flux writes a ModelCancel that stops the server.
  • Restarts. stream.on-restart says whether a stream whose server died fails or restarts on another.
# a server peer: holds the provider credentials, serves named models
agentspaces:
  groups:
    - name: research-fleet
      spaces:
        - { name: model-requests, admission: authorizer }   # prompts cross the fleet here; add strategy: AUCTION for price routing
  springai:
    model-server:
      enabled: true
      models: [gpt-4.1-mini, gpt-4.1]       # required: an enabled server with no models fails at startup
      routing: model                       # or price, which needs the space on strategy: AUCTION
      concurrency: 4

# a calling peer: no provider on the classpath, no key anywhere
agentspaces:
  springai:
    model-client:
      enabled: true
      model: gpt-4.1-mini
      stream: { on-restart: restart }

A server never executes anything on a caller's behalf. Tool calls come back in the assistant message, and the caller's own ToolCallingAdvisor runs them, with the caller's own tools. Media travels content-addressed over the group's block exchange, like any entry over the inline limit.

Four interfaces, with one default bean each, cover what a deployment might want to change:

  • ModelCatalog: which models this server offers.
  • ModelRequestRouter: by model or by price, or by tenant, region, or load.
  • StreamChunkingPolicy: latency against entry count.
  • StreamRestartPolicy.

The appendix explains how the model service relies on Spring AI 2.0's split between the model and the tool loop.

Where it livesFleetChatModel is a @Fallback bean. On a node with no provider it is the ChatModel Spring AI's ChatClient uses, so application code is unchanged. Beside a provider, injection by type resolves to the provider, and injection by name resolves to the fleet model.

ModelServer is a SmartLifecycle bean on the peers that hold keys, and only those peers ever see a credential.

Keep in mindOnly trusted servers answer. FleetChatModel accepts a response or chunk only from an issuer the authorizer permits MODEL_SERVE for the model. Grant it with agentspaces.security.grants.model-serve under the membership profiles, or the aspace:model-serve[:<model>] scope under the OIDC profiles (profiles and authorization).

Anyone admitted to the model space can read the prompts in it. Give that space its own admission and the group a content key (content encryption).

A blocking call's response also reports its attempt. A caller that must not pay twice for a retried request can see that it was retried.

Embeddings, usage, and MCP exportSpringAiEmbedderFleetUsage

This section covers three optional features: better ranking for semantic discovery, fleet-wide token usage, and publishing fleet tools to MCP clients.

Embeddings

Semantic discovery (capability services) ranks with a pluggable Embedder, and the shipped one is lexical. Set embedder.type: spring-ai to replace it with SpringAiEmbedder over the application's EmbeddingModel.

  • Cached. Vectors are L2-normalized and cached by the text's content hash, so a card is embedded once.
  • Matched. The embedder's identity (spring-ai:<model>) is advertised on the capability. Peers query only peers that rank alike, so a fleet never averages two models' notions of similarity.

Usage

With usage.enabled, FleetUsageObservationHandler reads token counts from Spring AI's gen_ai observations and hands them to a UsageSink. The default sink, FleetUsage, keeps this peer's counts per model and per agent.

For totals across the fleet, name a space in usage.metrics-space. The sink then also writes there:

  • Each call as a leased ModelUsage entry, for audit.
  • This peer's running total per model as a ModelUsageTotal, on every publish-interval, under a lease of three intervals (ten seconds at least).

Any peer then reads fleetTotal(model), the sum of the newest total from each peer, with no collector. Without a metrics space the sink keeps local counts only, and fleetTotal is empty.

UsagePanel puts the figures on the fleet console (the fleet console). Replace the sink to export to a billing or FinOps system.

MCP export

MCP clients such as Claude Desktop or an IDE agent sit outside the fleet's trust boundary. Nothing is exposed until mcp.include-agents names the agents that may be. Export also needs:

  • the FleetTools bean (tools.enabled, the default);
  • a synchronous MCP server bean (McpSyncServer).

FleetMcpToolSync then publishes those agents' tools through Spring AI's MCP server. On every FleetToolsChangedEvent it adds and removes tools and sends notifications/tools/list_changed, so connected clients refresh as cards arrive and lapse.

mcp.discovery-tools exports the three discovery tools too, and mcp.capability-tools exports the enabled capability tools.

agentspaces:
  springai:
    embedder: { type: spring-ai, model: text-embedding-3-small }
    usage:    { enabled: true, metrics-space: metrics }   # declare a "metrics" space in the group
    mcp:      { enabled: true, include-agents: [summarizer, translator] }   # needs tools.enabled (default) and a sync MCP server bean

Patterns on the annotations

A model can take part in the fleet's coordination with nothing from this library: the annotations already do it. The patterns module shows three shapes. Each runs on its own small fleet over TCP with scripted models, so it runs offline.

  • Judges. A panel of @Ballot agents votes, each through Spring AI's FactCheckingEvaluator over the judge's own model. A lead's @OnDecision records the verdict when the quorum closes. Every ballot is a signed entry, so which judge, on which peer, voted how is auditable from the space.
  • Priced by tokens. Model workers on an AUCTION space bid with a @BidFunction: the model's price per thousand tokens times an estimate of the prompt. They bid infinity for tasks harder than the model handles well. Routine work goes to the cheap model and hard work to the premium one, with no router.
  • Extraction ensemble. Extractors on different models react to every document with @SpaceNotify and write a candidate carrying a confidence. Voters back the most confident with @Ballot, and a filer's @OnDecision files the winner with the tally as provenance.
// springai-patterns -- JudgePanel: the judge, and the lead
@Ballot(space = "votes", prefix = "claim:", lease = "10m")
public String judge(VoteCapability.Proposal proposal) {
    String[] parts = proposal.question().split(EVIDENCE, 2);
    boolean holds = evaluator.evaluate(new EvaluationRequest(
            List.of(new Document(parts.length > 1 ? parts[1] : "")), parts[0])).isPass();
    return holds ? "approve" : "reject";
}

@OnDecision(space = "votes", prefix = "claim:", resultLease = "1h")
public Verdict record(VoteCapability.Decision decision) {
    return new Verdict(decision.proposalId(), decision.winner(), decision.tally().toString());
}

// TokenPricedAuction: the cheapest capable model takes the task
@BidFunction(space = "model-tasks")
public double bid(ModelTask task) {
    if (task.difficulty() > maxDifficulty) {
        return Double.POSITIVE_INFINITY;
    }
    return pricePerThousandTokens * estimatedTokens(task.prompt()) / 1000.0;
}
Keep in mindWith a strict, a careful, and a lenient judge, a true claim passes three to nothing. A false one fails two to one, because the other two judges outvote the lenient one.

The agents that call a model (the judges, the priced model workers, the extractors) take a ChatClient, or an Evaluator built on one, by constructor. A real provider drops in with no other change. The leads, voters, and filers hold only a space handle.

PropertiesAgentSpacesSpringAiProperties

All under agentspaces.springai. group names the group the library works in (default: the first configured).

propertydefaultmeaning
tools.enabledtrueregister FleetTools
tools.prefix, .include-agents, .exclude-agents, .require-attestedfleet_, all, none, falsetool naming and which cards become tools
tools.timeout, tools.on-timeout30s, resulthow long a tool call waits for its result, and whether a timeout returns an explanation to the model or throws
tools.refresh-interval, tools.cache-ttl5s, 1schange-event cadence and snapshot caching
discovery-tools.agents, .assets, .datafalseenable find_fleet_agents, list_fleet_assets, fetch_fleet_data
discovery-tools.data-space, .timeout, .max-result-charsdata, 10s, 20000the data space, the query timeout, the result cap
take-lease.enabled, .stream-renew-intervaltrue, 30sthe lease advisor, and how often a streamed round-trip renews
memory.enabled, .space, .ttl, .conversation-id, .max-messagesfalse, conversations, 24h, take, 20chat memory in the space; take, agent, or explicit keys the conversation
model-client.enabled, .space, .model, .timeout, .stream.on-restartfalse, model-requests, server default, 120s, failthe calling side of the model service; restart emits a restart marker and begins the new attempt from its beginning
model-server.enabled, .space, .models, .routing, .prices.<model>false, model-requests, none, model, 1.0the serving side; models must name at least one model when enabled, or startup fails; price routing bids on an AUCTION space
model-server.lease, .chunk-interval, .chunk-max-deltas, .chunk-lease, .response-lease, .concurrency, .model-beans.<model>2m, 100ms, 32, 2m, 10m, 4, noneserver tuning; model-beans maps a model name to a ChatModel bean when several providers are present
embedder.type, .model, .require-match, .cache-sizehashing, class name, true, 4096spring-ai ranks semantic discovery with the application's EmbeddingModel; require-match queries only peers advertising the same embedder
usage.enabled, .metrics-space, .entry-lease, .publish-intervalfalse, none, 24h, 30sfleet-wide token usage; the metrics space holds the per-call audit entries and each peer's running totals, and the fleet total needs it
capability-tools.vote, .aggregate, .ballot-lease, .settle-timeoutfalse, false, 1h, 10sthe capability tools: vote enables propose_vote, cast_ballot, read_tally, and read_decision; aggregate enables contribute and read_estimate; the lease applies to the proposals and ballots the tools write, and read_estimate waits up to the settle timeout for an estimate
mcp.enabled, .include-agents, .discovery-tools, .capability-toolsfalse, none, false, falseMCP export of the named agents' tools, of the discovery tools, and of the enabled capability tools
vector-store.enabled, .space, .asset, .description, .freshnessfalse, data, knowledge-base, a generic description, 5mserve the application's VectorStore bean as a fleet data asset
Where to go nextExample 15 (examples/springai-fleet in the library's repository) runs the summarizer, a translator, and the orchestrator as three Spring Boot applications; examples/springai-patterns holds the three patterns above.

Spring AI 2.1 notes

The 0.7.0 line of agentspaces-springai builds on Spring AI 2.1.0-RC2 and Spring Boot 4.1. Four things differ from 2.0:

  • Attach fleet tools with defaultTools(...). ChatClient.Builder.defaultToolCallbacks(...) and ChatClientRequestSpec.toolCallbacks(...) are deprecated for removal in Spring AI 3.0. defaultTools(fleet.toolCallbacks()) takes the same provider and still reads it on every request.
  • Sampling options and Anthropic. The model server passes a caller's temperature, topP, and topK to the provider. Spring AI 2.1's Anthropic model drops all three and logs a WARN, because the Anthropic SDK 3.x rejects them. Other providers are unchanged.
  • Stream deltas. Providers now stream reasoning and partial tool-call parts. The model server does not forward a delta that has no text, no complete tool call, no media, and no finish reason, so callers see the same chunks as on 2.0.
  • Tool call limits. Every ChatClient stops a tool loop at 40 calls to one tool or 150 in total. Fleet tools count like any other tool. Raise the caps with spring.ai.tools.limits.*.

Deployment recipes: choose features per role

Start with the smallest role that does the job. Enable features on the peers that own them, and declare every feature space in the selected group. The integration does not need Embabel; an Embabel application can use these same workers or a Spring AI model service alongside its planner.

RoleEnable / attachSupply
LLM worker@SpaceTake + injected ChatClient.Builder; take-lease advisor defaults on. Optionally enable memory.A local provider model or enabled fleet model client; work space; conversation space if memory is enabled.
Tool orchestratorAttach fleet.toolCallbacks() to the client. Tools default on, but are not automatically attached.A model supporting the desired tool flow; shared domain types and routes to worker spaces. Keep the provider object so requests can refresh the tool set.
Model clientmodel-client.enabled=true; select a model by client default or request options.Model-request space and group access. No provider API key is needed on a caller that uses only the fleet model.
Model servermodel-server.enabled=true; configure model names and routing.Provider ChatModel beans and credentials; model-request space; MODEL_SERVE authorization. Map names with model-beans when several providers exist.
Retrieval servervector-store.enabled=true.An application VectorStore bean and data space; asset name, description, and freshness policy.
Retrieval callerEnable needed discovery-tools and attach discovery.toolCallbacks().Data space for fetches; a prompt or application flow that actually uses returned documents. Discovery embeddings rank advertisements, separately from the knowledge base’s vector search.
MCP edgemcp.enabled=true with explicit include-agents.A configured Spring AI MCP server. To export discovery tools, enable both the individual tools and mcp.discovery-tools.

Task memory with an explicit conversation outside a worker

Inside a take, the default conversation key follows the entry across workers. In a controller or scheduler there is no take context; take and agent modes cannot invent one. Pass an explicit conversation id, or provide a ConversationIdResolver bean keyed to your application’s session.

// With memory.enabled=true and its configured space declared:
String answer = chat.prompt()
    .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, conversationId))
    .user(question)
    .call().content();
Memory is a checkpointRecovery can use the latest available replicated snapshot; it does not resume a Java stack or guarantee that the last in-flight model/tool operation was saved. Serialize writes to the same conversation when turn order matters. Keep side-effecting tools idempotent and use separate conversation ids for independent sessions.

Size the three clocks independently

Three durations matter, and each needs its own value:

  • The task's write lease bounds how long uncompleted work remains useful.
  • Its take lease bounds how long another worker waits after a claim stops renewing.
  • The caller's timeout bounds how long it waits for an answer.

Set all three for the workflow. Do not copy one duration everywhere.

Know what the lease advisor covers:

  • Before each round-trip. TakeLeaseAdvisor renews before each synchronous model round-trip. A blocking call or tool operation that exceeds the lease can still lose its claim.
  • During streaming. The advisor schedules renewals until the stream terminates, even if no new token arrives. It does not detect a hung stream, so set provider and stream deadlines.
  • Renew interval. Keep take-lease.stream-renew-interval shorter than the take lease.
  • Manual clients. A manually constructed client must receive the advisors explicitly.

Model streaming has its own recovery rules:

  • fail, the default policy, raises FleetStreamRestartedException with partial text.
  • restart signals a new attempt and replays from its beginning. Downstream consumers must reset the partial answer. They must not append the new attempt as if it were a continuation.
  • Cancelling this model-client stream sends ModelCancel. A fleet tool timeout has no equivalent cancellation guarantee.

A shared retrieval role

# Merge with the peer identity, transport, and group configuration from the Spring Boot starter.
agentspaces:
  groups:
    - name: research-fleet
      founding: research-fleet-v1
      spaces:
        - { name: work }
        - { name: data }
  springai:
    group: research-fleet
    vector-store:                 # on the peer with the VectorStore bean
      enabled: true
      space: data
      asset: knowledge-base
      freshness: 5m
    discovery-tools:              # on a caller; colocated here for illustration
      assets: true
      data: true
      data-space: data
// Attach explicitly to a client used for retrieval.
ChatClient retrieval = builder
    .defaultTools(discovery.toolCallbacks())
    .build();

For model servers, protect model and conversation spaces with the group's admission and content-key policy. The caller verifies response and chunk issuers against MODEL_SERVE for the model. Use membership grants or the OIDC model-serve scopes for the selected security profile. Fleet tool filters and MCP allowlists add to these permissions. They do not replace them.

Replace policy through a beanFleetToolFilterModelRequestRouterUsageSink

To change a default policy, define an application bean of the interface. Auto-configuration then uses yours in place of its default.

InterfaceDefault policyUse an override for
FleetToolFilterInclude/exclude names or ids; optional attestation requirement.Application-specific trust and exposure policy.
ToolNamingStrategyPrefixed, sanitized, bounded, deduplicated names.A consistent tool namespace across deployments.
ConversationIdResolverTake, agent, or explicit conversation ids.Tenant/session keys outside take loops.
ModelCatalogConfigured model names backed by provider beans.A model registry or dynamic catalog.
ModelRequestRouterModel matching or price bids.Eligibility and routing by region, tenant, or load.
StreamChunkingPolicy100 ms or 32 deltas per chunk.Different latency and entry-volume tradeoffs.
StreamRestartPolicyFail or restart.Application-specific partial-answer recovery.
UsageSinkFleet counts and optional audit entries.A billing/telemetry export with its own retention and accounting semantics.

Auto-configuration backs off for these application beans. A custom RemoteActions bean also supplies explicit task routes, result routes, and correlation to Spring AI tools.

Fleet-wide usage totals need usage.metrics-space. Without it the default sink still keeps local counts. Each peer republishes its running total under a lease of three publish intervals (ten seconds at least), so a peer that stops publishing drops out of the fleet total. When exact billing matters, use retained, deduplicated audit records or a dedicated accounting sink.

Verify the behavior you rely on

The checked-in examples use scripted models and run without provider credentials. Use them to test coordination first, then add a live provider as a separate integration check. The Spring AI repository includes context tests for configuration and TCP flow tests for tools, crash recovery, streaming, routing, retrieval, usage, and MCP.

SymptomCheck first
No remote action/toolIs the card from another peer and still live? Do both domain classes resolve locally? Is the action invocable, routed to a registered space, and permitted by the tool filter?
Tool exists but times outConfirm a worker actually takes the input type, result routing matches resultSpace, and request/result correlation preserves the id. Increasing the timeout cannot fix a missing route.
Wrong or duplicate answerCheck shared-field correlation and reused business ids; then distinguish retried execution from a repeated notify/decision reaction. Card names do not pin workers.
Worker restarts without historyCheck memory enablement, space, snapshot lease, conversation id, and whether a snapshot had replicated before failure. Preserve take context across thread hops.
Request sits in model spaceCheck server lifecycle, served model names/provider mapping, matching conflict strategy for price routing, and model-serve authorization.
MCP tool missingCheck MCP server setup, export enablement, explicit agent allowlist, and tool refresh events. FleetTools itself is intentionally not an auto-exported provider bean.
Layer 4 binding failsRegister the concrete vote capability or ordered coordinator before enrollment; verify group/space names and the ordered holder’s signing identity.
Source-backed examples and checksThe examples and tests below show each behavior. Run the Spring AI example suite with mvn verify -Pexamples once the matching core artifacts are available.
  • Core: examples/example-05-quorum, example-08-intake-fleet, example-12-exactly-once-desk, and example-14-gossip-learning.
  • Embabel: EmbabelBinderTest, EmbabelRemoteActionsTest, and FleetPlannerEnablementTest (a minimal type-chaining planner), plus integration-tests/embabel-it/EmbabelFleetPlanningTest for the real Embabel platform.
  • Spring AI: examples/springai-fleet, examples/springai-patterns, CrashSafeWorkerFlowTest, ModelServiceCrashFlowTest, and FleetMcpExportFlowTest.
aspace://guide/micronaut · chapter 8

Micronaut integration

Micronaut is a JVM framework for microservices. agentspaces-micronaut does for a Micronaut microservice what the Spring Boot starter does for a Spring Boot application. It is a separate library, in its own repository at github.com/badmonkeyai/agentspaces-micronaut, built on the published AgentSpaces artifacts.

It also treats a service as both an agent and a data source. An AssetCard is the card that advertises a data asset, the way an AgentCard advertises an agent.

  • Its annotated beans publish AgentCards.
  • Its data and its HTTP presence publish AssetCards.
  • Other services resolve it through @Client, with the fleet as the registry.

It needs Micronaut 5.2, which runs on JDK 25. The library itself is Java 21 bytecode.

<!-- pom.xml -->
<dependency>
  <groupId>ai.badmonkey.agentspaces</groupId>
  <artifactId>agentspaces-micronaut</artifactId>
  <version>0.7.0</version>
</dependency>
// build.gradle.kts, under the Micronaut Gradle plugin; the Groovy form is implementation '...'
dependencies {
    implementation("ai.badmonkey.agentspaces:agentspaces-micronaut:0.7.0")
    annotationProcessor("ai.badmonkey.agentspaces:agentspaces-micronaut-processor:0.7.0")   // optional: compile-time enrollment and native-image hints
}

The library, its processor, and the LangChain4j and MCP bridges (agentspaces-micronaut-langchain4j, agentspaces-micronaut-mcp) are on Maven Central with the core and carry their version explicitly, since they release from their own repository.

Configure the peer (the library calls this the fabric) with the same agentspaces.* properties as the Spring Boot starter, with the same names and defaults. One YAML fragment configures a peer under either framework. The shared properties cover:

  • the security profile, transports, and TLS;
  • groups founded or joined, and spaces with admission;
  • content keys and capabilities;
  • the console and the A2A gateway.

Durations take ISO-8601 (PT5M) or the short form (5m, 250ms). What the library adds lives under agentspaces.micronaut.

featurebeanswhat it gives a microservice
FabricAgentSpacesFactory, FleetLifecycle, FleetContextthe peer, groups, spaces, and capabilities from agentspaces.*; the node loop, card refresh, and shutdown with the context
Agents@SpaceAgent, FleetEnrollerannotated beans found by stereotype at startup, bound, and published as AgentCards
Compile-time enrollmentagentspaces-micronaut-processorbeans with only method annotations enroll; native images keep the binder's reflection
AssetsAssetConnectors, ServiceAssetCardevery AssetProvider bean served through one connector runtime; the embedded server itself as an AssetCard
RegistryFleetDiscoveryClient@Client("orders") resolves to the peers whose AssetCards advertise orders
ManagementFleetHealthIndicator, FleetInfoSource, AgentSpacesEndpoint, FleetMeters/health, /info, /agentspaces, and Micrometer gauges
Console and A2AConsoleFactory, A2aFactorythe fleet console and the A2A gateway as Micronaut-managed servers

What you can build with it

A Micronaut service is a natural fleet member because it already has the three things a peer needs:

  • beans that do work,
  • data it owns,
  • an address other services call.

The library turns each into a card, and the cards are what the rest of the fleet, in any framework or language, sees. The shapes below compose. A real service is usually two or three of them at once.

shapewhat you addwhat the fleet gets
A service that is also an agent@SpaceAgent on a bean with @SpaceTake or @SpaceNotify methods; the controller delegates to itan AgentCard with one action per method: work arrives through the task space with leases, exactly-once takes, and crash recovery, and HTTP keeps working beside it
A data service as an assetan AssetProvider bean over the service's table, index, or APIan AssetCard any agent discovers by meaning and queries through the data space, with leased, pull-once results and the connector-serve grant deciding who may serve
Fleet-resolved HTTPservice-asset.enabled on the server, registry.enabled on the callers@Client("orders") load-balances across every peer whose card advertises orders, with no registry server and no URL configured anywhere
A keyless AI servicean @AiService and model-client.enabled; no provider module, no API keythe fleet's agents as the model's tools, and the model itself served by whichever peer holds credentials, with the take lease, memory, and usage handled
A model servera provider module with its key and model-server.enabledone place for credentials; every other peer calls the model through the space, Spring AI peers included
An MCP gatewaymicronaut-mcp's server and mcp.export.enabledthe fleet's agents as tools for Claude Desktop, an IDE agent, or any MCP client, kept in step with the cards and filtered at the fleet's edge
An MCP importermicronaut-mcp's client to an external server and mcp.import.enabledthe external server's tools as a fleet agent any peer invokes through the space, with one peer holding the connection
A mixed fleetMicronaut peers beside Spring Boot ones on the same agentspaces.* configurationone fleet: the same cards, the same spaces, the same model-service wire, workers and callers on either framework

Two things make these shapes cheap:

  • Shared configuration. The configuration is the starter's property set, byte for byte. A team that runs the Spring starter already knows how to configure a Micronaut peer, and a YAML fragment moves between the two.
  • Pay only for what you enable. Every feature is a bean behind a @Requires on its property, so a service enables the shapes it plays and pays for nothing else. A pure data service never starts the registry or the bridges, and a pure gateway never enrolls an agent.

Agents and enrollment

To make a bean a fleet agent, give it @SpaceAgent and the usual annotations. The annotations are unchanged. The library enrolls the bean at startup.

On StartupEvent the library finds every bean definition carrying @AgentSpec or @ProvidesCapability. @AgentSpec counts directly, or through a stereotype such as @SpaceAgent, which is a bean-defining annotation and an @AgentSpec at once. The library instantiates each bean and binds it through the facade:

  • worker loops start;
  • bids wire;
  • the AgentCard publishes into every joined group whose spaces satisfy the bean's annotations.

A bean naming a space no group registers fails at startup with the bean, the spaces, and the configured groups.

// agentspaces-micronaut/examples/micronaut-fleet (example 16): the orders service's agent
@SpaceAgent(name = "orders-service", description = "Prices customer orders")
public class Pricer {
    private final OrdersRepository orders;

    Pricer(OrdersRepository orders) { this.orders = orders; }

    @SpaceTake(space = "tasks", resultSpace = "findings", lease = "1m")
    public PricedOrder price(PriceRequest request) {
        Order order = orders.find(request.orderId()).orElseThrow();
        return new PricedOrder(order.id(), order.qty() * order.unitPrice(), "orders-service");
    }
}

@Controller("/orders")
@ExecuteOn(TaskExecutors.BLOCKING)
public class OrdersController {
    private final Pricer pricer;
    // ...
    @Post("/price")
    public PricedOrder price(@Body PriceRequest request) { return pricer.price(request); }
}

One implementation gets two front doors:

  • HTTP. HTTP clients POST to the controller.
  • The fleet. Fleet agents write a PriceRequest into the task space. The service's AgentCard lists price as an action any agent invokes through RemoteActions (remote actions), Spring AI tools included.

Keep the agent a plain bean. A Micronaut AOP interceptor binding (@Retryable, @Cacheable, @Transactional, a custom @Around) on the agent bean fails at startup saying so. Put such bindings on the controller that delegates to the agent. HTTP concerns like @ExecuteOn, which is not AOP, belong on that controller too.

A bean whose only fleet annotations are on methods, such as a plain @Singleton with a @SpaceNotify method, needs one of these to enroll:

  • compile the application with agentspaces-micronaut-processor on the annotation-processor path; Micronaut then hands every such method to the library before StartupEvent, and the bean is enrolled once;
  • or give the bean @SpaceAgent.

The appendix explains how enrollment finds beans, how the processor works, and why AOP hides the annotations.

Assets and the service card

To share a service's data with the fleet, write an AssetProvider bean. Every AssetProvider bean is served through the connector SDK (the connector SDK) on the data space. That is agentspaces.micronaut.assets.space (default data, registered under the group like any other).

The peer runs one connector runtime over all of its providers, because two runtimes on one space would race for the same query. With that runtime:

  • a query goes to the provider that described the asset;
  • cards publish and refresh on the card cadence;
  • the profile's authorizer is asked CONNECTOR_SERVE before anything is advertised.

TableAssetProvider serves an in-memory table. A provider over a Micronaut DataSource is the shape of a real connector.

The service card

With service-asset.enabled, the embedded server itself publishes an AssetCard once it has bound. The card carries:

  • asset micronaut.application.name;
  • the server's URI, or external-uri behind an ingress;
  • shape http and freshness live;
  • under access: the scheme, the instance id, and whether it answers queries.

service-asset.query: get with allowed-paths lets a fleet agent that has no network path to the service GET an allowed path through the space. The agent receives one row (status, content-type, body). This query is off by default, bounded by a timeout and a body cap, and authorized like every other connector query.

ServiceAssetCustomizer beans adjust the card. Give the service card and any table asset different names.

# application.yml of the orders service
micronaut:
  application: { name: orders }
agentspaces:
  bind: 127.0.0.1:7500
  groups:
    - name: order-fleet
      founding: order-fleet-v1
      spaces: [ { name: tasks }, { name: findings }, { name: data } ]
  micronaut:
    service-asset: { enabled: true }      # the service's HTTP presence as an AssetCard

The fleet as a service registry

Use the registry to call another service by name with @Client, with no URL configured anywhere. agentspaces.micronaut.registry.enabled adds a Micronaut DiscoveryClient over the group's ad-cache, the peer's store of signed advertisements, cards among them, received from the group.

  • Resolution. A service id resolves to every peer whose AssetCard advertises an http asset of that name, from issuers the authorizer permits CONNECTOR_SERVE.
  • Load balancing. Micronaut's composite discovery client includes it, so @Client("orders") load-balances across the peers that serve orders.
  • Expiry. A card that lapses (its TTL passes without a refresh) drops its instance.

Registration is the card itself, so there is nothing else to register.

// the analyst: resolved through the fleet
@Client("orders")
public interface OrdersClient {
    @Get("/orders/{id}")
    Order get(String id);
}
Keep in mindThe registry trusts a card only if the ad-cache accepted its signature and the authorizer permits its issuer to serve. Under the membership profiles that is every admitted member, unless agentspaces.security.grants.connector-serve narrows it. Under the OIDC profiles it is the aspace:connector-serve scope (profiles and authorization). Narrow it before you let @Client follow the fleet.

Management, console, A2A

Use these features to watch a peer from your operations tools, and to run the fleet console and the A2A gateway inside the service.

With micronaut-management on the classpath the peer reports itself:

  • Loop liveness. A liveness HealthIndicator named agentspaces-loop (/health/liveness) reports the node loop's health as its watchdog judges it: DOWN once the watchdog escalated, so a supervisor that probes liveness restarts the process, and UP for OK and DEGRADED, with the state and reasons in its details. It is the counterpart of the Spring starter's liveness (loop health).
  • Health. A readiness HealthIndicator named agentspaces. Its details are the fleet summary: peer, profile, groups with member counts and spaces, local and remote agent cards, asset cards, enrolled agents, the connector and its counters.
  • Info. An InfoSource under agentspaces.
  • Endpoint. The /agentspaces endpoint, sensitive by default, which adds every card the peer sees. It reads and never writes, since command-and-control is the console's job.
  • Metrics. With Micrometer, gauges agentspaces.members, agentspaces.cards.agents.local, agentspaces.cards.agents.remote, and agentspaces.cards.assets per group, and agentspaces.agents.enrolled.

Two servers can run inside the service:

  • Console. agentspaces.console.enabled serves the fleet console on agentspaces.console.port with the application's ConsoleViewCustomizer, ConsoleCommand, and ConsolePanel beans. The console serves on the loopback interface.
  • A2A. agentspaces.a2a.enabled serves the A2A gateway with agentspaces-a2a on the classpath. The gateway refuses to bind a routable address without a token or an OIDC gate.

Both are built by the Spring starter's own build methods and keep its rules.

Properties

The properties the Micronaut library adds are below. The shared agentspaces.* properties are those of the Spring Boot starter.

propertydefaultmeaning
agentspaces.enabledtrueswitch the whole integration off
agentspaces.micronaut.groupfirst groupthe group assets, the registry, and the views work in
agentspaces.micronaut.enroll.enabledtrueenroll annotated beans at startup
agentspaces.micronaut.assets.enabled / space / freshnesstrue / data / PT5Mserve AssetProvider beans on the data space
agentspaces.micronaut.service-asset.enabledfalsepublish the embedded server as an AssetCard
agentspaces.micronaut.service-asset.asset / external-uri / descriptionapplication name / server URI / generatedwhat the card says
agentspaces.micronaut.service-asset.query / allowed-paths / query-timeout / max-body-bytesnone / none / PT5S / 1 MiBget answers data queries for allowed paths
agentspaces.micronaut.registry.enabledfalseresolve @Client ids through fleet AssetCards
agentspaces.micronaut.management.enabledtruehealth, info, endpoint, meters (each also needs its module)
agentspaces.micronaut.tools.enabled / prefix / include-agents / exclude-agents / require-attested / timeout / on-timeout / refresh-interval / maxtrue / fleet_ / all / none / false / 30s / result / 5s / 64the fleet tool catalogue the LangChain4j and MCP bridges share

LangChain4j: three ways to use a model on the fleet

LangChain4j is a Java library for calling models and building AI services. agentspaces-micronaut-langchain4j plugs the fleet into LangChain4j's own extension points, the way the Spring AI library does for Spring AI. There are three ways to use it, one for each place a model can sit:

  • inside a worker,
  • inside an orchestrator,
  • on the fleet itself.

They combine. Example 17 (agentspaces-micronaut/examples/micronaut-ai-fleet) runs all three on three peers.

A worker with a model inside its take

The simplest use needs only the bridge's lease handling. A @SpaceAgent injects the peer's ChatModel (or an @AiService) and calls it inside @SpaceTake. The space distributes the work, the model does it, and the result completes the take.

The bridge's TakeLeaseListener is a ChatModelListener. It renews the in-flight take on every model request and response, and on an interval in between, so the lease can be short.

  • A worker making progress keeps its claim, however long its loop takes.
  • A worker that dies stops renewing, and its task reappears when the lease expires.

Which providers get the listener:

  • Listener beans reach OpenAI models automatically.
  • The bridge attaches them to Ollama and Anthropic builders.
  • Any other provider needs one BeanCreatedEventListener line on its builder.
// example 17: the summarizer runs on the peer that holds the key
@SpaceAgent(name = "summarizer", description = "Summarizes a topic into a short briefing")
public class Summarizer {
    private final ChatModel model;
    Summarizer(ChatModel model) { this.model = model; }

    @SpaceTake(space = "tasks", lease = "2m")      // renewed on every model round-trip
    public Summary summarize(Brief brief) {
        return new Summary(brief.topic(), model.chat("Summarize '" + brief.topic() + "' in " + brief.sentences() + " sentences."));
    }
}

With memory.enabled, the worker's conversation lives in a replicated space too.

  • SpaceChatMemoryStore keeps each conversation as its latest leased snapshot and retires the older ones.
  • FleetChatMemoryProvider keys it by the in-flight take by default (conversation-id: take; agent and explicit are the alternatives). A task that reappears after a crash resumes on another peer with the conversation it had.
  • Shared with Spring AI. The snapshot is the shared wire record, so a conversation a Spring AI worker started resumes on a Micronaut worker and vice versa.

A service picks the fleet memory with @AiService("fleet"), or every service gets it with memory.auto-apply: true.

An orchestrator whose tools are the fleet

An orchestrator is an ordinary @AiService, and the bridge gives it the fleet as its tools. FleetToolProvider is a LangChain4j ToolProvider. On every service invocation it returns the fleet's current foreign AgentCards as tools:

  • Name: fleet_<agent>_<InputType>.
  • Schema: a JSON schema from the input record.
  • Description: the card's description and goals.

The tool set is live by construction. A worker that joins is a tool on the next request, and one that leaves is gone when its card lapses. A tool call writes the input into the agent's take space and awaits the result there, so a worker invoked as a tool completes in its take space.

The bridge applies the provider to every @AiService as the service is built (tools.auto-apply, on by default). To choose per service, set it off and name FleetAiServiceCustomizer in @AiService(customizer = ...). @AgenticService agents receive the provider by themselves.

The appendix explains why the bridge applies the tool provider itself.

// example 17: nothing here is fleet-specific
@AiService
interface Orchestrator {
    @SystemMessage("You coordinate a fleet of specialist agents. Use the fleet tools, then answer with a short plan.")
    String plan(@UserMessage String request);
}
// the model sees fleet_summarizer_Brief and fleet_pricer_PriceRequest, calls them, and plans from the results

// an agentic workflow fans out across the fleet the same way
@AgenticService
interface OffsitePlanner {
    @SequenceAgent(outputKey = "plan", subAgents = { Researcher.class, Budgeter.class })
    String plan(@V("request") String request);
}

Which cards become tools is a deployment decision. Choose with any of these:

  • agentspaces.micronaut.tools.include-agents and exclude-agents;
  • require-attested, to admit only agents signing with a certified key of their own (agent certificates);
  • a FleetToolFilter bean for a rule of your own.

ToolNamingStrategy is the other replaceable default. A tool call waits tools.timeout for its result. Then it returns an explanation to the model (on-timeout: result) or an error (throw). For large fleets, tools.max caps the tools offered per request, most recently seen first.

Three more tools let the model look around without acting: find_fleet_agents, list_fleet_assets, and fetch_fleet_data (discovery-tools.agents, .assets, .data). They work over the discovery and connector layers of discovery and the connector SDK. Each is switched on separately because each widens what the model can reach.

Keep in mindA tool routes by entry type. The tool writes its input as a task, and whichever agent takes that type does the work. The card names one agent that does, and the description says so, but that does not pin the work to that agent.

To keep an agent's work private, do one of these:

  • Give it a request type of its own.
  • Restrict who may take from the space with admission: authorizer and the space-take grant (space admission).

Tool descriptions are model input. Filter which cards become tools before you trust what they say.

The fleet as the model

The third use removes credentials from most peers. One peer holds a provider key and serves the model, and the other peers call it through the space.

On the serving peer, set model-server.enabled. The peer serves its ChatModel beans to the fleet:

  • Which requests. It takes requests from the model space by the models it serves, or by price under AUCTION. Each bean's default model name names a model; models narrows the list, and model-beans maps a name to a bean.
  • While it runs. It renews the take lease while the provider runs, and streams in chunks.
  • Retries. A restarted request carries an attempt counter.

On a peer with no key, set model-client.enabled. That gives it FleetChatModel and FleetStreamingChatModel, which @AiService resolves without configuration when the peer has no provider module.

  • One round-trip is one request and one response through the space.
  • Tool calls return to the caller and run with the caller's own tools.
  • Trust. A response is trusted only from an issuer the authorizer permits MODEL_SERVE for the model.
  • Streams reorder chunks and fill gaps with a read-through. They follow a server's death by stream.on-restart: fail (the default) ends with FleetStreamRestartedException carrying the partial text, and restart replays the new attempt from its beginning.
# the worker peer: holds the key, serves the model
langchain4j:
  open-ai: { api-key: ${OPENAI_API_KEY}, chat-model: { model-name: gpt-4.1-mini } }
agentspaces:
  micronaut:
    langchain4j:
      model-server: { enabled: true }
      usage: { enabled: true }

# the orchestrator peer: no key, no provider module
agentspaces:
  micronaut:
    langchain4j:
      model-client: { enabled: true, model: gpt-4.1-mini }

The wire records are the Spring AI module's, in the shared agentspaces-model-wire artifact, and the space names an entry type by its class. So a Micronaut LangChain4j peer and a Spring Boot Spring AI peer serve each other's model calls on one fleet. A Micronaut orchestrator can run on a Spring peer's models, and a Spring worker on a Micronaut peer's.

  • Embeddings. embedder.type: langchain4j ranks semantic discovery with the peer's EmbeddingModel. Vectors are normalized and cached, and the identity langchain4j:<model> goes on the capability advertisement so peers rank alike.
  • Usage. usage.enabled records every response's token usage per model and agent. It sums usage across the fleet from each peer's running total in the metrics space (usage.metrics-space). It also adds a console panel that, on a mixed fleet, shows both frameworks' usage as one.

MCP: the fleet's edge, in both directions

MCP (the Model Context Protocol) gives a client a tool list and a transport. The fleet gives a set of processes a shared, leased, signed space. agentspaces-micronaut-mcp connects the two at the fleet's edge, and the two directions are two different services.

Export: a gateway peer for MCP clients

Use export to let Claude Desktop, an IDE agent, or any MCP client drive agents anywhere on the fleet, in any framework, through one endpoint. It works much as the A2A gateway serves A2A clients.

A gateway peer runs micronaut-mcp's server (micronaut.mcp.server.transport, STDIO or HTTP) and sets mcp.export.enabled. The bridge publishes the fleet's tools on that server, the same catalogue the LangChain4j provider uses. It keeps them in step with the cards: a tool is added when a card appears and removed when it lapses.

  • Over STDIO, the server notifies clients of changes when micronaut.mcp.server.tools.list-changed is on.
  • Over HTTP, micronaut-mcp 2.1 is stateless, and clients see the change on their next tools/list.

A call from the client writes the task into the fleet and returns the worker's result.

# a gateway peer, adapted from example 17; the example exports every agent,
# and this export names two
micronaut:
  server: { port: 8090 }
  mcp:
    server: { transport: HTTP, info: { name: ai-fleet, version: 0.4.0 } }
agentspaces:
  micronaut:
    mcp:
      export: { enabled: true, include-agents: [summarizer, pricer] }

# an MCP client's configuration, pointing at the gateway
{ "mcpServers": { "fleet": { "url": "http://gateway.example:8090/mcp" } } }

The export has its own include-agents and exclude-agents, separate from the in-process catalogue's. An MCP client sits outside the fleet's trust boundary, so a tool the orchestrator may call is not automatically one the outside world may. Authentication on the HTTP transport is Micronaut Security's, on the gateway's own routes.

The bridge also makes the server advertise the tools capability even when it has no tools of its own at startup. The appendix explains why the bridge sets this capability.

Import: an external server's tools as a fleet agent

Use import to bring an MCP server the fleet does not own into the fleet, such as a search service, a ticketing system, or a vendor's tools. Peers use it without each one needing a connection to it.

An importing peer configures micronaut-mcp's LangChain4j client (micronaut.mcp.client.*) and sets mcp.import.enabled. The bridge then publishes one AgentCard per client:

  • agent mcp-<name>;
  • one take action per tool, consuming McpToolCall(server, tool, argumentsJson, callId) and producing McpToolResult.

A worker loop takes calls for that server from the import space, runs them through the client, and completes the take with the result.

Every other peer (Spring, Micronaut, Python, or TypeScript) sees an ordinary agent and invokes it the ordinary way:

  • through RemoteActions;
  • as a LangChain4j or Spring AI tool;
  • by writing the entry.

Tools are re-listed on each card refresh, so a server that adds tools gains actions. A server that is not up at startup is retried.

# the importing peer
micronaut:
  mcp:
    client:
      transport: HTTP
      http:
        search: { url: https://mcp.example/mcp }
agentspaces:
  groups:
    - name: fleet
      spaces: [ { name: mcp-calls, admission: authorizer } ]
  micronaut:
    mcp:
      import: { enabled: true, servers: [search] }

// any peer: the external tool is a fleet action
RemoteAction search = RemoteActions.over(group, self).available().stream()
        .filter(a -> a.inputType() == McpToolCall.class).findFirst().orElseThrow();
McpToolResult hits = (McpToolResult) search.invoke(
        new McpToolCall("search", "web_search", "{\"query\":\"offsite venues\"}", "c1"), Duration.ofSeconds(30)).orElseThrow();
Keep in mindThe import peer executes whatever McpToolCall entries the import space admits, with its own credentials. Give that space admission: authorizer with the space-write grant, list the servers to import explicitly in production, and treat the external server's tool descriptions as untrusted input to the models that will read them.

Deployment recipes: choose features per role

Start with the smallest role that does the job. Enable features on the peers that own them, and declare every feature space under the group. The roles compose on one peer, and a fleet mixes them with Spring Boot peers configured the same way.

roleenablesupply
Agent service@SpaceAgent beans; the processor module for method-only beansthe spaces the annotations name; a plain bean for the agent, interceptor annotations on the controller that delegates to it
Data serviceAssetProvider beans (assets.enabled defaults on)the data space; the connector-serve grant on who may serve
Fleet-resolved serviceservice-asset.enabled on the server; registry.enabled on callersmicronaut.application.name, or service-asset.asset, as the service id; external-uri behind an ingress; a different name for any table asset
LLM worker@SpaceTake with an injected model; take lease defaults on; optionally memory.enableda provider module or model-client.enabled; the conversation space if memory is on
Orchestratoran @AiService; tools default on and auto-apply; discovery-tools.* as neededa model (local or the fleet's); shared entry types for the tools' inputs and outputs on the classpath
Model servermodel-server.enabledprovider beans and credentials; the model space; MODEL_SERVE authorization (grants.model-serve or the OIDC scope)
Model clientmodel-client.enabled with a modelthe model space; no key
MCP gatewaymicronaut-mcp server, mcp.export.enabled with explicit include-agentsMicronaut Security on the HTTP transport; tools.list-changed over STDIO
MCP importermicronaut-mcp client, mcp.import.enabled with explicit serversthe import space with admission: authorizer
Operator viewagentspaces.console.enabled; micronaut-management on the classpaththe console port; endpoints.agentspaces.sensitive and Micronaut Security for the management routes

Size the three clocks independently

Three durations matter, and each needs its own value:

  • A task's write lease bounds how long uncompleted work stays useful.
  • Its take lease bounds how long another worker waits after a claim stops renewing.
  • The caller's timeout (tools.timeout, model-client.timeout, a RemoteAction.invoke argument) bounds how long it waits for an answer.

Set the three for the workflow. Do not copy one duration everywhere.

TakeLeaseListener renews around each model round-trip, and on take-lease.stream-renew-interval while a streamed one runs. Keep that interval shorter than the take lease. Keep provider deadlines on the model calls themselves, since the listener is not a hung-call detector.

Replace policy through a bean

To change a default decision, define a bean of its interface, and the library uses yours. The library registers most defaults behind @Requires(missingBeans = ...) or as a @Secondary. The AiServiceCustomizer row is the exception: an application names it per service.

beandecidesdefault
Embedderhow semantic discovery ranksthe hashing embedder, or the LangChain4j one with embedder.type
InstantSourcethe fleet's clockthe system clock (TimeSource.system()); tests inject a VirtualTime or a TestClock
FleetToolFilter, ToolNamingStrategywhich cards become tools, and their namesthe include and exclude lists and require-attested; fleet_ prefix, sanitized to 64 characters
ServiceAssetCustomizerwhat the service's own AssetCard saysshape http, the server's URI, the instance id
AiServiceCustomizer (per service)what one @AiService receives, named in @AiService(customizer = ...)none registered: tools.auto-apply gives every service the fleet tools through a listener, and FleetAiServiceCustomizer opts one service in when it is off
ConversationIdResolverwhich conversation a model call belongs tothe in-flight take's entry id
ModelRequestRouter, StreamChunkingPolicy, StreamRestartPolicywhich requests a server takes and how it bids; when it flushes chunks; what a client does on a restartby model, or by price under AUCTION; 100 ms or 32 deltas; fail
ModelCatalogwhich model beans serve which namesevery ChatModel bean by its default model name
UsageSinkwhere usage records goFleetUsage: local totals and, with usage.metrics-space, each peer's running total and the per-call entry
ConsoleViewCustomizer, ConsolePanel, ConsoleCommandwhat the console shows and lets operators dothe generic view of every configured space
BeaconLocator (any number, ranked by @Order)an extra way to find a group, for every group or, through appliesTo, for onenone; the seeds and the agentspaces.bootstrap.* locators that the agentspaces-bootstrap-micronaut module's BootstrapFactory builds
DnsResolver, BootstrapChainFactoryhow the DNS locators resolve; how each group's chain is composedthe JDK's JNDI resolver; ChainComposer over the properties, or the core's plain chain when no bootstrap key is set
PeerNodeCustomizer, PeerNodeConfigurerthe node builder before build(); the built node before any group joinsnone

Verify the behavior you rely on

Write two kinds of test for your service, the way the library tests its own features:

  • A context test with ApplicationContext.run(Map) for the role it plays.
  • A two-context test for the path that crosses the fleet.

The appendix lists what the library's own tests prove. The symptoms below are the ones the library's own build met.

symptomcausefix
A bean carries fleet annotations and nothing enrolls it, silentlya plain @Singleton with only method annotations, and no processor moduleadd agentspaces-micronaut-processor to the annotation-processor path, or give the bean @SpaceAgent
Startup fails: "intercepted by Micronaut AOP"an interceptor binding (@Retryable, @Cacheable, @Transactional) on the agent bean hides its annotations from the bindermove the binding to the controller or service that delegates to the agent; @ExecuteOn is not AOP and is fine
A fleet tool times out though the worker ranthe worker completes into a resultSpace, while a remote action awaits in the take spacelet a worker invoked as a tool complete in its take space, or configure the route
An @AiService sees no fleet toolstools.auto-apply is off, or the service is built by handname FleetAiServiceCustomizer on the service, or call toolProvider(...) on the builder
Data queries reach the wrong providertwo assets share a name, the service card's includedgive the service card and any table asset different names
Fleet model calls are refused on the callerthe server's issuer is not permitted MODEL_SERVE for the modelagentspaces.security.grants.model-serve, or the aspace:model-serve[:<model>] scope
Adding a tool to the MCP server fails with "Server must be configured with tool capabilities"micronaut-mcp advertises the tools capability only when it has tools at build time, and the SDK refuses addTool without itthe bridge sets the capability when mcp.export.enabled is on; code adding tools by hand needs a BeanCreatedEventListener on ServerCapabilities.Builder calling tools(...)
The imported agent is named mcp-<uuid>a client built outside micronaut-mcp's factories, with LangChain4j's default keyset .key(name) on the client builder; the bridge does so for micronaut-mcp's clients
UnsupportedClassVersionError at startupMicronaut 5.2 is Java 25 bytecoderun on JDK 25; the AgentSpaces libraries are Java 21 bytecode and load there

How it is built

The library reuses the Spring starter's wiring without Spring. Most users need only these facts from it:

  • Replace any bean. Every bean yields to an application-supplied one of the same type.
  • Jackson. Micronaut 5 is on Jackson 3 and the core on Jackson 2.21.7. Both coexist, with jackson-annotations 2.22 for Micronaut.
  • Transports. Transport is TCP, TLS, and DTLS (the agentspaces.transport.dtls.* block works unchanged).
  • No QUIC. agentspaces-transport-quic pins Netty 4.1 and Micronaut manages 4.2, so QUIC is not available under Micronaut.

The appendix explains how the library reuses the Spring starter's wiring.

aspace://guide/langchain4j · chapter 9

LangChain4j on any host

Use agentspaces-langchain4j to put a LangChain4j application on the fleet from any JVM host, with no application framework on the classpath. The host can be a command-line agent, an embedded service, a batch job, or a service on a framework this guide has no chapter for. It gets the same fleet features Spring AI and Micronaut get.

It is a separate project, in its own repository at github.com/badmonkeyai/agentspaces-langchain4j, built on the published AgentSpaces artifacts. It has two artifacts:

  • agentspaces-runtime: a peer in plain Java from the same agentspaces.* configuration the starter reads, with the framework-neutral tool catalogue.
  • agentspaces-langchain4j: the fleet on LangChain4j's extension points.

The Micronaut bridge is wiring over them. It needs Java 21. LangChain4j 1.20 and 1.22 are both verified.

<!-- pom.xml -->
<dependency>
  <groupId>ai.badmonkey.agentspaces</groupId>
  <artifactId>agentspaces-langchain4j</artifactId>
  <version>0.7.0</version>
</dependency>

A peer from one file. PropertiesLoader reads the agentspaces section of a YAML document (or a nested map, or flat dotted keys) into the starter's properties. FleetRuntime builds the peer from them, with no Spring present: identity, node, transports by security profile, groups, spaces, capabilities.

  • Running. It then starts the node's loop, starts each FleetParticipant, and refreshes cards on the card cadence.
  • Stopping. close() stops it all in reverse.
  • Agents. bind(agent) binds the annotated objects.
  • Features. context(group) gives the FleetContext a feature works in.

The appendix explains how the runtime reuses the starter's build methods.

FleetRuntime runtime = FleetRuntime.start(PropertiesLoader.yaml(Path.of("agentspaces.yaml")));
runtime.bind(new Summarizer());                  // @AgentSpec and @SpaceTake, as anywhere

LangChain4jFleet fleet = LangChain4jFleet.builder(runtime)
        .tools()                                 // the fleet's cards as tools
        .modelClient(ModelClient.of("gpt-4.1-mini"))   // the fleet as the model
        .build();

Assistant assistant = AiServices.builder(Assistant.class)
        .chatModel(fleet.chatModel())
        .toolProvider(fleet.tools())
        .build();

The facade. LangChain4jFleet builds only what its settings enable, so a one-line facade never widens the fleet's reach by accident. Its parts:

  • tools() is a LangChain4j ToolProvider over the live catalogue. Each tool is named fleet_<agent>_<InputType> and has a JSON Schema from the input record. A call writes the input into the agent's take space and awaits the result.
  • DiscoveryTools.all() adds find_fleet_agents, list_fleet_assets, and fetch_fleet_data.
  • listeners() carries the take-lease listener, which renews the in-flight @SpaceTake on every model round-trip, and the usage listener. Pass them to a provider model's builder, or wrap a model with listening(model).
  • TakePropagation.wrap(...) and .executor(...) carry the take to another thread, so a renewal from a future or a parallel step still lands.
  • Memory.on() puts chat memory in a replicated space, where a conversation a Spring AI or Micronaut worker started resumes.
  • ModelClient.of("model") makes chatModel() and streamingChatModel() route calls through the space to the peers that serve them.
  • ModelServer.on() with modelServer(ModelCatalog.of("model", chatModel, streamingModel)) serves this peer's models on the shared wire records (agentspaces-model-wire), so the three hosts serve each other.
  • An embedding model. FleetRuntime.builder(...).embedder(LangChain4jFleet.embedder(embeddingModel, "name")) puts a real embedding model behind semantic discovery.

The service is the worker. An AiServices interface may carry the fleet annotations beside its LangChain4j ones:

  • a @SpaceTake method that is also a @UserMessage template takes the entry, asks the model, and completes with the answer;
  • a @Ballot method asks the model for the option.

The binder reads the annotations through the proxy's interface, so runtime.bind(AiServices.create(Reviewer.class, model)) is the whole of it.

Capability tools. .capabilityTools(FleetCapabilityTools.Settings.all()) adds six tools over the group's vote and aggregate capabilities: propose_vote, cast_ballot, read_tally, read_decision, contribute, and read_estimate. A model can then open or join a council and contribute to an epoch.

  • The settings choose the families, the ballot lease, and the settle timeout.
  • A tool answers with a plain error when the capability is not provided.
  • The Spring AI starter and the Micronaut bridge expose the same tools under their own settings.

The settings are records with defaults. Build them in code, or bind them from the tools and langchain4j sections of the same YAML with the Micronaut library's key names (ToolSettings.from(map), LangChain4jSettings.from(map)). One file configures a peer under any host.

The replaceable decisions are interfaces with defaults:

  • Tools: FleetToolFilter, ToolNamingStrategy.
  • Memory: ConversationIdResolver.
  • Model service: ModelCatalog, ModelRequestRouter, StreamChunkingPolicy, StreamRestartPolicy.
  • Usage: UsageSink.
Where it livesOne FleetRuntime per process, closed on exit, and one LangChain4jFleet per runtime, built before the services that use it. Its participants (the catalogue, a model server, the usage publisher) register with the runtime on their own.

If you build the parts over a bare FleetContext and FleetScheduler instead, the host starts participants() itself.

Example 19examples/langchain4j-fleet in the project runs a worker peer (a summarizer on its own model, a pricer with none, the model served to the fleet) and a keyless orchestrator peer whose tools and model are the fleet. Its flow test also leaves a worker stuck mid-task and watches another finish it.

The security notes of the Micronaut bridge apply unchanged:

  • Tool descriptions are model input.
  • requireAttested admits only agents with a certified key.
  • A caller accepts a model response only from an issuer the authorizer permits MODEL_SERVE.

Time and loop health on any host

A FleetRuntime runs the same node loop as the starter (time and the node loop), so a plain-Java host gets the same health signals:

  • runtime.loopHealth() reads the watchdog's judgement, OK, DEGRADED, or DOWN, and runtime.onLoopHealth(listener) hears each change. A host with no liveness probe sets agentspaces.watchdog.escalation: exit.
  • One time source. FleetRuntime.builder(...).clock(time) is the node's clock too when it is a TimeSource. In a test, pass VirtualTime.create() and move time with advance(...). FleetContext.time() is the node's time source.
  • Card refresh is a one-shot on the node's time source, re-armed after each run, so a slow refresh never stacks. FleetScheduler runs its tasks the same way.
  • The loop and watchdog keys bind from the same YAML, and an expert override's dotted key binds in each of its forms (which keys bind from YAML).

The model wire records: agentspaces-model-wire

agentspaces-model-wire is one small artifact with no dependencies. It holds the entry types that the model service, chat memory, and usage write, so that the three hosts serve each other.

  • Model calls. ModelRequest, ModelResponse, ModelChunk, ModelCancel, and ModelAttempt, with the Wire* parts they carry (messages, tool calls and tool responses, tool definitions, options, generations, usage, media). FleetChatModel and ModelServer write them, in agentspaces-springai and in agentspaces-langchain4j, which the Micronaut bridge wires.
  • Chat memory. ConversationSnapshot is chat memory in a space, written by SpaceChatMemoryRepository (Spring AI) and SpaceChatMemoryStore (LangChain4j).
  • Usage. ModelUsage is fleet-wide token usage on both.

The space names an entry type by its class, so two peers read each other's model calls only when they use the same classes. That is what the artifact is for:

  • a Micronaut service with no key calls a model a Spring Boot peer serves;
  • a conversation one framework's worker started resumes on the other's after a crash;
  • a mixed fleet's console sums usage as one.

The records are in the package ai.badmonkey.agentspaces.springai.model.wire. The three libraries bring the artifact in transitively. Add it directly only to read or write the records from code of your own.

The appendix explains the package name and the golden byte tests.

aspace://guide/space · chapter 10

The Space API

The Space API is the interface the annotations are built on. Use it when ordinary application code, such as a controller, a scheduled job, or a test, needs to write or take entries directly.

A space is a typed, leased tuple space: a shared collection of typed entries. Three things hold for every space:

  • Entries are plain records. Every entry is signed by its writer.
  • Entries expire. An entry goes away when its lease runs out, unless its writer renews it.
  • Every peer holds a copy. Each peer's copy of the space, its replica, keeps answering even while the network is split.

Getting a handleAgentSpaces.GroupContext

Before you call any verb, you need a Space object. There are four ways to get one, shown below. They all return the same object, so a space behaves the same however you reached it.

// 1. Inside an agent: @SpaceRef, injected at bind time. The common case.
@SpaceRef("findings") Space findings;

// 2. Anywhere else under Spring: the AgentSpaces facade bean, injected normally.
@Component
public record Coordinator(AgentSpaces spaces) {
    public void submit(String topic) {
        spaces.group("research-fleet").space("tasks")
              .write(new ResearchTask(topic, 3), Lease.of(Duration.ofMinutes(30)));
    }
}

// 3. Building one yourself: plain Java, tests, or a peer with no Spring at all.
ReplicatedSpace tasks = ReplicatedSpace.builder(runtime, "tasks", identity, "my-agent")
        .settleWindow(Duration.ofMillis(200))
        .build();
LocalSpace scratch = LocalSpace.builder("scratch", identity.agent("my-agent")).build();

// 4. Another agent's view of the same replica: same space, different signer and issuer (agent certificates).
Space asAuditor = tasks.as(identity.subordinate("auditor"));
Where it livesA controller, a scheduled method, a message listener, a test, a main: nothing about the space API requires an agent. The annotations are a convenience over this interface. Use the facade whenever the caller is ordinary application code that happens to need the fleet, and @SpaceRef when the caller is already a bound agent.
Keep in mindLocalSpace is the single-process form: the same interface and the same leases, with no network and no peer. Use it in unit tests, and in production for in-process fan-out. Swapping it for a ReplicatedSpace changes no calling code.

So you can write the logic against Space, test it locally, and deploy it replicated. Keep these points in mind:

  • LocalSpace has no conflict strategies or admission rules. A take there is exclusive within the process and first in, first out.
  • One replica per space name per node. A second ReplicatedSpace for a name that is already open is refused, naming the stream.
  • Close a replica to reopen its name. close() deregisters the first replica so the name can be opened again; example-02-research-fleet closes and reopens one.

The verbsSpace

These are the methods on Space. You write entries, read them, take them to process them, and subscribe to changes.

<T> EntryHandle          write(T entry, Lease lease);
<T> EntryHandle          write(T entry, Lease lease, Map<String,String> tags);
<T> Optional<T>          read(Template<T> template);
<T> Optional<T>          read(Template<T> template, Duration timeout);
<T> List<T>              readAll(Template<T> template, int limit);
<T> List<Issued<T>>      readAllIssued(Template<T> template, int limit);
<T> List<Entry<T>>       readAllEntries(Template<T> template, int limit);
<T> Optional<TakenEntry<T>> take(Template<T> template, Lease takeLease, Duration timeout);
    void                 complete(TakenEntry<?> taken);
<R> EntryHandle          complete(TakenEntry<?> taken, R result, Lease resultLease);
<R> EntryHandle          complete(TakenEntry<?> taken, R result, Lease resultLease, Map<String,String> tags);
<T> Subscription         notify(Template<T> template, SpaceListener<T> listener, Lease lease);

A few rules govern the verbs:

  • take is destructive and exclusive under the space's conflict strategy. The taker holds a TAKE lease and must call complete before it lapses, or the entry reappears.
  • complete with a result validates and prepares the result record before it commits the completion. A task can never end up completed but resultless.
  • Reads run against the local replica. They never block on the network.

Who wrote an entry

readAllIssued returns each match as an Issued<T>(T entry, AgentId issuer, Attestation attestation). The entry record's signature authenticates the issuer, and the attestation says how:

  • PEER_ASSERTED: the hosting peer's key signed and vouched for the name.
  • AGENT_ATTESTED: the agent's own peer-certified key signed (agent certificates).

Any reader that makes a trust decision per entry, such as a vote tally, an audit reader, or a result consumer, uses this. Do not trust a field the entry declares about itself. SpaceEvent carries the same authenticated issuer.

The full entry view

readAllEntries returns each match as a Space.Entry<T> view over its record. The view gives you:

  • value() and entryId().
  • The authenticated issuer() and its attestation().
  • The tags() the writer gave.
  • The lease() in force and the issued() stamp.

The four-argument complete(taken, result, lease, tags) writes a tagged result atomically with the completion. This is how a Tagged return from a same-space take lands.

A SpaceEvent carries the same view as details(), with tags() as a shortcut. The library's spaces fill it for WRITTEN and REAPPEARED, and for any other kind while they still hold the record. An event built without the record carries null there and empty tags.

Events fire on every peer

Events fire at every replica. A notify subscription, and every annotation built on one, runs on each peer that holds the space and the agent. When something must happen once across the group, use one of these:

  • a take;
  • a fleet-wide join or reduce;
  • a vote (idempotent per proposal id);
  • an idempotent write.

notify events arrive at least once, so use the event's entry id to drop duplicates. Listeners must return promptly. The @SpaceNotify binder does both for you, which is why it is the recommended interface. The event kinds are:

  • WRITTEN, TAKEN, and COMPLETED.
  • EXPIRED: a write lease lapsed, or its writer cancelled the entry, and the entry vanished.
  • REAPPEARED: a TAKE lease lapsed and the entry came back.

ReplicatedSpace adds a consistency hint on read and readAll:

  • ConsistencyHint.LOCAL (the default) matches the replica as it stands.
  • FRESH first triggers exactly one anti-entropy pull, a request for updates this peer may be missing, toward one random member. Then it matches locally. It is the cheap "make sure I am current" check a late joiner or an operator console wants, and it does not change the local-first default for everyone else.

Templates and matchersTemplateMatchers

A template says which entries a read, take, or subscription matches. Build one from a type, then add field and tag conditions.

Template.of(ResearchTask.class)
        .where("kind", eq("summarize"))
        .where("priority", gte(3))
        .whereTag("region", eq("eu"))      // a condition on the record's tags
        .hasTag("claimId");                 // the tag is present, whatever its value

Matching is by type, plus field predicates, plus tag conditions. The matchers live in ai.badmonkey.agentspaces.api.space.Matchers:

  • Comparisons: eq, ne, gt, gte, lt, lte.
  • Sets and text: in(values...), and contains(fragment) for character sequences.
  • Nulls: isNull, notNull.
  • Anything else: predicate(fn) is the escape hatch.

Fields resolve through record components. On a non-record type, the usual getX/isX accessors are read instead. An unknown field name throws at where(...) time, and the error lists the fields the type does have.

whereTag(key, matcher) and hasTag(key) condition the entry record's tags. The matcher receives the value stored under the key, or null when the record carries no such tag. So:

  • eq, in, and contains fail on an absent key.
  • isNull() selects untagged entries.

Both spaces check tag conditions after the type comparison and before they decode the payload, on every verb and on subscription delivery. So a keyless relay or a tag shard can select by tag without ever opening the record.

Tag values stay visible metadata under content encryption. Choose neutral tag values where that matters.

Leases and handlesLeaseEntryHandleTakenEntry

A lease is how long an entry, or a claim on it, stays valid. Lease.of(Duration) is the only constructor you need.

A write returns an EntryHandle with renew(extension) and cancel(). Cancellation is issuer-signed, so nobody else can withdraw your entry. Everything shares the one failure idiom: state you stop renewing goes away, and nothing needs a cleanup job.

A renewal reaches every member. renew moves the entry's lease, and every member judges the entry by the renewed lease, so a renewed entry stays readable and takeable everywhere until its new end. Java, Python, TypeScript, and Ruby all read it this way. A renewal never shortens a lease: one that asks for less keeps the current expiry (replication by entry).

A cancel withdraws the entry everywhere. When the writer calls cancel(), every replica stops returning the entry to reads and takes, and each raises EXPIRED once:

  • the cancelling replica at once, and every other replica that held the entry when the withdrawal reaches it;
  • a replica that learns of the entry only as withdrawn raises nothing, and a cancel that arrives twice, or a lapse after a cancel, raises nothing more;
  • a take whose settle window sees the entry withdrawn comes back empty;
  • completion wins over a concurrent cancel: every replica ends completed and hears COMPLETED once, and a cancel of an entry you already completed does nothing;
  • a cancel that another member signs withdraws nothing and raises nothing.

So a listener that drops state on EXPIRED hears a retired entry within a gossip round on every member, a LocalSpace and a ReplicatedSpace alike.

Waiting on other peers. Anything that waits on another peer expects lateness. A fetch, a graft, or a head that has not loaded is asked again later, of other holders, with backoff. A Python, TypeScript, or Ruby client re-dials a lost seed at 5, 10, 20, and 30 s until you close it. Give your own waits the same shape: a deadline, a retry with backoff, and another source.

Conflict strategies: pick per spaceConflictStrategyType

A conflict strategy decides which worker gets an entry when several try to take it. The space itself decides the first two strategies in the table, and you choose one when you build the space. The third is not a space setting at all; see the note below the table.

strategyhow a take is decidedcostreach for it when
LEASE_RACEthe first claim holds after one settle window (default 200 ms); at most one completion per entry, everone settle window of latency; transient duplicate work possible across partitionsthe everyday default; idempotent tasks
AUCTIONevery take carries a bid from the agent's bid function; the lowest bid takes the entry, converging over gossipa few gossip rounds; needs a bid functioncost-aware routing: cheap capacity sweeps easy work, premium capacity takes hard work
ORDEREDsigned take claims are submitted to a Raft log as commands; its commit order arbitrates identically on every member and the first valid committed claim per entry generation takes the entry, exactly once, in one total ordermajority quorum for liveness: a partitioned minority cannot take at all, which is precisely the trade the strategy sellsnon-idempotent, high-stakes entries: payments, filings

A space fixes one strategy for all its entries; use several spaces the way you would use several queues (tasks-bulk, tasks-auction, commits).

The winner can depend on arrival orderUnder LEASE_RACE and AUCTION, which claim wins a take can depend on the order in which claims reach each peer. Two peers can keep different winners, and a back-dated claim can beat an honest one. Narrow TAKE scope, or use ORDERED, where strict fairness or agreement on the winner matters.

The appendix explains how arrival order decides a claim.

ORDERED is a coordinatorPassing ConflictStrategyType.ORDERED to the space builder throws, and so does strategy: ORDERED in YAML. Build the space with the default strategy and take through the ordered-log capability instead, as below. Reads, writes, and completions still go through the space as usual; only take moves.

Taking through the ordered log

ORDERED takes go through the ordered-log capability, a coordinator registered on the group rather than a space setting. The ordered log covers the quorum, the registration, and what the log guarantees; @OrderedTake is the worker as one annotation.

Space admission: who may write and takeAuthorizer

Space admission decides which agents may write to and take from a space. A space advertises how it admits writers, independently of how the group admits members. Reads stay open to the group in every mode.

  • GROUP (the default) admits every admitted member of the group.
  • ALLOWLIST admits a fixed set of agents. A local caller outside the list gets a SpaceAdmissionException; an inbound record or claim from an unlisted agent is dropped and reported as misbehavior.
  • CREDENTIAL admits whoever holds a live credential from the issuer. A credential is an ordinary leased SpaceCredential entry that the issuer writes into the space itself, so nothing new appears on the wire. The issuer's node grants with space.grant(agent, scopes, validity) and revokes with space.revoke(agent), which is a signed cancellation.
  • AUTHORIZER hands the decision to the profile's Authorizer, scoped by the space name, which is how an identity provider's scopes (aspace:space-write:tasks) end up deciding.

How a write or take is judged

Each transition, such as a write or a take, is judged once as it arrives, after its signature verifies:

  • A refused local call throws.
  • A refused remote delta is dropped. It strikes its sender (reports it for misbehavior) only when the rule says the refusal cannot be a late credential.
  • A late credential is no strike. Under CREDENTIAL, a transition whose credential has not merged yet is dropped without a strike, because the evidence can legitimately arrive after the write it authorizes.
  • A record for another space is dropped first. A record whose spaceId names another space is dropped before any of this, however validly signed.

Which identity is judged depends on the mode:

  • ALLOWLIST and CREDENTIAL judge the acting agent. Several agents of one peer can share a replica through views (space.as(identity), agent certificates). Each view is admitted or refused on its own agent's standing, so such a space can admit one agent of a peer and refuse its sibling.
  • The CREDENTIAL issuer's peer is the exception. Every agent of a CREDENTIAL space's issuer peer is always admitted.
  • AUTHORIZER judges the peer. It asks the authorizer about the acting agent's peer, so every agent of one peer gets the same answer.

Building a spaceReplicatedSpaceNamespaceSchemaRegistry

The starter builds spaces from YAML; plain Java builds them directly. LocalSpace is the single-process form (same API, ideal for tests); ReplicatedSpace attaches to a joined group's runtime.

ReplicatedSpace tasks = ReplicatedSpace.builder(runtime, "tasks", identity, "my-agent")
        .settleWindow(Duration.ofMillis(200))
        .writer(identity.subordinate("my-agent"))   // sign as the agent's own certified key (agent certificates)
        .strategy(ConflictStrategyType.AUCTION)     // with .bidFunction(fn)
        .blocks(new BlockExchange(runtime, codec))   // content-addressed payloads
        .groupKey(key)                               // AES-256-GCM payload encryption
        .tagShard(tags -> "eu".equals(tags.get("region")))  // partial replica
        .admission(SpaceAdmission.allowlist(agents))  // or group/credentials/authorizer
        .maxLease(Duration.ofHours(24))              // tombstone horizon, see below
        .schemaHints(ResearchTask.class, Finding.class)  // published on the space ad
        .advertise(publisher)                        // with .advertisementTtl(ttl)
        .build();

Built with .advertise(publisher), a space publishes its own advertisement the moment it is created. The advertisement carries its strategy, admission, replication mode, and schema hints. These builder options control its lifetime and cleanup:

  • advertisementTtl (15 minutes by default). The advertisement is published once, at construction, and lapses from caches at this TTL unless the host calls refreshAdvertisement() on a cadence.
  • founderLease. When set, the space turns read-only when the founders' lease lapses, rather than silently accepting writes nobody will keep.
  • maxLease fixes the longest lease the tombstone sweep (the cleanup of finished entries) allows for. Replication by entry gives how long each kind of finished entry is kept.
  • local() makes a writer-local space: one only its own writer reads, such as a cache one agent keeps. It joins no gossip and sends no frames, so it costs the group nothing.

maxLease does not reject a longer lease. Without it, the replica uses the longest lease it has observed, up to 24 hours.

Payloads over 64 KiBConfigure .blocks(...) and large entries travel content-addressed: the space replicates a hash reference, and peers fetch the bytes on demand, verified against the hash. Because reads never block on the network, an entry whose block has not landed yet is not visible yet. Nothing is lost; it arrives a moment late.

While the block is on its way:

  • The replica starts one background fetch as soon as the record merges. A read that misses the entry starts one too.
  • A read with a timeout polls within that timeout and sees the entry once the block arrives.
  • A notify subscriber receives the entry's WRITTEN event the moment the block is local, without anyone having to read.
  • readAll skips the entry for that round.
  • A subscription event fires on the later merge or read that finds the block locally.

Replication by entryGroupRuntimeReplicatedSpaceReplicatedSpace.HorizonMode

From 0.7.0 two replicas repair a space entry by entry, not by the whole space's digest. Nothing changes in how you write, read, take, or watch. What changes is the traffic: a member that missed one entry fetches that one entry, and a late joiner pulls a large space in bounded answers.

  • The audit (wire.ae=2). Each space keeps a fingerprinted tree of its entries. Two members compare the trees from the top, walk down only where they differ, and fetch the entries that differ by id.
  • Budgeted answers. Every answer stays within a byte budget, 1 MiB by default. A large pull arrives in several answers, each one continuing where the last stopped.
  • The per-entry horizon (wire.horizon=1). A withdrawn entry is collected ten minutes after its own lease expiry, instead of after twice the longest lease. This holds only while this member and every member in its view advertise the hint, and only after a settling wait of one longest lease plus five minutes. Otherwise the older rule holds.
  • A renewal never shortens a lease. renew(extension) sets the expiry to the later of the current expiry and now plus the extension. The rule is the same for an entry, a take, and a subscription. To end a lease sooner, cancel it; to shorten it, cancel the entry and write it again.

The hints are negotiated

  • Each member says on its card what it understands. A round toward a member opens in the form that member's card names: the audit, the hashed round of earlier releases, or the full digest.
  • So there is no flag day for replication. 0.6.0 and 0.7.0 members replicate together, and a member of an older release sees nothing new on the wire.
  • A member without the hint returns withdrawals to the older horizon. One member in view without wire.horizon=1 is enough. The node takes up the per-entry horizon again only after the view has held no such member for three rounds of anti-entropy and the settling wait has passed.

How long a finished entry is kept

  • Completed: twice the longest lease after its lease expiry.
  • Withdrawn (cancelled): ten minutes after its lease expiry under the per-entry horizon; otherwise twice the longest lease, and never less than ten minutes.
  • Lapsed, with its lease run out: the shorter of twice the longest lease and five minutes.
  • The longest lease is the largest the replica has observed, capped at 24 hours, or the builder's maxLease.
propertydefaultmeaning
agentspaces.gossip.audittrueadvertise wire.ae=2 and audit toward members whose card carries it; off, every round keeps the hashed or text form
agentspaces.gossip.audit-budget1048576the bytes each answer to this node's audit requests may hold, 4096 to 4194304
agentspaces.gossip.audit-sessions4audit sessions kept open per asker, 1 to 4; a stream past the bound waits a round
agentspaces.gossip.probe-hash-streams32a probe carries a hash per stream up to this many streams, then the root alone; 0 to 256
agentspaces.space.horizonper-entryper-entry advertises wire.horizon=1; legacy keeps twice the longest lease. Use legacy on a node that renews for an identity another node renews for at the same time
agentspaces.space.renew-shortening-logtruelog once per space, at INFO, the first renewal that asks for less than its lease has left

Where to look when you want to see it work:

  • GroupRuntime.replicationStatus() reports the forms in view, the audit's counters, and the pacing.
  • ReplicatedSpace.horizonMode() reads LEGACY, WAITING, SETTLING, or PER_ENTRY.
  • ReplicatedSpace.renewShortenings() counts the renewals that asked for less than their lease had left. Each kept the longer lease, so the count names callers to fix.
  • Hand-wired, the keys are PeerNode.Builder.audit, auditBudget, auditSessions, probeHashStreams, horizon(boolean perEntry), and renewShorteningLog.

The appendix explains why repair by entry costs the same at any size, and why a renewal may not shorten a lease.

The schema registry: naming types on the wireNamespaceSchemaRegistry

The schema registry sets the name each type has on the wire. Change it when you want your types named by an IRI namespace.

By default, every type a space writes is named <fully.qualified.Name>#v1. The schema hints and the cards of bound agents carry the same names.

NamespaceSchemaRegistry.of(Map.of("org.example.claims", "https://example.org/claims#")) names the classes of the mapped packages by an IRI namespace (https://example.org/claims#Claim). It leaves every other type on the default rule, the reserved SpaceCredential, vote, ordered-log, and JoinTicket records included.

Share one instance, so the names the spaces write and the names the cards advertise agree. Give it to:

  • each space builder: .schemaRegistry(schemas);
  • the binder or facade: spaces.schemaRegistry(schemas), or a SchemaRegistry bean under the starter.

Set it early:

  • The facade's setting is the default for every group registered afterward.
  • A group's own schemaRegistry(...) and the binder's schemas(...) refuse a registry once that group has bound its first agent.

Remote actions resolve a card's names through the registry's classFor. For an IRI under a mapped namespace that no registration produced, classFor tries a class of the mapped package, loaded without initialization. So a peer needs the class on its classpath, but no prior registration. An IRI outside the mapped namespaces never loads a class.

// plain Java -- one registry for the spaces and the facade
SchemaRegistry schemas = NamespaceSchemaRegistry.of(Map.of("org.example.claims", "https://example.org/claims#"));
ReplicatedSpace intake = ReplicatedSpace.builder(runtime, "intake", identity, "registrar")
        .schemaRegistry(schemas)                    // org.example.claims.Claim is written as https://example.org/claims#Claim
        .schemaHints(Claim.class, RegisteredClaim.class)
        .build();
spaces.schemaRegistry(schemas);                   // call before registering groups: they inherit it
aspace://guide/discovery · chapter 11

DiscoveryDiscoveryServiceBeaconLocatorBootstrapChain

Discovery answers "who can do what" in the group. Use it to find the group in the first place, and then to see which peers, agents, spaces, and assets are out there.

Each peer keeps a per-group cache of cards: signed advertisements with a time to live (TTL), which expire unless their issuer republishes them. The peers keep the caches fresh by passing cards from peer to peer, a process called gossip. Chapter 12 covers the services built over the same fabric.

A peer has to find its group before it can read any card, so the chapter opens with that first contact:

Then it turns to the cards.

1 LOCATE: THE CHAIN ASKS EVERY LOCATOR AT ONCE, EACH UNDER ITS OWN DEADLINE2 DIAL: THE ORDINARY STRANGER PATH3 JOIN: THE VIEW FILLS AND THE LOCATORS GO QUIETnewcomerempty viewDNSSRV, DNS-SD, TXTbeaconsigned documentseed memberlistening peerthe groupSWIM, gossip_agentspaces._tcp.<domain>?hosts, ports, url=GET /.well-known/agentspaces/beacon.jsonseeds, founding, wire hints, signedmerge the hints in order, drop duplicates:one BeaconHint with the shortest TTLdial the first endpoint, HELLOsigned founding, member viewverify the founding hashes to the id that was asked for;bootstrap budget, advertisement verification, admissionSWIM probes, gossip, anti-entropycards: peers, spaces, agents, assetswhile the view is empty the chain is re-asked, between refresh-min and refresh-max apart
Finding the group. A newcomer asks its locators at once: DNS answers with hosts and a pointer, the beacon answers with a signed document of live seeds and the founding. The chain merges one hint, the newcomer dials a seed through the same stranger path any peer takes, verifies the founding against the id it wanted, and the group's own gossip does the rest. A locator can delay a join and never admit anyone.

Picking bootstrap options

Every option below answers the same question: whom does a newcomer dial first? None of them admits anyone. Whatever a locator returns is dialed through the ordinary stranger path, so the choice is about where the answer lives and who maintains it.

The chain asks every configured locator at once, and ranks their answers in the order you listed them. So you can combine two or three and let the cheapest one answer first. For example:

  • a seed list for the first day;
  • DNS for the fleet;
  • a beacon document for partners.

Start with the simplest option that fits the network you actually have. Add the next one when the seed list goes stale.

OptionWhat it gives youWhat it needsBuild with it
Seed list (groups[].seeds)a way in with no infrastructure; a name with several addresses dials every address; a member once joined needs the seeds no morea list to keep current; two seeds per peer so one that is down is only a delaya service fleet on a fixed set of hosts, Docker Compose, a CI harness, every numbered example
Multicast beacon (agentspaces.multicast.*, off by default)peers on one segment find each other with no seeds and no configuration; the datagram can be sealed under the group's content keyUDP on the segment; counts only as a hint under required attestationa lab bench, a vehicle, a shop-floor cell, a classroom demo, a floor of devices and robots on one network
DNS SRV (SrvLocator)the directory the enterprise already runs answers with hosts, ports and priorities; Kubernetes, Consul and Cloud Map publish SRV recordsrecords to register when the seed set moves; an authenticated resolver before DNS may name the groupa fleet across virtual machines in one corporate network, a service that migrates between hosts, a registry-backed platform
DNS-SD and a TXT pointer (DnsSdLocator, TxtLocator)zero per-peer configuration: the search domain DHCP hands out carries _agentspaces._tcp, and one TXT record can point at a document that follows the live groupa zone you administer; the beacon prints the recordsagents on office desktops and laptops, branch offices, developer workstations that join by domain alone
Kubernetes headless service (K8sLocator)the SRV records Kubernetes publishes for a named port, with no Kubernetes client; a UDP port resolves to DTLSa headless service in the namespace; pods that listena fleet of pods per namespace, autoscaled worker pools, a sidecar peer beside an existing service
Beacon document over HTTPS (UrlLocator, agentspaces-beacon)one URL where newcomers read the group's current seeds, wire hints and the signed founding, signed by the beacon and pinned by its PeerIda stable peer with its own keystore, TLS in front of its HTTP port, a pointer record in DNSpartners who hold only an id and a URL, a fleet across organizations, a seed set that changes often, a hosted control plane
Static document (StaticDocumentLocator)the same signed document from a file or a classpath resource, read again at every locatea way to ship the file; a re-issue when the seeds changeair-gapped sites, field kits, appliance images with the document baked in, offline installs
Rendezvous and relay roles (agentspaces.roles)not locators but what the others point at: a rendezvous answers discovery for a whole site, a relay carries one signed hop between peers that cannot dial each otherone more peer per site or region; relayed frames are refused under required attestationa WAN with one well-known address (example 06), laptops and robots on carrier networks, home-office developers without a VPN
Join by group id (join: aspace://<id>)a founding verified against the id before the first frame, so the id can travel further than the configurationa signed founding (a group started from a text has none) and a reachable member that holds it; a ten-second timeoutprinted or emailed credentials, partner onboarding, a registry of groups, invitations
A custom locator (BeaconLocator)your own registry or cloud API as one element of the chain, with appliesTo to serve one groupone small classConsul, etcd or ZooKeeper lookups, a cloud instance API, a licence server that hands out seeds
Keep in mindThe beacon document follows the live group, and the DNS records do not. So when the seed set changes, register only the pointer record and let the beacon carry the rest.

Two more limits apply:

  • Plain DNS cannot name the group. A plain DNS answer may list seeds but may not name the group. By default, accept-group-id-from accepts only an authenticated resolver (DNS over HTTPS with DNSSEC, in agentspaces-bootstrap-dns) or the url and document locators.
  • There is no universal bootstrap group and no mDNS. A deployment that needs a directory of groups founds one and seeds from it. Or it runs a beacon and registers its records in the DNS it already administers.

Finding the group: locators, hints, and the chainBeaconLocatorBeaconHintBootstrapChain

A peer that has just started knows no members of its group yet. It has to dial one member before the fabric can do anything else. Two terms:

  • A seed is an address a newcomer dials first.
  • A locator is one way of finding one.

BeaconLocator.locate(BeaconRequest) answers with a BeaconHint, or with BeaconHint.none() when the locator has nothing. The request carries what the node knows:

  • the group's name;
  • its GroupId, when the group was founded locally or is joined by id;
  • the scheme a bare host:port takes;
  • every scheme the node can dial.

The hint carries:

  • endpoints, in priority order;
  • optionally, the group id the locator believes and the signed founding;
  • parameters, such as wire hints;
  • a lifetime (BeaconHint.DEFAULT_TTL, five minutes, when the source states none);
  • the evidence a trace shows.

A BootstrapChain is the locator a group is joined with. It is an ordered list of locators that it asks all at once, each under its own deadline (timeout, three seconds by default). A locator that throws or times out contributes nothing and stops nothing.

The chain merges the hints in order:

  • The first locator ranks highest. Its addresses come first, and the chain removes duplicates.
  • The first founding is kept. The chain keeps the first founding it finds.
  • Group id claims need permission. The chain takes a group id claim only from the locators named in acceptGroupIdFrom, and only for a request that carries no id. Every join in 0.7.0 carries the id it was configured with, so today the setting is validation only: it refuses startup when it names an unauthenticated locator without insecure-group-id. The builder defaults to url; a chain composed from agentspaces.bootstrap.* defaults to url and document.
  • Names expand last. The chain expands names to addresses last.
  • The shortest lifetime wins. The merged hint gets the shortest lifetime among the contributors.

firstWins() asks one locator at a time instead, and stops at the first that returns addresses. A locator's appliesTo(groupName) lets one chain element serve a single group.

typewhat it is
BeaconLocatorname(), locate(request), appliesTo(groupName) (every group by default), and policy()
BeaconRequestgroupName, groupId (optional), defaultScheme, schemes
BeaconHintendpoints, groupId, founding, parameters, ttl, evidence; of(endpoints, evidence) and none()
LocatePolicyminInterval, maxInterval, require, trace: how the node paces, requires, and traces one locator's answers
BootstrapChainthe builder's add, addAll, firstWins, timeout, acceptGroupIdFrom, expandNames, and locatePolicy; lastTrace() lists what each locator did
SeedsLocatorthe configured seed list as a locator: of(List<String>) with host:port or scheme://host:port strings, fixed(endpoints), parse
MulticastLocatorwhat the node's multicast beacon heard, so that the datagram takes a place in the chain
DnsExpansionone endpoint per address of a seed name: expand and split

A custom locator is one small class, and the chain composes it with the others:

BeaconLocator registry = new BeaconLocator() {
    public String name() { return "registry"; }

    public BeaconHint locate(BeaconRequest request) throws IOException {
        // your registry call
        List<PeerAdvertisement.Endpoint> found = lookup(request.groupName());
        return found.isEmpty() ? BeaconHint.none()
                : BeaconHint.of(found, "registry " + request.groupName());
    }

    public boolean appliesTo(String groupName) {
        return groupName.startsWith("research-");
    }
};

BeaconLocator chain = BootstrapChain.builder()
        .add(SeedsLocator.of(List.of("seeds.corp.example:7500")))
        .add(registry)
        .timeout(Duration.ofSeconds(3))
        .build();
GroupRuntime group =
        node.joinGroup(groupAd, GroupMembership.Config.defaults(), chain);

A group is joined in one of three forms. PeerNode.joinGroup has an overload for each that takes a BeaconLocator in place of a seed list:

  • GroupAdvertisement for a group started from a text;
  • SignedGroupAdvertisement for a peer that holds the signed founding;
  • GroupId with a timeout, to join by id.

The node asks the locator when it joins, and again while it knows no members of the group. PeerNode.Builder.locateInterval(min, max) sets the pace: never faster than min allows, and at least once per max (30 seconds and 10 minutes by default). A locator's own LocatePolicy overrides that for its group.

To see what happened, and to leave a group:

  • lastBootstrapTrace(groupId) returns one BootstrapChain.Trace per locator asked: name, milliseconds, endpoint count, evidence, and error.
  • lastBeaconHint(groupId) returns the last merged hint.
  • leaveGroup(groupId) releases one group and keeps the others.
Where it livesThe interfaces are in agentspaces-api (api.spi); the chain, the seeds locator, and name expansion are in agentspaces-peering (peering.bootstrap); the starter and Micronaut compose a chain per group from properties (chapter 5). agentspaces-bootstrap adds the DNS, Kubernetes, and document locators (below).
Keep in mindA locator can never admit anyone. Whatever it returns is dialed through the node's ordinary stranger path: the bootstrap budget, full advertisement verification, and the group's admission policy. So a wrong DNS answer delays a join and substitutes nothing.

A hint's group id and founding are claims. The node verifies a founding against the id it was configured with, and every join carries that id, so a locator's group id claim is never consulted today. accept-group-id-from is the permission a future join by name would need, and in 0.7.0 it only refuses startup when it names an unauthenticated locator.

The locators and the DNS resolver

The agentspaces-bootstrap project (ai.badmonkey.agentspaces:agentspaces-bootstrap:0.6.0, its current release) supplies the locators an enterprise network can answer, over a small DnsResolver interface, and depends on nothing beyond the AgentSpaces libraries and Jackson. Each locator below asks one directory.

classasks
SrvLocatorthe SRV records (RFC 2782) at one owner name, one endpoint per record at the record's priority; records of one priority are ordered weighted-random by weight
DnsSdLocatorDNS-SD (RFC 6763) under each network domain: the PTR records at _agentspaces._tcp.<domain> name the instances, each instance's SRV records give hosts and ports, and its TXT record gives v, group, id, scheme, url, and multicast. An instance whose group differs from the request's group name is skipped unless anyGroup is set, and a url is followed through a UrlLocator
TxtLocatorone TXT record at agentspaces.<domain> that holds url= (and optionally id=), followed through a UrlLocator
K8sLocatorthe SRV records Kubernetes publishes for a named port of a headless service, _<port>._<protocol>.<service>.<namespace>.svc.<cluster-domain>, with no Kubernetes client; a UDP port is looked up under _udp and its endpoints default to dtls
UrlLocatora beacon document over HTTPS, with a deadline, a size cap, at most two redirects on the same host, no credentials or cookies, private-address targets refused, an optional host allow-list, a signature required and verified (an unsigned document is refused unless url-allow-unsigned allows it, because it would let its publisher choose the seeds), and a pinned beacon PeerId honored. It selects the group by id when the request has one, else by name
StaticDocumentLocatora beacon document from a file or a classpath: resource, read again at every locate
DomainFinderthe network domains the DNS locators look under: the configured list, the AGENTSPACES_DOMAIN variable, the search and domain lines of /etc/resolv.conf, or on Windows the search list ipconfig /all prints
DnsResolveraddresses, srv, ptr, txt, and authenticated(). JndiDnsResolver uses the JDK's JNDI provider and authenticates nothing, InMemoryDnsResolver serves tests, and DnsJavaResolver in agentspaces-bootstrap-dns (dnsjava, BSD-licensed) adds servers, doh, dnssec, trustAnchors, and timeout
BootstrapSettings, LocatorAssemblythe agentspaces.bootstrap.* keys as a POJO, and the locators those keys ask for, in order
ChainComposer, BootstrapTreethe composition both hosts share, and the nested-map binding of the keys for Micronaut
DnsResolver dns = new JndiDnsResolver();
String site = "https://agentspaces.corp.example";
URI doc = URI.create(site + BeaconDocument.WELL_KNOWN);
UrlLocator url = new UrlLocator(List.of(doc), UrlLocator.Options.defaults(), null);
BeaconLocator srv = new SrvLocator(
        "_aspace._tcp.agentspaces.corp.internal", "tls", dns);
BeaconLocator sd = new DnsSdLocator(
        DomainFinder.of(List.of("corp.example")), dns, false, url);
BeaconLocator k8s = new K8sLocator("agentspaces-seeds", "fleet", "aspace",
        "cluster.local", "tcp", "tls", dns);

// DNS over HTTPS with DNSSEC validation: the agentspaces-bootstrap-dns project
DnsResolver secure = DnsJavaResolver.builder()
        .doh("https://dns.corp.example/dns-query").dnssec(true).build();
Keep in mindAn authenticated() resolver is what lets a DNS answer name the group. LocatorAssembly refuses a plain-DNS locator (dns-sd, dns-txt, dns-srv, k8s) or multicast in accept-group-id-from at startup, naming the property, unless insecure-group-id is set or the resolver authenticates its answers, as DnsJavaResolver does with DNSSEC.

Beacons and the beacon document

A beacon gives newcomers one stable place to learn the group's current seeds. Three terms:

  • A beacon is a peer that newcomers can find and dial first: an ordinary member with a stable address, usually playing RENDEZVOUS, with no special role on the wire.
  • The beacon document is the signed JSON it serves at BeaconDocument.WELL_KNOWN, /.well-known/agentspaces/beacon.json.
  • The multicast beacon is the opt-in LAN datagram, a core feature that appears in a chain as MulticastLocator.

BeaconDocument, in agentspaces-bootstrap, is a record of:

  • the format version;
  • the issuer's PeerId and key;
  • the issue time and a time to live;
  • the groups;
  • an Ed25519 signature over the canonical bytes.

Each group entry carries its name, id, seeds, wire hints, multicast group, and free parameters. It carries the signed founding when the group has one. The methods:

  • BeaconDocument.signed(identity, issuedAt, ttl, groups) signs.
  • parse(bytes) reads; unknown fields are ignored.
  • verifies() checks the signature, and signer() names the issuer.
  • toBytes() returns the exact signed JSON.

The writer refuses a parameter named like a content key, a credential, or a membership hint, so a document never carries a secret.

The agentspaces-beacon project (ai.badmonkey.agentspaces:agentspaces-beacon:0.6.0, its current release) is a ready-made beacon and the classes to build your own:

classwhat it does
BeaconDocumentSourcebuilds the document from a running PeerNode: one entry per joined group, the founding when the group has one, the seeds (this node first, then the rendezvous members, then the other members that listen, capped at eight by default), the node's wire hints, and the multicast group; signs it with the node's identity; rebuilds at most once per refresh interval
BeaconDocumentCustomizera hook on each group's entry before signing: add a parameter, replace the seeds, or change the entry's other fields
BeaconServerserves the document on the JDK HTTP server: GET and HEAD of the well-known path only, Cache-Control from the TTL, an ETag answered with 304, read-only CORS, a per-source request rate, and an optional file copy (see below the table for when the copy is refreshed)
BeaconPublisherthe interface a host's own web layer implements instead of BeaconServer
RecordPrinterthe DNS-SD PTR, SRV, and TXT records and the single TXT pointer for a document, as a zone fragment
BeaconMainthe standalone beacon: --keystore, --founding or --join, --bind, --advertise, --http, --roles, --domain, --url, --write-to, and more

No timer refreshes the file copy. The server rewrites the file atomically inside current(), which runs when a request is served (and once at BeaconMain startup), when the document differs from the last copy written. So an ingress that serves only the file sees a newer document only after a request reaches the beacon's own port.

BeaconDocumentSource source = new BeaconDocumentSource(node, identity,
        InstantSource.system(), Duration.ofMinutes(5), Duration.ofSeconds(30),
        8, null,
        List.of((draft, group) -> draft.parameter("region", "eu-west-1")));
BeaconServer server =
        new BeaconServer(source, 50, Path.of("/var/lib/agentspaces/beacon.json"));
int port = server.start(new InetSocketAddress("0.0.0.0", 7580));

String records = RecordPrinter.zone(source.get(), "corp.example",
        "https://agentspaces.corp.example" + BeaconDocument.WELL_KNOWN);
byte[] signedJson = source.get().toBytes();   // for a web layer you already run
Where it livesThe Spring Boot and Micronaut adapters for a beacon (agentspaces.beacon.*) are not built yet, so an application on either framework wires these classes itself.
Keep in mindGive the beacon a keystore, because its PeerId signs the document and readers pin that PeerId with beacon-peer. Without one, the id changes at every start. Put TLS in front of the HTTP port, because a reader trusts the hostname.

Two more points about the document:

  • Register only the pointer record. The document follows the live group, and the DNS records do not: SRV records registered by hand name the seeds of the day they were typed. So when the seed set changes, register only the pointer record (agentspaces.<domain> TXT url=).
  • A group started from a text has no signed founding. Its entry carries none, and a peer joins it with the same text. Only a group with a signed founding can be joined by id from the document.

Cards, the ad cache, and the ads stream

Everything discoverable is a card: a typed, signed advertisement in a per-group cache that gossip keeps fresh. A card whose issuer stops republishing ages out. The advertisement families are:

  • peers and groups;
  • spaces, with their admission and replication modes;
  • capabilities;
  • AgentCards, with their space bindings;
  • AssetCards;
  • ModelCards;
  • AppCards;
  • revocations.

The cache verifies every signature, bounds its own occupancy, and evicts by TTL. A peer volunteering as RENDEZVOUS holds four times as much. Query structurally, or by meaning through the semantic-discovery capability (its reference embedder needs no model at all):

// who can turn a ResearchTask into a Finding?
List<AgentCard> researchers = discovery.find(AgentCard.class,
        card -> card.produces().contains(Finding.class.getName() + "#v1"));

// or escalate beyond the local cache: rendezvous peers first, then scoped gossip.
// The remote predicate is structural (field name to the expected value's string form, so match on description rather than on the agent id) so it can
// travel on the wire, and it is validated against the type before anything is sent.
discovery.remoteFind(AgentCard.class,
        Map.of("description", "Researches topics"), Duration.ofSeconds(2));

Most fleets never call this. Work finds its worker because the worker is sitting on the space taking that type. The routing is the entry's type, and nobody looks anything up.

Discovery earns its keep when you need to know who is out there, rather than get one task done:

  • a console drawing the room;
  • a planner deciding whether a capability exists before committing to a plan (the Embabel bridge builds on exactly this);
  • an operator asking which peers can still do a thing;
  • a dispatcher that wants to fail loudly when nobody is listening, instead of writing an entry into a space where it will sit until its lease lapses.

The cards an application uses

Four kinds of card matter to an application (the four cards), and a fifth announces services:

  • An AgentCard describes a bound agent. The binder builds it from the identity annotation and the bound method signatures. Remote actions, fleet tools, and planners read its actions.
  • An AssetCard describes a data asset: its name, shape, freshness, and access. A connector publishes it (the connector SDK, or an AssetProvider bean under Micronaut), for data queries and for the fleet as a service registry. A content store advertises itself with one too (a store for the fleet).
  • A ModelCard describes 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 signs it with an AdvertisementSigner and publishes it with discovery.publish. serves(task) and residentAt(site) keep a predicate short.
  • An AppCard describes an application that joins the fleet: its kind (peer, fed, gateway, assembled, or dynamic), its shape (web, desktop, static, or a2ui), the spaces it reads, the actions it may request, its views, and the A2UI components it draws. An AppCardPublisher signs it, reissues it as members join and leave, and puts a large card's parts on the content swarm. fromOrigin(system, ref) and handles(format) filter it, and discovery.resolve(card) fetches a large card's parts.
  • A CapabilityAdvertisement is a service's card, signed and leased like the others (chapter 12).
// AssetDiscoveryTest: the serving peer publishes a signed ModelCard; another peer finds it by task
server.discovery().publish(signer.sign(classify, server.identity()));
List<ModelCard> classifiers = agent.discovery().find(ModelCard.class, c -> c.serves("classify"));

// AppCardsGateTest: the publisher issues an AppCard; a reader filters by origin and fetches a large card's parts
AppCardPublisher publisher = new AppCardPublisher(a.identity(), a.runtime(), a.discovery());
publisher.publish(card).join();
List<AppCard> fromRealm = b.discovery().find(AppCard.class, c -> c.fromOrigin("realm", "example-realm/*"));
AppCard full = b.discovery().resolve(stub).join();

An AgentCard holds:

  • the agent's name, description, and goals;
  • one declared action per bound method: the consumed type, the produced types, and the method's description;
  • its space bindings;
  • under subordinate keys, its public key and certificate;
  • since 0.7.0, the chat threads it answers, when it names any (threads).

All of them travel on the ads stream, the group's advertisement gossip, which the Python, TypeScript, and Ruby clients read as ads. A new card spreads fast, and a late joiner catches up. The appendix explains how the ads stream spreads cards.

How long a card lives

Every card is leased, and each kind is republished on its own cadence:

  • Agent cards: the binder republishes them on agentspaces.card-refresh-millis (five minutes by default).
  • Capability advertisements: the capability runtime republishes them on the same cadence through refreshTick().
  • Space advertisements: a space's advertisement lapses at its advertisementTtl unless the host refreshes it.
  • Any card whose issuer stops republishing ages out of every cache at its TTL.

Revocations travel on their own gossip streams: revocations for peers, and credential-revocations for agent credentials. The cache purges the cards of a revoked peer and of a revoked agent.

Where it livesAnywhere you can reach a DiscoveryService: spaces.group("g").discovery() under Spring, or the service you constructed on a plain-Java peer. This is no concern of an agent's: agents publish cards automatically by being bound, and read them only when they want to reason about the fleet.
Keep in mindfind is a local, in-memory scan of the cache, so call it as often as you like. remoteFind puts a query on the wire and blocks for the wait you give it, so it belongs on a slow path rather than in a loop.

Both return what the cache holds now. A card whose issuer died is still there until its TTL runs out, and a card from a peer that just joined may not have arrived yet. Treat the result as a hint about a live fleet, never as an authoritative roster. The fabric itself applies the same discipline.

Chat threads, dynamic AppCards, and A2UI 1.0AgentCardAppCardChatThread

SPEC v0.1.38 adds two card fields in 0.7.0. Both are a flag day, so read the note below before you publish either.

The threads an agent answers

An AgentCard may name the conversations its agent answers in threads, so a reader learns from the card which channel the agent chats on, without its configuration. Each entry is a ChatThread(space, key, scope):

  • space is the space the agent watches for chat lines.
  • scope is exact (the one thread the key names), tree (that thread and every key:<sub> thread under it), or all (every thread of the space).
  • key names the thread. It is empty exactly when the scope is all.
  • Limits. A card names at most 16 distinct threads. A space name or key is 1 to 128 characters with no white space.
  • Setting them. card.withThreads(List.of(...)) returns the card with its threads; an empty list leaves the field out. A card without threads keeps its 0.6.0 bytes.
  • Matching a line. ChatThread.takes(space, key) says whether a thread takes a chat line, and overlaps(other) whether two threads could take the same line.
AgentCard chatty = card.withThreads(List.of(
        new ChatThread("conversations", "support", ChatThread.TREE)));
// tree: the thread "support" and every "support:..." thread under it
boolean mine = chatty.threads().get(0)
        .takes("conversations", "support:order-7");    // true

The dynamic AppCard

  • AppCard kinds are now peer, fed, gateway, assembled, and dynamic (AppCard.KINDS). A reader refuses any other kind.
  • assembled is a composition its publisher selected and reviewed before publishing, served as is: a static site, or a page whose components were chosen once and that binds the live reads its reads name, such as a chat page.
  • dynamic (new) means the app's agent composes the layout per person and per moment from the catalogs its ui.catalogIds lists. Every surface is checked against those catalogs before it reaches a person.
A flag day for two fieldsA reader older than SPEC v0.1.38 refuses an AgentCard that carries threads, and an AppCard of kind dynamic, and drops the whole card. A 0.6.0 member therefore does not see such an agent or application. Every 0.7.0 implementation reads both. Move every member of a group to 0.7.0 before any of them publishes either field.

A2UI 1.0 final

The pages a card declares and the widget catalogs are A2UI 1.0, the final specification. A2UI 0.9.1 is no longer read.

  • Envelope keys at the root of a component take the @ prefix: @catalogId, @accessibility, @metadata, @checks. id and component stay bare.
  • Bindings are {"@path": ...} and calls @call; the builders refuse the 0.9.1 forms.
  • Component ids are Unicode identifiers (UAX #31), so a hyphen is refused.
  • The renderers are the @a2ui/* packages at 0.16.1.

The A2UI guide shows how an AgentCard and an AppCard declare the pages a fleet draws, with the open widget library and the renderers.

Semantic discovery and embeddersSemanticDiscoverySemanticClient

Use semantic discovery to ask "who holds something like this?", a question by meaning. find takes a structural predicate instead.

The semantic-discovery capability (aspace:cap/semantic-discovery) is an embedding index over the group's advertisements: a search index over number vectors that stand for the meaning of each card's text. It sits behind a pluggable Embedder. It is request/response and needs no clock and no model set-up.

  • The index holds AgentCards, AssetCards, ModelCards, AppCards, CapabilityAdvertisements, and SpaceAdvertisements. A ModelCard ranks by its name, version, tasks, modality, engine, and licence.
  • query(text, limit) searches the local cache.
  • remoteQuery(text, limit, timeout) escalates over the capability pipes to the peers that advertise the capability, and merges what they rank.
  • SemanticClient is the typed client, from group.capability(SemanticClient.class) or a @CapabilityRef field.
  • The Spring AI, Micronaut, and LangChain4j libraries expose the same query to a model as find_fleet_agents and list_fleet_assets.
// Semantic: find an asset by meaning rather than by name (examples/example-10)
var matches = semantic.remoteQuery("who holds customer order history?", 3,
        Duration.ofSeconds(2));
AssetCard card = (AssetCard) matches.get(0).advertisement();

Matching is only as good as the embedder. Pick one:

  • HashingEmbedder (shipped) needs no model and is a lexical approximation: good enough to find an asset by description, and short of understanding. The Python, TypeScript, and Ruby clients compute the same vectors and index each card by the same text, so every side ranks alike.
  • SpringAiEmbedder (embedder.type: spring-ai, Spring AI) wraps any Spring AI EmbeddingModel.
  • A LangChain4j model: the Micronaut and LangChain4j libraries do the same for a LangChain4j EmbeddingModel (embedder.type: langchain4j, or LangChain4jFleet.embedder(model, name)).

The embedder's identity (spring-ai:<model>, langchain4j:<model>) is advertised on the capability. So a query goes only to peers that rank alike. The appendix explains how vectors are cached and why the identity matters.

Model cards

A ModelCard (v0.1.24) is the AssetCard's sibling for a model a group may route to: its name, version, tasks (chat, embed, rerank, classify, transcribe, vision), modality, limits, licence, provenance (the upstream, the weight root on the content swarm, the weight hash, who admitted it), evaluations, cost hints, residency (sites, classifications), the engine that serves it, and the peers that hold it. It is signed and leased like every advertisement, cached and expired by the same cache, and found with discovery.find(ModelCard.class, c -> c.serves("classify") && c.residentAt("on-premises")). Semantic discovery finds it by meaning too: semantic.query("classify claims onnx", 3) returns the model cards whose name, tasks, or engine share those words, best first. A peer that advertises aspace:cap/llm-gateway routes requests tagged task=<kind> by such cards; a request addressed to a model name a ModelServer advertises is unchanged.

aspace://guide/capabilities · chapter 12

Capability servicesCapabilityRuntimeCapabilityProvider

Capability services answer "what does the fleet think" and "what must happen exactly once". Use them when agents need to vote, sense a fleet-wide figure, take an entry exactly once, learn a shared model, or obtain a content key.

These services are Layer 4, built over the same fabric as the space. Each one is a CapabilityProvider on the peer's CapabilityRuntime, advertised with a signed, leased CapabilityAdvertisement. An agent reaches it through an annotation or a typed client.

Six ship: vote, aggregate, the ordered log, gossip learning, key wrap, and semantic discovery. Chapter 11 covers semantic discovery with the cards it ranks. This chapter is the model every service follows, then one section per service, then how to serve one of your own.

WHAT REACHES IT: ANNOTATIONS AND TYPED CLIENTS@Ballot @OnDecision@Propose, a Motion returnVoteClienta Contribution return@OnEstimateAggregateClient@OrderedTakeORDERED join and reduceOrderedTakes.over(...)GossipLearning@ProvidesCapability@BidFunction reads itGroupKeyDistributorrequestAs(agent)content-key in YAMLTHE FIVE SERVICES: CapabilityProvider on the peer's CapabilityRuntimeVoteaspace:cap/votethe vote spaceAggregateaspace:cap/aggregatepipesOrdered logaspace:cap/ordered-logpipes + the spaceGossip learningaspace:cap/gossip-learnpipesKey wrapaspace:cap/key-wrappipesTHE PIPES AND THE SPACECapabilityPipes: PIPE_DATA frames addressed to one memberpush-sum shares, learning offers, key requests, Raft traffica spaceproposals and ballots; the entries an ordered take claimsTHE CLOCKthe peer's loop runs each provider when its round falls due; refreshTick() republishes its ad with the cardssemantic discovery, the sixth service, is the ad cache queried by meaning: chapter 11
The capability services. Each annotation or typed client in the top row reaches one service; each service is a provider the runtime registers, advertises, and runs when due; underneath, the pipes carry addressed frames and the vote and ordered services also work through a space. Semantic discovery lives with discovery in chapter 11.

How a capability is usedCapabilityRuntimeCapabilityAdvertisement

A capability has three roles, and a given peer may play any subset of them. Mixing up the roles is the most common wiring mistake at this layer.

  • The provider is the object that implements CapabilityProvider and serves the capability on this peer. Under the starter, the shipped ones are registered for you from agentspaces.capabilities.*. Otherwise it is a @ProvidesCapability bean.
  • The consumer is whatever calls it. Typed clients resolve off the group context, as spaces.group("g").capability(VoteClient.class), and need no annotation at all. Most application code is only ever this.
  • The clock advances a continuous capability's own protocol, such as an aggregate exchange, a gossip-learning offer, or a Raft heartbeat. You do not supply it. A capability runtime registers its providers with the peer's loop when it is constructed, so a provider is driven because it is registered. Each provider runs when its next round falls due. Nothing to schedule, nothing to remember.

Because the runtime drives every registered provider, the annotations are enough on their own. One loop per peer runs the whole stack (the node loop).

The aggregate keeps its own pace: its gossip rounds run once a second (PushSumAggregate.ROUND_PERIOD) while an epoch is active, and not at all once every epoch is quiet. The appendix explains when each service runs.

// There is no driver to write. Registering the capability is the whole of it:
// under the starter this already happened, and under plain Java it happens
// the moment the runtime exists.
AgentSpaces.GroupContext group = spaces.group("orders-fleet");
group.capabilities().isDrivenByPeerTick();     // true

// A test that wants each round to be an exact, countable step takes the
// rounds back and drives them by hand. (A node on VirtualTime needs none of this.)
group.capabilities()
        .detachFromPeerTick()
        .cadence(Duration.ofMillis(300));      // the period you will step it at

// one step, deterministically (at 300 ms a step the aggregate gossips about once per second of steps)
group.capabilities().protocolTick();

An aggregate needs a few dozen rounds of one second each, so a fleet settles in tens of seconds. When you drive the runtime by hand on a node whose loop is not running, as in the test above:

  • a runtime that declares no cadence gossips on every protocolTick();
  • one that declares a cadence gossips about once per second of it.

A second clock at this layer runs at a deliberately different rate. The protocol clock above runs on the peer's loop, at each provider's own deadlines. The advertisement clock, refreshTick(), republishes leased capability advertisements and runs with the card refresh, on the order of minutes. A method named for one will not do the other.

The six capability services

Each service below has its own section later in this chapter, except semantic discovery, which is in chapter 11.

  • Vote (aspace:cap/vote): proposals and ballots are signed entries, and the decision closes at quorum. Any member recomputes the tally from the space. QUORUM mode is the canonical, auditable form; MAJORITY_GOSSIP is a cheap approximate temperature check.
  • Aggregate (aspace:cap/aggregate): every member ends up with the same fleet-wide figure, with no collector. Six operators (SUM, AVG, COUNT, MIN, MAX, QUANTILE) work over a supplied value or over a template's matching entries. Call aggregate.start("backlog", localValue), then estimate("backlog").
  • Ordered log (aspace:cap/ordered-log): provides strong consistency, for ordered operations, exactly-once delivery, and similar designs. It runs a small Raft among volunteers, with the leader lease published as an advertisement. It backs ordered takes and any workflow needing a total order. Off by default, since it needs a fixed member set.
  • Gossip learning (aspace:cap/gossip-learn): peers exchange mergeable models in pairs and end up at the fleet mean, with no parameter server. Suits learned bid policies. Off by default; enabling it wires the default weight-averaging learner.
  • Semantic discovery (aspace:cap/semantic-discovery, chapter 11): an embedding index over the group's advertisements behind a pluggable Embedder. query(text, limit) searches locally, remoteQuery(text, limit, timeout) escalates; the shipped hashing embedder needs no model at all, and agentspaces-springai swaps in any Spring AI EmbeddingModel (semantic discovery).
  • Key wrap (aspace:cap/key-wrap): distributes group content keys sealed per member, or per agent under requestAs. Encrypted spaces onboard members without any shared secret in transit (security). A holder serves every epoch of its key ring.

Typed capability clients

Consumers do not speak the capability's entries directly. A client type resolves off the group context, and the client finds the providers, speaks the protocol, and hands back ordinary values:

VoteClient vote = spaces.group("orders-fleet").capability(VoteClient.class);
vote.propose("rollout-7", "ship the new pricing model?",
            List.of("yes", "no"), 3, Lease.of(Duration.ofMinutes(10)))
     .castBallot("rollout-7", "yes", Lease.of(Duration.ofMinutes(10)));

Optional<VoteCapability.Decision> decided = vote.decision("rollout-7");  // or tally(id)

AggregateClient agg = spaces.group("orders-fleet")
        .capability(AggregateClient.class);
agg.start("backlog", queueDepth()).estimate("backlog");

Register your own with spaces.clientFactory(new MyClient.Factory()), and serve your own capability with a @ProvidesCapability bean (custom capabilities).

Reaching a capability from inside an agentVoteClientAggregateClientSemanticClient

To use a capability from inside an agent, use a field or an annotation. An agent POJO has @SpaceRef for spaces; the equivalent for capabilities is @CapabilityRef.

For what agents do with a capability, there are annotations of the same shape as @SpaceNotify (chapter 3 and chapter 4):

  • @Ballot and @OnDecision for the vote;
  • @OrderedTake for the ordered log;
  • a Contribution return for the aggregate.

Constructor injection of the capability object still works, and is still fine when the caller has it in hand. The annotations are the idiomatic form because they encode the discipline for you: one ballot per proposal, one reaction per closed vote, and the resubmit after an election. Every hand-written consumer got that discipline wrong at least once.

// agentspaces-partybus -- Party.TravelerAgent: contributes to the aggregate and votes, with no vote code
@AgentSpec(name = "traveler",
        description = "A traveler on the trip: reports energy each day and votes on the party's choices",
        goals = {"have a good trip"})
public static final class TravelerAgent {
    private final Traveler traveler;
    private final int stamina;
    private final PushSumAggregate aggregate;      // constructor-injected; @CapabilityRef AggregateClient also works
    @SpaceRef(TRIP) Space trip;

    @SpaceNotify(space = TRIP, lease = "12h")
    public EnergyReport feel(TripDay day) {
        int energy = energyOn(day, trip.readAll(Template.of(TripEvent.class)
                .where("tripId", eq(day.tripId())).where("date", eq(day.date())), 20));
        aggregate.start(Itinerary.energyEpoch(day.tripId(), day.date()), energy);
        double spent = 40 + (traveler.about().toLowerCase().contains("food") ? 45 : 20) + day.dayIndex() * 3;
        aggregate.start(Itinerary.spendEpoch(day.tripId(), day.date()), spent);
        return new EnergyReport(day.tripId(), day.date(), traveler.name(), energy, spent);
    }

    @Ballot(space = DECISIONS, prefix = "next:", lease = "12h")
    public String decide(VoteCapability.Proposal proposal) {
        return preference(proposal.options());       // the cue is the proposal itself: no wait, no voted set
    }
}

Under Spring the typed clients resolve from the facade, as spaces.group("trip").capability(VoteClient.class), or arrive by @CapabilityRef; SemanticClient joins VoteClient and AggregateClient. Providing a capability through the facade (group.provide(vote)) is what makes the vote annotations on its space bindable; group.ordered(space, coordinator) does the same for @OrderedTake.

Where it livesCapabilities are peer-scoped: one PushSumAggregate per peer serves every agent on it, and one vote capability per vote space casts for every bound agent, as that agent when the agent has a key of its own. There is no driver to get wrong: the capability runtime runs what it registers on the peer's loop.

VoteVoteCapabilityVoteClient

Use the vote capability when the fleet must reach one decision that any member can audit afterwards. The vote capability (aspace:cap/vote) runs over a space:

  • A Proposal is a signed entry carrying the proposal id, the question, the options, the quorum, and a lease.
  • Each Ballot is a signed entry naming the proposal and the option.
  • The decision closes when the tally meets the quorum.

Any member recomputes the tally from the space, so a decision is auditable afterwards from the entries alone. There are two modes:

  • QUORUM is the canonical form and counts one ballot per eligible voter.
  • MAJORITY_GOSSIP is a cheap approximate temperature check by push-sum, the method the aggregate uses. The Python and TypeScript clients carry it too: cast_preference and leader in vote.py, castPreference and leader in vote.ts, over their push-sum aggregate.

The electorate is any authenticated issuer by default, which is the starter's choice too. Narrow it to fresh AgentCards with VoteCapability.freshAgentCards(discovery), and by the authorizer. The voter is derived from the ballot's authenticated issuer, never from a field the ballot declares.

VoteClient is the typed client:

  • propose(id, question, options, quorum, lease), or propose(Motion), which is idempotent per proposal id;
  • castBallot(id, option, lease);
  • tally(id);
  • decision(id), which answers once the quorum is met with the winner, the tally, and the granularity that closed it.

The capability's own onDecision(proposals, listener, lease) returns a leased subscription. Inside an agent, the same three steps are annotations: @Propose opens, @Ballot casts, and @OnDecision reacts once when the vote closes.

To register the capability:

  • group.provide(vote) registers it and also advertises it.
  • group.vote(space, vote) registers it without advertising it.
  • Under the starter, agentspaces.capabilities.vote builds one over votes-space. List that space under groups[].spaces so agents can bind to it.
Who counts as a voterA ballot names its voter, and the tally discards any ballot whose declared voter is not the entry's authenticated writer. That check stops anyone voting on your behalf. How many distinct voters a peer can be is then the authorizer's decision.

The tally counts at the authorizer's granularity(VOTE, space):

  • PEER (the default, and every OIDC profile): one peer is one counted ballot however many agent names it writes, so a member cannot multiply itself.
  • AGENT: switch it on by naming peer/localName AgentIds in agentspaces.security.grants.vote. Each named agent counts once, and only when its ballot is AGENT_ATTESTED, signed by the agent's own certified key (agent certificates).

A fresh AgentCard is a liveness filter, never an eligibility check. Decision.granularity() says which rule closed the vote.

A VoteCapability still votes as the one agent its space handle writes as (space.writer()). Constructing one with another identity throws, rather than handing you an object whose every ballot would be silently dropped.

Aggregate: sensing the fleet with push-sumPushSumAggregate

Use the aggregate for questions no single peer can answer: what is the fleet's average backlog, how many workers are live, what is the p95 of a number every peer holds a piece of. It uses push-sum, a method in which peers repeatedly share parts of their values with each other. There is no collector and no metrics server; every member ends up holding the same estimate.

Two rules keep the estimate honest. The capability runtime applies the first for you:

  • A share goes only to a member that takes part. participants(rule) restricts the push, and PushSumAggregate.advertisedIn(discovery) admits a member whose capability advertisement is live. The runtime applies that rule to every aggregate it registers, so a bystander peer (a console, a client that has not started the capability) never takes part in the estimate.
  • A Settle rule says when the figure has stopped moving. It counts a step only when the step is a gossip round this node took part in after it first heard the epoch, or when the epoch has gone quiet.

Rounds run once a second (PushSumAggregate.ROUND_PERIOD), so a settle of forty seconds is a streak of forty steps. The Python and TypeScript aggregates advertise and filter the same way. The appendix explains why the aggregate needs these two rules.

// Every member contributes its own number to a named epoch...
aggregate.start("backlog", myQueueDepth());

// ...the peer's loop exchanges them, and after a few dozen rounds every member
// reads the same fleet-wide figure. Empty until the first round completes:
// a capability that has not run yet will not pass its own seed off as a
// fleet answer.
OptionalDouble sensed = aggregate.estimate("backlog");

// A supervisor can then act on what the whole fleet feels rather than on its own view:
if (sensed.orElse(0) > BACKLOG_THRESHOLD) {
    vote.propose("scale-up-1", "Average backlog is " + sensed.getAsDouble()
            + "; add two workers?", List.of("approve", "reject"),
            4, Lease.of(Duration.ofMinutes(10)));
}

Sense with aggregate, then decide with vote. That pair is the whole of examples/example-05-quorum, and it is the canonical shape for autonomic behavior: the fleet notices its own condition and commits to a response that every member can audit afterwards from the vote space.

To act once the figure has stopped moving, instead of polling estimate:

  • AggregateClient.awaitSettled(epoch, Settle.after(Duration.ofSeconds(8), tolerance), timeout) blocks until the rule holds.
  • @OnEstimate reacts to the same rule as an annotation.
Keep in mindestimate returns empty until this peer has taken part in at least one exchange (a round or a received share, for any epoch). After that, a freshly started epoch answers with this peer's own seed until shares arrive. It returns a converging number before it has settled, so read it a moment after start rather than in the next statement.
  • An epoch id is a string every participant agrees on. Different strings are different, independent aggregations. The partybus runs one epoch per trip day this way.
  • An estimate that stays empty is the fabric telling you the capability is not being driven. Under the starter that should never happen.
  • Over a fully replicated space, prefer AVG, MIN, MAX and QUANTILE in template mode. SUM and COUNT over entries every replica already holds will count each entry once per replica, which is almost never what you meant.

The ordered logOrderedTakes

Use the ordered log when an entry must be taken exactly once. The ordered log (aspace:cap/ordered-log) provides strong consistency, for ordered operations, exactly-once delivery, and similar designs. It runs a small Raft among a fixed set of volunteers. Raft is a protocol in which a fixed set of members agrees on one order of commands. The leader lease is published as an advertisement, so role=leader is discoverable. On a started node the leader sends a heartbeat every 250 ms, a follower stands for election after 1.25 to 2.25 s of silence, and the log republishes its card at a role or term change and at half its lease.

It backs the ORDERED claim path. Signed take claims are submitted to the log as commands, and its commit order arbitrates identically on every member. The first valid committed claim per entry generation takes the entry, exactly once, in one total order.

How it fits with the space:

  • The space keeps the default strategy. ORDERED is a coordinator registered on the group.
  • OrderedTakes.over(...) wraps the log and the space as the coordinator that takes through it. Reads, writes, and completions still go through the space as usual, and only take moves.
  • A peer hosts one ordered log per group. So an ORDERED join or reduce lives on the space that has the coordinator.
  • It is off by default, because it needs a member set the starter cannot guess. The starter's ordered-log switch refuses automatic assembly for that reason.

Exactly-once is one annotation now: @OrderedTake is @SpaceTake with the take routed through the space's ordered-log coordinator, so the loop, the resubmit after a leader election, and the complete-or-lapse are the binder's. What stays yours is the quorum: a fixed member set, one coordinator per space, built with OrderedTakes.over(...) and registered on the group. The exactly-once desk and the Party Bus booking clerks are the worked examples.

// examples/example-12-exactly-once-desk -- ExactlyOnceDesk.startClerk(...)
OrderedTakes ordered = OrderedTakes.over(new CapabilityPipes(base.runtime(), codec), codec,
        identity, name, members, InstantSource.system(), seed, base.payments());
base.group().ordered(PAYMENTS, ordered);   // registers the log on the peer's loop; @OrderedTake can now bind

// ExactlyOnceDesk.Clerk: the exactly-once worker is one method
@OrderedTake(space = PAYMENTS, lease = "30s", pollTimeout = "2s", resultLease = "1h")
public PaymentReceipt confirm(PaymentOrder order) {
    return new PaymentReceipt(order.orderId(), order.payee(), order.cents(), peer.name(),
            peer.raft().commitIndex());
}

Reach for this only where a duplicate is genuinely unacceptable and you would otherwise reach for a distributed lock: charging a card, filing a return, allocating a serial number, sending a message a customer will see once. Everywhere else LEASE_RACE is cheaper and more available, and the duplicate work it can produce across a partition is the price of continuing to run at all.

Where it livesThe worker is an annotated method on any bound class; the quorum is assembly code that runs once. Wire the RaftLog and OrderedTakes at startup, in a @Bean method or the assembly code of a plain-Java peer. The worker is a @OrderedTake method or a loop you own.

If you want the rest of the agent model around it, keep the ordered worker as its own class. Let the annotated agents handle everything that is not the exactly-once step. The partybus does this: it keeps one small Raft quorum for bookings, and leaves thirty-odd other agents on LEASE_RACE.

Keep in mindThe member set is fixed, and every member must be given the same list. This is a static quorum that does not grow with membership. A minority partition cannot take at all, by design; that is the availability you trade away for exactly-once.

Registering the log is the whole of the clock wiring: the peer's loop runs elections and heartbeats. A log you construct but never register is never elected, and every take times out empty. The appendix explains what OrderedTakes.over(...) and registration do for you.

Gossip learningGossipLearnerGossipLearning

Gossip learning lets peers build a shared model without any raw data leaving any peer. This section shows it end to end. It also ships as a runnable fleet, examples/example-14-gossip-learning: three peers whose local weight vectors reach the fleet mean on the peer's loop alone, with a test that asserts it.

The idea: every peer holds a parameter vector. Peers pair off at random and average their vectors, and the fleet reaches the mean without a parameter server. Add a local update step that runs after each merge and you have federated training: train on what you have, average with a neighbour, repeat.

Three things must be true for it to work. The first two are your job:

  • Every participant registers the same model id with the same vector length.
  • The local update, if any, is supplied at construction.
  • Something drives the exchange. This is the runtime's job, done for you as soon as the provider is registered.
// 1. Build the learner. The starter's gossip-learn toggle gives you a pure
//    averaging learner; to train, construct your own and publish it as a bean.
//    (Illustrative bean: the builder call is GossipLearningTest's, the bean shape is
//    EchoCapability's under @ProvidesCapability; "metrics" must be a space declared under groups[].spaces.)
@Component
@ProvidesCapability(GossipLearning.TYPE)          // "aspace:cap/gossip-learn"
public class BidPolicyLearner implements DueCapabilityProvider {
    private final GossipLearning learning;

    public BidPolicyLearner(AgentSpaces spaces) {
        AgentSpaces.GroupContext group = spaces.group("orders-fleet");
        // The builder is the configurable form: a training step, and a metrics
        // space so endEpoch below has somewhere to write.
        this.learning = new GossipLearning(GossipLearner.builder(
                        group.pipes(), group.runtime().sampler(),
                        group.identity().peerId(), CborCodec.defaultCodec(), group.clock(),
                        WeightAveraging.INSTANCE)
                .localUpdate(params -> sgdStep(params, batch()))  // the training step
                .metrics(group.space("metrics"), Lease.of(Duration.ofDays(7)))
                .build());
    }
    @Override public String capabilityType() { return learning.capabilityType(); }
    @Override public CapabilityAdvertisement describe(GroupId g) {
        return learning.describe(g);
    }

    // 2. Join the model. Every peer must use the same id and the same length.
    @EventListener(ApplicationReadyEvent.class)
    public void join() {
        learning.start("bid-policy", new double[]{1.0, 0.0, 0.5});
    }

    // 3. Advance the protocol. The loop runs the learner at its own deadlines (an offer
    //    once a second); hand both calls on, and you write no driver.
    @Override public void attach(DueWork.Driver driver) { learning.attach(driver); }
    @Override public long run(long nowNanos) { return learning.run(nowNanos); }
    @Override public void tick() { learning.tick(); }   // a node driven by hand steps this

    // 4. Read the current parameters wherever you need them -- e.g. from a
    //    @BidFunction, which is what makes the fleet's bid policy learned.
    public double[] parameters() {
        return learning.model("bid-policy").orElse(DEFAULTS);
    }
}
// And at the end of a training epoch, write one evaluation per model into the
// metrics space, so the fleet's loss curve is itself replicated state
// (agentspaces-capabilities -- GossipLearningTest, trimmed):
Space metrics = spaces.group("orders-fleet").space("metrics");
List<GossipLearner.Evaluation> written =
        learning.endEpoch(epoch, params -> lossOn(params, holdoutSet()));
// Any member can then read everyone's, attributed to its authenticated author:
List<Space.Issued<GossipLearner.Evaluation>> all = metrics.readAllIssued(
        Template.of(GossipLearner.Evaluation.class).where("epoch", eq(epoch)), 100);

Use it for anything where peers hold private data and want a shared model:

  • learned bid policies (the fleet converges on what work actually costs);
  • drift detectors;
  • shared bandit statistics;
  • federated fine-tuning signals.

It is the natural partner of @BidFunction. A bid function is a plain method over numbers, and this is how those numbers learn.

Under pure averaging, the fleet mean does not drift. Three things can move it:

  • a lost ACCEPT can move mass one-sidedly;
  • a local update changes the mean by design;
  • a departing peer takes its share with it.

The appendix explains how pairwise averaging reaches the mean.

Where it livesA provider bean. The four numbered steps above sit in one class on purpose, because they share the learner instance. Consumers, such as a bid function or a scheduled reporter, read parameters() off that bean by ordinary injection.

For a model that is not a double[], implement MergeableModel and build a GossipLearner<YourType> directly. GossipLearning is the double[] specialization under WeightAveraging. Its two short constructors cover pure averaging and averaging-plus-update. Anything more, such as a metrics space or a block exchange, goes through the builder as above.

Keep in mindPeers that never called start for a model id ignore exchanges about it, and a vector of the wrong length is dropped rather than merged. So a rolling deploy that changes the model's dimension silently splits your fleet into two populations that never interact. Version the model id when the shape changes.
  • Keep the local update cheap. It runs after every merge, so keep it to one step; a full training run in there will stall the learner.
  • Large models need a block exchange. Models above the 64 KiB inline limit travel content-addressed through the block exchange automatically, but only if the learner was built with one.
  • endEpoch needs a metrics space. It throws unless the learner was given one, which is the one reason to prefer the builder over the plain constructors.

Key wrap: content keysGroupKeyDistributor

Use key wrap to give a member the group content key without ever putting it on the wire in the clear. With key wrap (aspace:cap/key-wrap), the holder serves the key under the profile's authorizer. A joining member asks for it sealed to its own X25519 key (X25519, HKDF, AES-256-GCM).

The holder serves every epoch of its key ring; each rotation of the key is a new epoch:

  • request returns the epoch-0 key alone.
  • fetch(holder, epochs, timeout) brings rotated epochs sealed to the peer.
  • requestAs brings them sealed to an agent.
  • follow(ring, discovery) fetches whatever epoch the ring lacks, each time a holder's card changes.

It is request/response and needs no driver, though it runs on the peer's loop for auto-rotation and for following a holder's epoch announcements. Under the starter, agentspaces.groups[].content-key is both what the capability serves and what seals every payload. Content encryption and rotation covers the epochs, the key-rotator grant, and what rotation can and cannot do.

// Key wrap: the holder serves the key under the profile's authorizer...
keys.serve(contentKey, authorizer, groupId);

// ...and a joining member asks the holder for it, sealed to its own X25519 key.
// request returns epoch 0; fetch and requestAs bring the rotated epochs.
Optional<GroupKey> key = keys.request(holderPeerId, Duration.ofSeconds(2));
Keep in mindThe authorizer is consulted per request rather than once at serve time. So revoking a grant takes effect on the very next ask. A request nobody serves completes empty rather than hanging.

The content key is a ring of epochs that rotates. An agent with a certified X25519 key can ask as itself (requestAs), so a sibling agent on the same peer learns nothing.

Custom capabilitiesCapabilityProviderProvidesCapability

Write a custom capability when your fleet needs a service the shipped ones do not provide. A capability of your own is a CapabilityProvider:

  • capabilityType() names it.
  • describe(group) builds its signed CapabilityAdvertisement.
  • start() is an interface default you override when the protocol needs setting up.
  • A protocol with rounds of its own implements DueCapabilityProvider. Its run(nowNanos) does what is due and returns the next deadline. attach(driver) hands it a driver whose wake() asks for a run now and whose describeChanged() republishes its card.
  • The older form, overriding tick() or requiresTick(), still works and is stepped every 250 ms. requiresTick() is deprecated.

Mark the class @ProvidesCapability and register it: as a Spring bean, through spaces.bind(bean), or with group.provide(provider). The group's CapabilityRuntime then starts it, publishes its advertisement, refreshes it on every card refresh, and runs it on the peer's loop.

  • To speak to peers, use group.pipes(), the PIPE_DATA frames addressed to one member that the shipped services use, or a space.
  • Consumers reach it through a client type registered with spaces.clientFactory(new MyClient.Factory()). They resolve it like any other, by group.capability(MyClient.class) or a @CapabilityRef field.

The gossip learner above is the worked example of a provider with rounds of its own. The echo capability under @ProvidesCapability is the smallest one.

aspace://guide/large-data · chapter 13

Large dataContentPieceStore

This chapter covers payloads too big for an entry, such as a model checkpoint or a 3 GiB scan. The content swarm moves them between the members of a group, and between groups.

The content swarm

An entry carries up to 64 KiB inline, and up to one 8 MiB block by reference. Above that, a payload is an artifact of the content swarm (aspace:cap/content-swarm, module agentspaces-content). Three parts make it work:

  • The manifest. The fabric replicates a small signed manifest. It carries the artifact's root, a CIDv1 over the hashes of its fixed-size pieces, which identifies the artifact by its content.
  • Holdings. Every member that holds pieces writes a leased holding that says which. So the replica itself is the index of who has what.
  • The bytes. They move between members over whatever transport sessions exist, from every holder at once.

Nothing in the module names a transport scheme. So a browser on wss, a kit on dtls, and a server on quic serve pieces of one artifact to one receiver, and a relay forwards pieces it cannot read.

1 PUBLISH: CUT THE BYTES INTO PIECES, HASH EACH ONE, WRITE A MANIFESTcheckpoint.bin, in fixed-size pieces (1 MiB by default)0h01h12h23h34h45h56h67h7h = sha2-256 of one pieceContent.publish(path, options)returns the manifest; its root names the byteshashesManifestroot: a CIDv1 over the piece hashesHoldingthe publisher holds every piece; leasedcontent spacegossip copies both2 FETCH BY ROOT: FROM EVERY HOLDER AT ONCE, EVERY PIECE CHECKEDpublisherall 8peer-b0 to 4peer-c3 to 7reader: fetch(root)01234567each piece: sha2-256 = table[i]?pieces 0, 1pieces 2, 3, 4pieces 5, 6, 7the rarest piece first, from every holder;a holder whose piece fails is struck;the reader serves what it has checked
The content swarm. A publisher cuts an artifact into fixed-size pieces, hashes each one, and writes a small signed manifest whose root is a CIDv1 over those hashes, with a leased holding beside it. Gossip copies both to every member, so the content space is the index of who holds what, and a holding ages out when its holder stops renewing it. A reader fetches by root from every holder at once and checks each piece against the manifest's table before it keeps or serves the piece.

Publish and fetch

To share a file, publish it. Content.publish(path, options) hashes a file in pieces, writes the manifest and this peer's complete holding to the group's content space, and returns the manifest. Bytes and an InputStream work the same way. The options:

  • Piece size: 1 MiB by default. PublishOptions.pieceSizeFor(capabilities) answers 256 KiB for a binding that may lose frames, so a lost range costs little.
  • withInPlace(true) serves the file where it lies and copies nothing.
  • withAttrs(Map.of("run", "42")) attaches tags a template can match.

To get an artifact, fetch it by its root. Content.fetch(root) returns a handle with:

  • progress(): pieces verified, bytes per source, and an estimated time to completion;
  • await and cancel;
  • open() for the complete artifact;
  • trace(): what the scheduler did.

The fetch asks every reachable holder at once and verifies every piece against the manifest. A seeder's death does not stop a transfer, and a fetch resumes from the store after a restart. The appendix explains how the fetch scheduler picks pieces and holders.

Manifest m = content.publish(Path.of("checkpoint.bin"),
        PublishOptions.defaults().withName("checkpoint.bin").withAttrs(Map.of("run", "42")));
// on another member
Fetch fetch = content.fetch(m.root());
if (fetch.await(Duration.ofMinutes(10))) {
    try (SeekableByteChannel bytes = fetch.open()) { ... }
}
List<Content.Description> runs = content.search("checkpoint", null, Map.of("run", "42"), null, null, 10);

describe(root) reports the manifest and the holder counts without starting a fetch. list(template, limit) matches manifests by field and tag, and search(name, mediaType, attrs, origin, maxAge, limit) answers "the latest model for run 42" newest first.

Large entries

Attach the swarm to a space when its entries can be large. A space built with the swarm attached escalates any payload above escalate-above (4 MiB) into an artifact, and records its root in the entry. space.write(new Scan(pixels)) with a 3 GiB array is an ordinary write.

Built by hand, the space takes the swarm through bulk. A large write, and a take on another member, look like this:

ReplicatedSpace scans = ReplicatedSpace
        .builder(runtime, "scans", identity, "scanner")
        .blocks(blocks)
        .bulk(new SpacePayloads(content), 4L * 1024 * 1024)   // above 4 MiB
        .build();
EntryHandle written = scans.write(new Scan("ct-0042", pixels),
        Lease.of(Duration.ofHours(1)));
// the record carries the artifact's root, "bafkrei..."
String root = scans.recordOf(written.entryId()).orElseThrow().payloadRef();
// on another member: the take returns once the artifact is complete there
Optional<TakenEntry<Scan>> taken = scans.take(Template.of(Scan.class),
        Lease.of(Duration.ofMinutes(5)), Duration.ofMinutes(2));
  • Take and notify see the entry once the artifact is complete. A take or a notify on another member sees the entry once its artifact is complete there.
  • A read never waits on the network. A read that meets an artifact still on its way starts the fetch and skips the entry until it lands.
  • The lease is shared. An artifact's lease is the entry's lease.
ONE WRITE, THREE PATHS BY THE SIZE OF THE ENCODED PAYLOADscans.write(new Scan(id, pixels), lease)a space built with .bulk(new SpacePayloads(content), threshold)inline, up to 64 KiBthe bytes ride in the entry recordpayloadRef: nullone block, to 4 MiBfetched by its referencepayloadRef: "z..."an artifact, above 4 MiBon the content swarm (escalate-above)payloadRef: "bafkrei...", its rootmanifest + piecesthe artifact's lease is the entry's leaseGossip replicates the record; above 64 KiB it carries a reference in place of the bytes.A space without the swarm carries one block up to the block cap (about 8 MiB).ON ANOTHER MEMBERtake and notify see the entry onceits artifact is complete on thismember, so a taker never waits on bytesa read never waits on the network:it starts the fetch and skips theentry until the artifact landsone lease: the artifact lives aslong as the entry and goes whenthe entry goesa take hands over the decoded entry, the same as an inline one
When an entry escalates. The space measures each encoded payload. Up to 64 KiB the bytes ride in the entry; above that, one block by reference; and above escalate-above (4 MiB) in a space that has the swarm attached, an artifact whose root the record carries. The agents see none of it: a take or a notify on another member fires once the artifact is complete there.

The connector SDK's bulk results ride the same path. A 300 MiB query result reaches the requester through the swarm without a line of connector code. Build the data space with DataSpaces.builder(runtime, name, identity, agent, blocks, new SpacePayloads(content), threshold).

A space without the swarm can refuse a payload above a cap, with a message naming the property (agentspaces.blocks.max-payload). By default it carries one block up to the block cap, as before.

Stores

The store is where a peer keeps pieces. It is a backend provider interface with these implementations:

  • FilePieceStore keeps one directory per root, with a bitfield it forces to disk every eight pieces. It resumes after a restart, and evicts least-recently-served roots over its quota, never a pinned one.
  • MemoryPieceStore is for tests and small artifacts.
  • InPlaceStore serves files where they lie.
  • CompositeStore reads through several in order. It can cache a range from a read-only backend, such as a registry or a bucket, into the writable one.
  • EncryptedPieceStore wraps any store so the pieces on disk are encrypted under a local key (store.encrypt-at-rest).

To build a store by hand, compose the backends and pass the result to Content.builder(...).store(store). The starter builds the same store from agentspaces.content.store.* (operator keys).

Path dir = Path.of("/var/lib/agent/content");
PieceStore file = new FilePieceStore(dir, codec, InstantSource.system(),
        20L << 30);                        // a 20 GiB quota
PieceStore store = new CompositeStore(List.of(
        // pieces encrypted on disk, under a key kept in dir
        new EncryptedPieceStore(file, EncryptedPieceStore.keyIn(dir)),
        // files served where they lie
        new InPlaceStore()),
        false);                            // cache no external range

Holdings derive from what the backends report, so a peer that already holds artifacts is a seeder with no transfer.

Stores also check their own data. A writable backend re-hashes one piece in 64 when it starts and forgets a root whose sample fails. An in-place file is hashed at its first serve. So a damaged disk stops serving rather than serving damage.

Sealed artifacts

Under a group content key, pieces travel sealed (encrypted) per range under the epoch's key. A member without the key can neither serve nor fetch them.

To keep an artifact alive on members that may not read it, publish with withSealedHashing(true). It seals each piece once at publication and hashes the sealed bytes instead. Then:

  • any member can verify, store, and serve the pieces, including one without the key;
  • only key holders open it, through openPlain(root);
  • the root belongs to its group, because its bytes depend on the group's key.

In code, with a publisher, a member without the key, and a key holder:

Manifest m = content.publish(scan,
        PublishOptions.defaults().withSealedHashing(true));

// a member without the key verifies, stores, and serves the sealed pieces
keyless.fetch(m.root()).await(Duration.ofMinutes(5));

// a key holder fetches from any holder, the keyless one too,
// and opens the plaintext
keyHolder.fetch(m.root()).await(Duration.ofMinutes(5));
try (SeekableByteChannel plain = keyHolder.openPlain(m.root())) { ... }

To limit who a holder serves, and how much:

  • the CONTENT_FETCH grant (agentspaces.security.grants.content-fetch) narrows who a holder serves;
  • an upload budget per day bounds a holder;
  • a download budget does the same for a metered fetcher.

The bridge recipe

A bridge copies artifacts from one group into another. A member of two groups shares an artifact from one into the other with Content.share(root, lease). The second group gets a manifest with the same root, sealed under its own key when it has one, and the bridge serves both from one store.

  • A root hashed sealed is re-sealed under the second group's key and travels there as a new root: target.share(root, lease, source).
  • A whole catalogue: Content.shareAll(source, targets, predicate, lease) mirrors one, for example every root whose attrs name a mission.

A @SpaceNotify on Manifest in one group that calls share into another is the whole bridge.

On the bridge, inFleet and inMission are the Content of each group, over one store:

// a plain root: the same root in the mission's group, from one store
Manifest copy = inMission.share(m.root(), Lease.of(Duration.ofDays(1)));
// a sealed root: re-sealed under the mission's key, as a new root
Manifest resealed = inMission.share(sealed.root(),
        Lease.of(Duration.ofDays(1)), inFleet);
GROUP A, UNDER KEY A: SEALED HASHINGthe artifact's piecesp0p1p2p3p4p5seal each piece once, under key As0s1s2s3s4s5then hash the sealed bytesroot Aa CIDv1 over the sealed hasheswithSealedHashing(true)the root depends on the keypublisherholds key Akeyless memberno content keykey holderholds key Asealed pieceschecks each sealed piece byits hash, stores and servesit, and reads none of itfetches from any holder,then openPlain(root)without the key, openPlain refuses: "no content key"INTO GROUP B, UNDER KEY Ba member of Bfetches root Bpieces sealed under key Bshare(root, lease, source)a sealed root: re-sealed as root Bshare(root, lease)a plain root: the same root in Bit calls one of themthe bridgethe key holder, a member of B tooone store serves both groups
Sealed hashing, and a bridge. With withSealedHashing(true) the publisher seals each piece once under the group's key and hashes the sealed bytes, so a member without the key can check, keep, and serve every piece and read none of it. A bridge, a member of two groups with one store, shares a root into the second group; a sealed root is re-sealed under the second group's key and travels there as a new root.

Collections

Use a collection to list many artifacts without replicating a manifest for each. A collection is an AssetCard with access.kind = content-collection that a holder advertises for a named set of roots. It answers the connector SDK's query choreography with pages of manifest summaries, so a registry with thousands of artifacts lists them cheaply.

  • Unreplicated roots. A root published with withReplicate(false) is reachable only that way, and a fetcher asks a holder for its manifest on demand.
  • Per-group listings. A collection lists only roots its group's swarm serves, so a bridge advertises in each group exactly what it shares there.
  • Search by meaning. Its card description names what it holds, so semantic discovery finds "terrain tiles for sector 7".
  • Status. describe(root) says whether a root is replicated, advertised, or both, and the console lists each collection with its row count.

Operator keys

In the starter, agentspaces.content.* turns the swarm on per group. The capability runtime must be on. The keys are:

  • enabled (off by default), space, and escalate-above;
  • piece-size, seed-mode, and holding-lease;
  • max-sessions, max-window, max-fetches, and upload-bytes-per-day;
  • store.{backends, path, quota, cache-external, encrypt-at-rest}.

Blocks below the bound have a store of their own, agentspaces.blocks.*, so a live entry's block survives a restart. Its keys are store (memory or file), path (one directory per group), quota, and max-payload.

In YAML, a node that keeps pieces and blocks on disk, encrypts the pieces, and also serves files where they lie:

agentspaces:
  content:
    enabled: true
    escalate-above: 4194304          # 4 MiB
    piece-size: 1048576              # 1 MiB
    upload-bytes-per-day: 107374182400
    store:
      backends: [file, in-place]
      path: /var/lib/agent/content
      quota: 21474836480             # 20 GiB
      encrypt-at-rest: true
  blocks:
    store: file
    path: /var/lib/agent/blocks

To watch and limit the traffic:

  • The console's content panel shows roots, holders, the store, collections, and fetches in progress.
  • A relay counts the bytes it forwards per frame kind, so an operator sees how much of its traffic is pieces.
  • RelayPolicy.refusingKinds("PIPE_DATA:aspace:cap/content-swarm") keeps pieces off a metered relay.

To wire it by hand:

  • Build the content space first.
  • Build Content.builder(pipes, runtime, contentSpace, peerId).store(...).blocks(...).keyRing(...).authorizer(...).pieceSize(...).build(), and register it as a provider.
  • Give every application space .bulk(new SpacePayloads(content), threshold).

Other languages and hosts

The other ports publish and fetch with the same records on the wire:

  • Python: agentspaces.capabilities.content.
  • TypeScript: capabilities.Content, with a Node FileStore, the browser's OpfsStore, and the Workers R2PieceStore.
  • Clojure: agentspaces.content.
  • Groovy: group.content.

In Python, one member publishes and another fetches:

content = Content(Pipes(peer), Space(peer, "content"), MemoryStore())
manifest = content.publish(data, name="checkpoint.bin")

# on another member
fetch = other.fetch(manifest["root"])
if fetch.wait(600):
    data = fetch.read_bytes()

A dial-only client reaches every holder through its seed acting as a relay. In a browser, connect with a content block, and the resident worker runs the fetch, pushing progress to every tab.

The Spring AI, LangChain4j, and Micronaut hosts offer the swarm to a model as tools: publish_content, fetch_content, read_content, describe_content, and list_content.

Values that changePdtRefPdtRef

An entry never changes. To change a value, an agent writes a new entry and retires the old one, and every reader fetches the whole new value. For a large map or a large file that is wasteful: one changed field re-sends everything. A persistent value fixes that, in the module agentspaces-pdt.

A persistent value is a wide tree of small nodes, each named by the hash of its bytes (a CID). An update copies the path from the root to the change and shares every other node, as Clojure's collections do in one JVM. A reader that holds the old version holds every shared node and fetches only the new ones. That set is the delta.

A MAP AS A TREE OF NODES, EACH NAMED BY ITS HASHroot v1root v2abcc'defgg'PRef headfacts: root v2, base v1swap(m -> m.assoc(id, fact)) copies the path from the rootto the change and links every other node as it was:about log32(n) new nodes, four for a million entriesnew in v2: the deltaa link to a node v1 hasA READER THAT HOLDS v1its node store beforev1abcdefgit asks once for v2, naming v1a holder prunes every subtreeunder v1 and sends the restafter: three nodes arrivedv2c'g'every other node it already heldTHE DELTA REACHES THE OTHER MEMBERS ONE OF THREE WAYSinline32 KiB or less: on the head, by gossippusheddown the gossip tree, under a budgetfetchedthe reader names the roots it holds
A value that changes. A persistent value is a wide tree of small nodes, each named by the hash of its bytes. One assoc writes a new root and the nodes on the path to the change, and the new root links every other node of the old version. A reader that holds v1 receives only the new nodes, inline on the head when they are small, pushed down the gossip tree, or fetched by naming what it holds.
  • PMap and PSet hold keys in a 32-way hash trie. Equal maps have equal roots, however they were built.
  • PVector is an indexed sequence. An append writes one small root node, and splice, insertAt, slice, and concat write only the nodes on the paths they touch.
  • PBlob is a byte sequence cut where the content says and indexed by a tree, so an edit in a large file ships one chunk and a few index nodes.
  • PText is text that several writers edit at once. Their edits merge with no conflict (text and long sequences).
  • PDb is a DataScript database (a database on a ref).
  • Every operation returns a new value and leaves the old one as it was. editor() batches many changes into one delta.

Refs and swap. Identity lives apart from value, as in a Clojure atom. A ref is a named, leased, signed entry (PRef), its head, that points at the current root. deref() returns the value. swap(f) reads the current value, applies f, writes the new nodes, and writes a new head that names the old one as its base.

  • Two writers that swap at once leave two heads. Every reader merges them the same way (key by key for maps, later head whole for vectors and blobs), and the next swap persists the merge.
  • A ref in linear mode takes its head first, so a second writer waits, as @SpaceReduce does.
  • watch delivers each new head, and history(n) walks back through the versions the store kept.
Pdt pdt = Pdt.builder(content, refSpace)
        .store(PackNodeStore.open(Path.of("/var/lib/agent/pdt")))
        .retain(64, Duration.ofHours(1))
        .build();
Ref<PMap<String, Fact>> facts = pdt.mapRef("facts", Codec.of(String.class), Codec.of(Fact.class));
facts.swap(m -> m.assoc(fact.id(), fact));     // one path of nodes travels, the rest is shared
facts.deref().get(fact.id());
Ref<PBlob> table = pdt.blobRef("table");
table.swap(b -> b.append(rows));                // the new chunk plus the index path

Refs in agents. @PdtRef("name") hands a bound class a ref by name, on a field or on a trailing parameter of a verb method. The declared type picks the kind: Ref<PMap<K,V>>, PSet, PVector, PBlob, PDb, or PMap<String, FileEntry> for a directory tree. The binder resolves a parameter's handle once, when the bean binds. A class with a @PdtRef binds only into a group with trees, and the error names agentspaces.pdt.enabled. Spring and Micronaut both register the resolver.

@PdtRef("facts")
Ref<PMap<String, Fact>> facts;

@SpaceTake(space = "findings")
public void record(Finding finding, @PdtRef("ledger") Ref<PVector<Finding>> ledger) {
}

Deltas: inline, pushed, or fetched. A swap's new nodes reach the other members one of three ways:

  • Inline. When the new nodes total 32 KiB or less, the writer puts them on the head itself, so gossip delivers the change and nobody asks for anything.
  • Pushed. A writer built with .push(PushPublisher.Config.on()) sends a larger delta down the gossip tree to the members that follow the ref, under a budget (2 MiB a second, 8 MiB a delta by default). A follower that misses part of it fetches the rest.
  • Fetched. Otherwise a reader asks once for the new root, naming the roots it already holds, and every holder sends only the nodes the reader lacks, over the content swarm.

pdt.stats() counts deltasInline and deltasFetched. Measured on the sim fabric, a 10,000-entry map of 2.2 MB updated by one assoc ships about 4 KiB in two round trips.

Heads renew and retire. A head is a leased entry, and its writer looks after it:

  • The writer renews each live head at half its lease. Every reader judges a head by its renewed lease, so a head stays live as long as its writer runs.
  • When a newer head replaces one, the writer cancels the old head about 2 s later. A head that a fork still walks through stays.
  • Readers skip a cancelled head. When a writer stops for good, its head lapses at the end of its lease, and a follower that holds the value writes it again.

Java, Python, TypeScript, and Ruby behave the same way here, because they all follow the space rules for renewals and cancels.

History and late joiners. Each head links its ancestry, a chain of small version nodes the writer stores beside the value. A member that was away for a week, or a peer that restarted, walks that chain to find the version its heads share, fetches it, and reads the same value as everyone else. retain.{versions, age} (64 and 1 h) says how many versions a store keeps as delta bases.

Sharing a value into a second group. A member of two groups shares a ref's current version with pdt.share(ref, otherGroupPdt), which returns the handle of the same ref in the second group. The second group's facade writes a head of the same name with the same root, so the members of both groups read that version. A bridge that keeps one node store under both groups moves no node. Over two stores, the nodes are copied once, and share refuses when either store is sealed. Only the Java facade shares today, and Groovy calls it as it is.

Blobs and files. PBlob.of(path, store) chunks a file of any size in 64 MiB of heap; of(path, store, previous) shares every unchanged chunk with the earlier version. open(offset, length) reads a range and fetches only the chunks it needs. splice and append return new blobs. TreePublisher turns a directory into a map from path to blob, so a re-publish after ten edits ships ten blobs' deltas and one map path. A blob also carries a BLAKE3 identity, so a reader can check a range of it as it arrives (verified windows).

Opting a space in. A space can escalate its large entries as trees instead of artifacts, with no change to the agents that use it. Set agentspaces.pdt.spaces.<name>.escalate-above (64 KiB is the usual choice). The space hands a payload above the threshold to PdtPayloads, which spills every map, array, or byte string above 4 KiB into a sub-tree and keeps the rest in place; the record's payloadRef is the root. Successive writes of the same record share every unchanged sub-tree, so a @SpaceReduce accumulator that grows to 3 MiB updates by delta. Three things to know:

  • Mixed fleets. A member without the trees parameter never sees a tree message. When any current member lacks it, the writer falls back to the artifact or block path for that write; spaces.<name>.require=true makes that a startup refusal naming the members.
  • No pre-seal. An artifact is sealed before escalation under a fresh nonce, which would defeat all sharing. A tree space records the key epoch on the record and seals nodes as the mode below says.
  • The entry pins the root. The nodes live as long as the entry, as an artifact does.

Micronaut reads the same spaces.<name>.* keys. Until its facade is ready, a writer falls back to the flat swarm, or refuses by name under require.

What each sealing mode reveals. agentspaces.pdt.sealing picks one; the head carries it.

  • group-key (the default under a content key): nodes are stored in plaintext and sealed per message under the group content key. Only key holders hold or serve. Members learn that two nodes are equal; outsiders see nothing.
  • sealed-nodes: the writer seals each node under a key derived from the epoch's content key, and the CID names the sealed bytes. Members without the key, relays, and blind stores can verify, store, walk, and serve the nodes. They learn the shape of a tree (its links, node count, sizes, and epoch) and nothing of its contents.
  • none: for public data and groups without a content key.

In every mode the CIDs, the sizes, the ref's name, and its attrs are visible to members. Node contents are visible only to key holders. The appendix explains how a sealed node stays verifiable.

Configuration keys. Under agentspaces.pdt in the starter (the content swarm must be on):

  • enabled (off by default; builds the facade and advertises trees), space (the ref space, pdt by default), inline-delta (32 KiB), load-timeout (10 s), follow (full or lazy);
  • store.{kind, path, quota, require} (pack, memory, or a NodeStore bean; ~/.agentspaces/pdt). A store past its quota refuses a node by name;
  • retain.{versions, age} (64 and 1 h);
  • sealing (group-key, sealed-nodes, none);
  • refs.<name>.{mode, follow} (multi or linear; full or lazy for that ref alone);
  • spaces.<name>.{escalate-above, require}.
agentspaces:
  content:
    enabled: true
  pdt:
    enabled: true
    store: { kind: pack, path: /var/lib/agent/pdt, quota: 21474836480 }
    retain: { versions: 64, age: 1h }
    sealing: group-key
    refs:
      facts: { mode: multi }
    spaces:
      plans: { escalate-above: 65536, require: false }

A NodeStore bean replaces the store and a PdtMergeFunction bean named for a ref registers its merge. Micronaut reads the same keys through its factory (its ref space defaults to a registered application space named refs, and its sealing to none).

Clojure. The values are real Clojure collections, so get-in, assoc-in, transient, deref, and add-watch work on them. Add a :pdt block to the config map.

(require '[agentspaces.pdt :as pdt])
(def facts (pdt/ref fleet "facts" :map))
(pdt/swap! facts assoc-in [:claims id] claim)
(get-in @facts [:claims id])
(add-watch facts ::log (fn [_ _ old new] (println (count new))))

The appendix explains why a tree, and what a delta costs. The Clojure guide has a worked example.

A database on a refPDb

A db ref holds a DataScript database that every member of the group reads. Use it for state that many peers query by entity and attribute: a knowledge graph, a catalogue, a set of findings with their sources. Example 34 keeps the superfriends graph this way.

  • The database's three indexes (eavt, aevt, avet) are trees of nodes, like every persistent value.
  • A transaction's datoms ride on the head as its tail, so every member applies the same datoms within a gossip round.
  • Past 128 tail datoms, or 30 s after the last fold, the writer folds the tail into the indexes and writes only the changed paths.
  • A restarted peer reads the head's root and its tail and replays nothing. A query reads only the index nodes on its path.
A db REF: A DATASCRIPT DATABASE AS NODESPRef head (v 2, kind db)the root, with the tail's nodes inlinedb rootschema, largest eid and tx, branching 128taildn leaf, datoms in tx orderdn eavta branch nodeleafleafleafdn aevta branch nodeleafleafleafdn aveta branch nodeleafleafleafa datom is [e, a, v, tx]; each index node holds up to 128 of them, in its index's ordera transaction's datomsride on the head, so everymember applies them withina gossip roundTHE WRITER: TRANSACT, THEN FOLDpast 128 tail datoms, or 30 s after the last fold,the writer folds the tail into the indexesand writes only the paths that changed;a restarted peer reads the root and the tailand replays nothingA READER: ONLY THE NODES ON ITS PATHlookup(attribute, value) walks avet: the db rootand one path of index nodes, nothing else;Python, TypeScript, and Ruby read this way,and Clojure runs Datalog over the same nodesexample 34: one company from 9 of 278 nodes
A database on a ref. A db ref holds a DataScript database as a root over three sorted indexes and a tail, all of them content-addressed nodes. Each transaction rides on the head as tail datoms, and the writer folds the tail into the indexes from time to time. A reader loads only the index nodes its query walks.

Clojure writes and queries. DataScript runs where Clojure runs. agentspaces.datascript/datascript-conn returns a DataScript conn whose d/transact! writes the next head:

(require '[agentspaces.datascript :as pdt-ds] '[datascript.core :as d])
(def conn (pdt-ds/datascript-conn system "pdt" "graph"
                                  {:person/email {:db/unique :db.unique/identity}}))

(d/transact! conn [{:person/name "Ada" :person/email "ada@example.org"}])
(:person/name (d/entity @conn [:person/email "ada@example.org"]))   ; on every member

A few rules to know:

  • One writer at a time. A db ref is linear by default. When another writer moves the ref between your read and your write, the conn refuses the transaction with an ex-info holding :agentspaces.datascript/moved, and you retry.
  • Several writers. Set :pdt {:refs {"graph" {:mode :multi}}}. Two heads then merge by datoms: the union of both sides' changes, with a cardinality-one clash settled on the later head and raised as a PConflict.
  • Remote changes. A head another member writes replaces the conn's database, and d/listen! callbacks hear it.
  • Values. Attributes must be keywords. A value is an integer, text, keyword, boolean, byte array, float, UUID, instant, or big integer.

Java. pdt.dbRef(name, merge) returns a Ref<PDb>, linear by default, with a DbMerge for multi mode or null to take the later head whole. PDb gives the indexes (index("avet")), the tail(), and changesSince(base). Datalog runs in Clojure, so a JVM fleet usually runs one Clojure peer that writes and queries, and Java peers that read datoms.

A Java peer reads the datoms of a ref that a Clojure peer writes:

// linear by default; a null merge takes the later head whole
Ref<PDb> graph = pdt.dbRef("graph", null);
PDb db = graph.deref();
db.index("eavt").iterator().forEachRemaining(d ->     // in eavt order
        System.out.println(d.e() + " " + d.a() + " " + d.v()));
// the datoms not yet folded into the indexes
List<Datom> recent = db.tail();

Python, TypeScript, and Ruby read. Their DbReader answers lookup(attribute, value), entity(e), and datoms(index, ...components) over the tree, loading only the nodes a read walks. They run no Datalog. A Python reader that follows the ref lazily:

pdt = Pdt(content, Space(peer, ref_space), store, load_timeout=15.0, follow=FOLLOW_LAZY)
ref = pdt.db_ref(name)
db = ref.deref()
e = db.lookup(attr, value)
found = [[d.e, d.a, d.v, d.tx] for d in db.datoms(index, *components)]

In example 34, a Python reader found one company and its 315 findings in a graph of 13,500 datoms while it held 9 of the graph's 278 nodes.

A store for the fleetContentStoreStorePolicy

A content store is a member that holds bytes for the group, so a value outlives the peer that wrote it. A data agent publishes a table, asks two stores to hold it, and leaves; a reader that joins a day later fetches the table from the stores.

  • A store advertises an AssetCard of kind content-store with its capacity, free bytes, largest object, leases, tier, price, and whether it is blind.
  • A member asks for holding by writing one SignedPin: the root, the copies it wants, the lease, and its own signature. A store takes only a pin its requester signed.
  • Each store that takes the pin fetches the root, holds it, and writes a StoreReceipt. The pin stays takeable until it has as many receipts as copies.
  • A store releases a root when its lease lapses with no renewal. To renew, the requester writes a fresh pin with the same terms.
1 CHOOSE: EACH STORE ADVERTISES A CARD; GOSSIP FILLS THE AD CACHE2 PIN: ONE SIGNED PIN, TAKEN ONCE PER COPY3 PROVE AND REPAIRrequestera data agentcontent spacethe pin and receiptsstore-acontent storestore-bcontent store, blindreaderjoins laterAssetCard, kind content-store: free bytes, tier, pricethe same from store-b, which is blindstoreFor(root, Need.of(0, 2), lease) picks storeswith room; it writes no pin when none fitsSignedPin: root, 2 copies, leasetake the pinfetch the root, hold itStoreReceipt; the pin again, 1 lefttake, fetch, StoreReceiptreceipts(root): twoCHALLENGE: up to 16 random piecesthe bytes, within the deadlinecompare held roots, fetch what is losta pin lapses with its lease; the requester renews by writing a fresh pin with the same terms
A store for the fleet. Stores advertise content-store AssetCards, and gossip carries them into every ad cache. A requester signs one pin for two copies; each store that takes it fetches the root, holds it, and writes a receipt, and the requester can leave. A late reader fetches from the stores and challenges them for random pieces, and two stores compare what they hold after a crash and fetch what one lost.

Turn a peer into a store. With the content swarm and the trees on, set agentspaces.store.*:

agentspaces:
  content: { enabled: true }
  pdt: { enabled: true, store: { kind: pack, path: /var/lib/agent/pdt } }
  store:
    enabled: true
    name: site-a
    capacity: 2TiB
    reserve: 50GiB
    accept-requesters: grant      # or open
    blind: false

The other keys are max-object (64 GiB), lease-default and lease-max (30 and 365 days), copies-max (3), accept-kinds (tree, artifact), tier (hot or cold), challenge-deadline (2 s), and price-per-gib-month. A store refuses to start without agentspaces.content.enabled and agentspaces.pdt.enabled, and names the keys. A StorePolicy bean replaces the policy these keys build.

Who may store. Under accept-requesters: grant, the default, a requester needs the CONTENT_FETCH grant on the root. A store with that policy and no authorizer starts, listens, takes no pins, and says so on its card, until an authorizer shows up. Use open to let every member store.

Ask the stores to hold a root. The facade picks stores from their cards (enough free bytes, the tier, the price, never a store you avoid) and writes one signed pin naming them. It writes no pin when no store fits:

Ref<PBlob> table = agent.pdt().blobRef(REF);
PBlob blob = table.swap(b -> PBlob.of(rows, b.store()));
String root = blob.root();
agent.pdt().storeFor(root, StoreChooser.Need.of(0, 2), Duration.ofDays(1));
List<StoreReceipt> receipts = agent.pdt().stores().receipts(root);   // one per store that holds it

Check that a store holds it. pdt.challenge(root, storePeer) asks a store for up to 16 random pieces of the root, which it must send within the challenge deadline. A store that fails two challenges in a row stops counting toward your copies. A blind store passes a challenge without the key.

Blind stores. A store with blind: true holds no content key. In a group that seals its nodes (sealed-nodes), it verifies, holds, serves, and proves the sealed nodes and reads none of them. A blind store refuses a pin for a group-key tree, since it could read those nodes.

After a crash. Stores compare what they hold with each other, and a restarted store fetches again any root it holds a pin for and lost. In example 34 a store restarted with one pack file cut in half, found its table incomplete, and held it whole again 122 ms after one exchange of 122 bytes.

  • Python: stores.store_for(root, copies=2, lease_s=86400).
  • TypeScript: Stores.storeFor(root, { copies: 1 }, seconds).
  • Ruby: Pdt#store_for, which skips stores that wait for an authorizer.
  • Clojure: pdt/store-pin! and pdt/challenge!.
  • Groovy: pin and status on the group's facade.
  • Spring AI and LangChain4j: the model tools pdt_pin and pdt_store_status.

A platform console that deploys a store refuses a grant store with nothing to authorize its requesters. The appendix explains how stores pin, prove, and reconcile.

Verified windowsPBlob

A blob carries a BLAKE3 identity of its whole content, the same whatever the chunking, and an outboard of hash nodes beside it. The head names both. With them, a reader can read a range of a large blob and check each 16 KiB group of the range as it arrives, before the rest of the blob exists locally. Use it to read a window of a recording, a log, or a dataset.

READ BYTES [off, off + len) OF A LARGE BLOB AND CHECK THEM AS THEY ARRIVEPRef head of the blobpdt.blake3: the identity; pdt.bao: the outboardidentityBLAKE3 of the whole contentoutboard root (bo)hash pairs that chain up to itboboboboboboan outboard node covers up to 512 groups of 16 KiB (8 MiB); the reader fetches only those on its paththe windowchunks of 16 to 256 KiB, cut by contentonly the shaded chunks travelinside the window, group by group:okokokokokokxeach 16 KiB group is delivered only when its hashverifies up to the identity; a group that fails endsthe read with an IOException, after the groups before ita window of W bytes movesat most W + 128 KiB,whatever the blob's size
A verified window. A blob's head names its BLAKE3 identity and the root of an outboard of hash nodes. To read a range, a reader fetches the chunks under the window and the outboard nodes on the window's path, and it hands over each 16 KiB group only when that group verifies up to the identity, before the rest of the blob exists locally.
PBlob recording = pdt.blobRef("recording").deref();
// 40,000 bytes from offset 250,000
try (InputStream in = recording.openVerified(250_000, 40_000)) {
    byte[] window = in.readAllBytes();       // checked group by group
    ...
}
  • A group that does not verify fails the read with an IOException naming it, after the groups before it arrived.
  • A window of W bytes moves at most W plus 128 KiB, whatever the blob's size. A 2 MiB window from the middle of a 64 MiB blob moved 1.055 times the window.
  • PBlob.identity() gives the identity, so two publishers of one file see one identity.
  • The value must carry the identity its head names; a value without one refuses openVerified.
  • Python: open_verified(offset, length) on the blob. TypeScript: pdt.openVerified(root, identity, bao, offset, length, sources). Ruby: read_verified(offset, length) on a blob ref.

In Python, on a blob whose head names its identity:

blob = pdt.blob_ref("recording").deref()
window = blob.open_verified(250_000, 40_000).read()      # offset, length

The appendix explains how a verified window checks each group.

Text and long sequencesPTextPVector

Text. PText is a text that several replicas edit at once, with insert(pos, text), delete(pos, len), and toString(); positions count code points. Two replicas' edits merge by the union of their characters, so both insertions survive in a stable order and the engine raises no conflict. Make each writer's replica id with PText.replicaOf(agentId), and put texts in a map through PText.codec(replica):

Ref<PMap<String, PText>> onA = a.pdt().mapRef(NAME, Codec.of(String.class), PText.codec("alice"));
PMap<String, PText> v1 = onA.swap(m -> m.assoc("doc", PText.empty("alice").insert(0, "ac")));
// Bob, on another member, edits the same text
Ref<PMap<String, PText>> onB = b.pdt().mapRef(NAME, Codec.of(String.class), PText.codec("bob"));
onB.swap(m -> m.update("doc", t -> t.insert(1, "b")));
onA.deref().get("doc").orElseThrow().toString();   // "abc" on every member

In the measured run, two replicas making 1,000 edits shipped about 29 bytes per edit, and the slowest member read the merge in under 80 ms.

Long sequences. A PVector edited in the middle (splice, insertAt) keeps the relaxed shape its edits leave, so an insertion in a million elements ships 8 to 10 nodes and under 5 KB. packed() gives the dense form of the same elements, and equality compares packed roots.

TWO WRITERS, ONE TEXT: THE MERGE IS THE UNIONboth replicas hold "ac"aalice 0calice 1alice: insert(1, "b")aalice 0balice 2calice 1bob: insert(2, "!")aalice 0calice 1!bob 0then, at the same timeaalice 0balice 2calice 1!bob 0every member reads "abc!", and no conflict is raisedeach character keeps its replica's id and a counterand the union keeps both edits in one stable orderA SPLICE IN A LONG VECTORrr rootrr root'vvrvrv'leafleafleaf'an rv node carries z, the sizes undereach child, so an edit in the middleshifts nothing beside its pathone insertion in a million elements:8 to 10 nodes, under 5 KBpacked() gives the dense form
Text and long sequences. Two replicas edit one text at once. Every character keeps an id from its replica, so the merge is the union of both sides' characters in one order, and both edits survive. On the right, an insertion in the middle of a relaxed vector writes a new root, one relaxed node, and one leaf, and links every other node as it was.

Smaller changes to large chunks. When a chunk of a blob changes, a holder can send a small zstd patch against the old chunk to a reader that holds it, so a one-byte edit in a 64 MiB blob ships about 3 KB. The writer keeps these patches with .deltas(true) on the builder, the default except over a sealed store.

Mixed fleets. Members advertise a feature level. Java, Python, and TypeScript advertise pdt=2; Ruby stays at level 1. A writer sends the newer forms (patches, sketches, challenges) only to a member at level 2, and every member still reads what it read before. A peer can also keep each piece of the flat swarm once under its hash, so artifacts that share pieces share them on disk: set agentspaces.content.store.backends: [hash].

Persistent values in other languages

Every port reads and writes the same nodes, checked against the same golden vectors:

  • Python (agentspaces.pdt): maps, sets, vectors, blobs, texts, and refs with swap and deref; db_ref and DbReader; verified windows; store_for; pushed deltas with Pdt(push=True). It advertises pdt=2.
  • TypeScript (the pdt namespace of @agentspaces/client): the same set, with DbReader, openVerified, storeFor, and push reception. It advertises pdt=2.
  • Ruby (AgentSpaces::Pdt): refs with swap; reads of db refs, relaxed vectors (PVector#pack), texts, and verified windows; store_for. It stays at level 1.
  • Clojure (agentspaces.pdt and agentspaces.datascript): refs as Clojure values, datascript-conn, store-pin!, challenge!, text, splice, insert-at, and subvec.
  • Groovy: map and vector operators on the values, swap with a closure, and pin and status on the store.
  • Rust (the agentspaces-pdt crate): map_ref, set_ref, and tree_ref over the content swarm, with inline deltas, and the file share the spacewalk command uses. It has no linear swap and no escalation above 4 MiB yet (what is not built yet).
  • Spring AI and LangChain4j: the model tools pdt_read, pdt_assoc, pdt_history, pdt_pin, and pdt_store_status.

In Python, a ref swaps and reads as it does in Java:

pdt = Pdt(content, Space(peer, "pdt"), NodeStore())
facts = pdt.map_ref("facts")
facts.swap(lambda m: m.assoc("f-1", "the pump runs hot"))
pdt.map_ref("facts").deref().get("f-1")     # on every member

A dial-only reader, such as a Python process that dials one Java peer, reaches the other members through a peer with the RELAY role. A fleet that hosts dial-only readers gives one of its listening peers that role. The language guides show each port with code: Python, TypeScript, Ruby, Clojure, and Groovy.

Keep in mindA root with hashing: plain tells anyone who learns it that the group holds that exact artifact, because the root is a hash of the bytes. Where that matters, publish with sealed hashing: the root then depends on the group's key.
aspace://guide/peering · chapter 14

Peering, identity, and transportsPeerIdentityPeerNode

This chapter covers the bottom layer: how a peer gets an identity, joins a group, and talks over the network. Most applications configure it through the starter and never touch it. Use the API below when you wire a peer by hand or embed it without Spring.

PeerIdentity identity = PeerIdentity.generate();      // or FileKeystore.loadOrCreate(path)
PeerNode node = PeerNode.builder(identity).build();
node.listen(new TcpTransport(), "0.0.0.0:7500");      // and/or new QuicTransport(identity)

GroupRuntime runtime = node.joinGroup(groupAd,
        GroupMembership.Config.defaults(),   // member TTL 45 s, ping timeout 2 s, 2 indirect probes
        seeds);
node.startTicking(Duration.ofMillis(250));   // starts the loop; 250 ms paces only deprecated onTick work

Identity and groups

A peer is one running process with the AgentSpaces library inside it. A group is the set of peers that find each other and work together.

  • Identity. Each peer has an Ed25519 key pair. Its PeerId is the hash of the public key, so the identity survives every address and transport change.
  • Signatures. The peer signs every frame, card, entry, and state transition it emits with that key.
  • Group ids. A group's id comes from a founding text or from a signed founding.
  • A group from a founding text. Every member derives the same id from the same string, and no signed document exists. joinGroup(GroupAdvertisement, ...) joins it.
  • A group from a signed founding. The GroupId is the hash of a document the founder signed. A newcomer who knows only the id asks a seed (a member address it dials to get in) for the document, and checks the answer against the id before joining.
  • Joining a signed group. joinGroup(GroupId, ...) does that check. joinGroup(SignedGroupAdvertisement, ...) serves a peer that already holds the document.
  • Only a signed group can be joined by id. A group started from a text has no signed founding to serve, so an attempt to join it by id times out.
  • Starter properties. These are the founding, join, and founding-document trio of the starter. Discovery covers how a peer finds the seeds to ask.

Membership and topology

  • Membership. Members probe each other, and a silent member drops from the view on its own after its member TTL (45 s by default).
  • Admission. A group admits peers by policy: OPEN, INVITE (the peer presents a founder-signed credential at join), or POLICY (your validator SPI).
  • Rendezvous. Any member may volunteer as RENDEZVOUS: a bigger discovery cache that newcomers ask first.
  • Relay. Any member may volunteer as RELAY: it forwards signed frames verbatim for NAT-restricted peers.
  • Neither role is required. Correctness never depends on either role.
  • LAN discovery. On a LAN, the opt-in multicast beacon replaces seeds entirely.

The appendix explains how membership probing and gossip work.

Transports

A transport is the network protocol one peer uses to reach another. These ship:

  • Loopback. An in-JVM loopback, for tests.
  • TCP and TLS. TLS runs over TCP with the JDK's default protocol set; this binding does not pin a version.
  • QUIC and DTLS. QUIC (RFC 9000) and DTLS 1.2 (RFC 6347).
  • WebSocket and HTTP. WebSocket (RFC 6455, as ws and wss) and the HTTP exchange (http and https).

A peer advertises (transport, addr, priority) endpoints. Dialers try them in ascending priority and skip schemes that no configured transport serves. Peer identity stays with the signed envelopes on every transport.

QUIC

agentspaces-transport-quic carries the fabric's frames over QUIC (RFC 9000) through quiche and Netty's incubator codec. It plugs in through the same Transport SPI as TCP: node.listen(new QuicTransport(identity), address).

  • Build it with the identity. It then presents an ephemeral channel certificate that the peer identity endorses, so the attested mode below works over it. The no-argument new QuicTransport() encrypts and attests nobody.
  • Under the starter, set agentspaces.transport.quic.enabled to true and put the module on the classpath. The starter then builds the identity form. Startup refuses an enabled block without the module.
  • Not under Micronaut. QUIC is not available under Micronaut, which manages Netty 4.2 while the transport pins 4.1.

DTLS

agentspaces-transport-dtls carries the frames over DTLS 1.2 on UDP. It runs on BouncyCastle's DTLS, in pure Java with no native library. Nothing above the transport changes, and an association stays alive when a peer's address changes behind a NAT.

  • Turn it on with agentspaces.transport.dtls.enabled and a bind.
  • Attestation. It presents the same channel certificates as TLS and QUIC and attests in the same modes. A fleet that requires attestation may run on DTLS alone.
  • Without attestation. DtlsTransport.unattested() (property attestation: none) encrypts for fleets that use no attestation.
  • When to choose it. Choose DTLS where QUIC is unavailable (no quiche build for the platform, a validated-crypto policy) or blocked, and on lossy UDP-only links.
  • Certificates travel in clear. DTLS 1.2 sends certificates in clear, so a passive observer learns which PeerIDs talk. Use QUIC or TLS where that matters.
  • No congestion control. There is no congestion control beyond a fixed window.
  • Plain UDP. The bare udp binding in the same module runs over plaintext UDP, for closed test ranges and links already encrypted underneath. It registers only under dev-local or allow-plaintext.

The appendix explains how DTLS is made reliable and survives address changes.

WebSocket and the HTTP exchange

agentspaces-transport-http is how a browser, a Node process, a Worker, or anything behind HTTP infrastructure becomes a member. One Netty port serves both the WebSocket upgrade and the exchange.

  • ws and wss. ws is WebSocket. wss is the same inside TLS 1.3 with the tls binding's identity modes, and it admits a dialer with no certificate (a browser) as unattested.
  • http and https. These are the exchange, for intermediaries that break WebSocket.
  • Allowed origins. The listener admits browsers only from its allowed-origins. An empty list refuses every browser; * is for demonstrations.
  • Session mode. On an unattested link, both ends in session mode run session attestation inside it.
  • Only wss attests. ws, http, and https never attest, so they register under any profile, as tcp does. Startup refuses them under require-attestation.
  • Clients. The TypeScript client dials all four with the runtime's own WebSocket and fetch, and the Ruby client dials all four as well. Python dials tcp and tls and skips them.

The appendix describes the frame layout of each scheme and session attestation.

WebRTC

agentspaces-transport-webrtc and @agentspaces/webrtc carry the frames over a WebRTC data channel. Use it so that two browsers behind one seed, or a browser and a Java peer, talk directly and leave the seed out of the data path.

  • Engines. The Java engine is libdatachannel, a native library per platform. The TypeScript side is the browser's RTCPeerConnection, or node-datachannel on Node.
  • Signalling. Signalling travels through the fleet's own pipes (aspace:cap/rtc-signal): directly when the target is connected, through a relay member otherwise. That relayed signal is the one relayed frame a node under require-attestation admits.
  • Attestation. The channel attests the remote PeerID.
  • ICE servers. No ICE server is configured by default. Only host and mDNS candidates gather until agentspaces.transport.webrtc.ice-servers names STUN or TURN.
  • Bounds. Every bound is a property: offers per peer per minute, candidates per session, bytes per signal, and the 15 s dial. Nothing caps connections.

A node opens a direct channel only after relayed traffic to a member builds up:

  • Relay first. A node never dials a webrtc endpoint from inside a send. Frames to a member it cannot reach take the relay.
  • Then direct. Once more than agentspaces.transport.webrtc.offload.frames-per-minute (30) of them cross a relay to or from that member in a sliding minute, the node dials the endpoint from its loop. It sends directly from then on, so the relay carries none of the pair's frames.
  • If the dial fails. A dial that cannot complete falls back to the relay at the dial bound without losing a frame. The node retries it no sooner than retry-after (5 min).
  • TypeScript. The TypeScript core counts the same way (peer.onRelayed), and @agentspaces/webrtc decides on install.

The appendix explains how the signal travels and attests the remote peer.

Channel authentication

Use attested mode to skip per-frame signatures on links the transport already authenticates. TLS, QUIC, and DTLS present a channel certificate the peer identity endorses. A node that announces itself willing accepts unsigned frames from the peer that channel attests. This is the attested mode of the starter.

  • Mixing is fine. Signed and attested nodes mix freely.
  • The only downgrade costs speed. Forcing signed mode is the only downgrade an attacker can cause, and it costs nothing but speed.

The appendix explains why attested mode saves work.

Enterprise CA mode

Use this mode when you already run a certificate authority. Point the TLS, QUIC, or DTLS binding at a trust store. Peers then attest only when their chain validates to your anchors, with revocation checked against cached CRLs or fetched live.

Under require-attestation, every inbound frame must arrive on a channel attested for its sender. That makes the CA's revocation an authoritative eject from the whole fleet.

Revocation and rotation

Revoke a peer to remove it from the group. A signed RevocationAdvertisement spreads like any other advertisement and reaches late joiners too. A revoked identity is refused at dispatch ahead of every other check, evicted from membership, and its connection closed.

  • Issuing. GroupRuntime.revoke(...) and rotate(...) issue revocations.
  • Rotation names a successor. A self-certifying identity cannot rotate its key in place. So rotation is a revocation that names a successor, and the successor joins and is authorized like any new peer.
  • Enterprise validation. The founder-rooted RevocationValidator is the interface an enterprise deployment replaces.
  • More than peers. Agents, agent keys, channel leaves, and join credentials are revocable too; see revocation.

One loop per peer

startTicking(period) starts the peer's loop. Membership probing, rumour and anti-entropy gossip, replicated-space convergence, and capability protocols each register their jobs with it and bring no timer of their own. Each job runs when it falls due.

  • How layers register. A space, a capability runtime, and the content swarm each register a job with GroupRuntime.onDue(...).
  • Your own timed work. Register it the same way (the node loop).
  • Keep it quick. A job must not block.
  • Failures are contained. A job that throws is logged and cannot stop the loop or the other jobs.

Containment

A misbehaving peer is quarantined automatically. Per-issuer rate limits and bounded strike counters drive the quarantine, fed only by witnessed violations on fresh authenticated frames. Replayed frames and unadmitted peers never strike.

The appendix explains why replays never strike.

The table shows what an HTTP intermediary does to a link. Attestation survives anything that forwards TLS bytes unchanged. It dies at anything that terminates TLS. So a require-attestation fleet uses passthrough or stays off HTTP.

IntermediaryFabric effectAttestationOperator guidance
Layer-4 pass-through (TCP proxy, NAT)nonesurvivesnothing to do
TLS passthrough on SNI (ingress ssl-passthrough, L4 LB)nonesurvives; each end sees the other's channel certificatedial a hostname; the configuration for require-attestation fleets
TLS termination (ingress certificate, L7 LB, CDN)upgrade forwarded; frames flowdoes not survive: both ends read the link as unattested and run session attestation inside itrun ws/http behind the terminator inside a network you trust as far as it; never require-attestation behind termination
HTTP forward proxy (CONNECT)wss/https tunnel through; ws/http may be rewrittensurvives for wssthe JVM's https.proxyHost; browsers use their own proxy settings
Idle-timing proxiesa silent link is cut (often at 60 s)n/athe 30 s ping keeps a WebSocket alive; the long-poll returns within 25 s
Where it livesAssembly code that runs once: a main, a test fixture, or your own bootstrap class. Under the starter you write none of it. The starter’s properties build exactly this, and the PeerNode is a bean you can inject to assert the posture you configured.

Reach for the hand-wired form when you:

  • Embed a peer in something that is not a Spring application.
  • Write tests against a simulated network.
  • Need a topology the properties do not express.
Keep in mindNothing happens until you call startTicking, which starts the loop that runs membership probing, advertisement refresh, and anti-entropy. A peer that joined but never started its loop looks joined and converges with nobody.
  • Join order does not matter.
  • Seeds are a way in. They need not be reachable forever.
  • Close the node when you are done. An abandoned peer stays in other members' views until its membership lease lapses.

Agent keys and certificates, revocation of everything certified, and content encryption have their own chapter: Security.

Relay paths

A relay path is how a frame reaches a member that nobody can dial. The frame passes through RELAY-role members, and it may cross more than one relay. Use it when dial-only members behind different sites' relays need to exchange addressed frames.

The origin computes the path for you and pins it per target for the life of the flow. Every send to that target follows the pin until a hop leaves the view, a signal names it, or the path idles too long. These properties tune it:

  • agentspaces.relay.path-ttl (10 minutes) is how long a path may idle before the pin is dropped.
  • agentspaces.relay.max-path-hops (4) bounds the path.
  • agentspaces.relay.unreachable-signal turns off the unreachable signal (aspace:cap/relay-signal). A relay that drops a frame sends this signal to the origin.

GroupRuntime.hopsTo answers how many relays a frame to a member crosses. The content swarm uses it to prefer direct holders.

The test RelayPathTest runs two kits behind two site relays that both hang off one headquarters relay. It shows a frame and its reply crossing three relays on one pinned path.

The appendix explains how relays advertise, choose, and forward a path.

Time and the node loopPeerNodeGroupRuntimeTimeSourceNodeLoop

Until 0.6.0 every node ran all of its work on a fixed 250 ms tick. From 0.7.0 a node runs on deadlines. This section covers what that means for your code and your operations: the loop, the one time source, loop health and the watchdog, and the older names that still work.

A node does nothing on a fixed beat. Each of its jobs runs when its own deadline comes up, or when a frame or a local change asks for it, and the node sleeps in between. The jobs are probing members, refreshing the node's advertisement, gossip and anti-entropy, each space's sweep and retries, and each capability's rounds. An idle node wakes a few dozen times a minute, not four times a second.

  • Starting it. startTicking(period) starts the loop, and the starter calls it for you. The name is kept from earlier releases. No periodic tick runs behind it.
  • Your own timed work. Register it with GroupRuntime.onDue(name, work). The work receives the monotonic time in nanoseconds, does what is due, and returns its next deadline, or DueWork.NEVER.
  • Never block in it. The work sends, enqueues, or arms something and returns. Hand anything slow to a virtual thread.
  • A deadline that moves earlier. Call wake() on the registration onDue returned, or on the GroupRuntime. The loop asks the work again at once.
  • A deadline on a wall clock, such as a lease expiry: register with onDueWall(name, clock, work).
  • Running everything now. tick() runs every job once and returns. A test that drives a node by hand calls it.
  • Telling the two apart. GroupRuntime.loopRunning() is true on a node whose loop runs, and false on a node a host drives by hand.
AtomicLong nextSweep = new AtomicLong(DueWork.NEVER);
DueWork.Registration sweeper = runtime.onDue("my-sweeper", now -> {
    if (now >= nextSweep.get()) {
        sweepExpired();                                     // quick; never blocks
        nextSweep.set(now + Duration.ofSeconds(30).toNanos());
    }
    return nextSweep.get();                                // or DueWork.NEVER
});

nextSweep.set(0);        // something new to sweep: due now
sweeper.wake();          // ask the loop to run it at once

One time source per node

A node reads every clock through one TimeSource (ai.badmonkey.agentspaces.common.time). It has two kinds of time, and keeps them apart:

  • Wall time (millis(), instant()) is for anything another peer reads: stamps, leases, and expiries. It may step either way.
  • Monotonic time (monoNanos()) is for every local period, such as the next probe. It never goes backwards.
  • A wall step of more than 1 s against the monotonic clock is told to onWallStep listeners, so deadlines on the wall clock are asked again.
  • A late wake is a timer that fires more than 30 s late (onLateWake). The node treats it as a wake from sleep (waking from sleep).
  • In production the node uses TimeSource.system(), one per process, and you set nothing.
  • In a test, give the node a VirtualTime from agentspaces-test-support. Time then moves only when the test advances it, so a test never waits out a real timer (test support).
VirtualTime time = VirtualTime.create();                   // agentspaces-test-support
PeerNode node = PeerNode.builder(identity).clock(time).time(time).build();
// ... listen, join ...
node.startTicking(Duration.ofMillis(250));                 // starts the loop
time.advance(Duration.ofSeconds(30));                    // thirty seconds of protocol time, at once

Deprecations and their replacements

Code written for earlier releases keeps working. Move it when you next touch it.

deprecated in 0.7.0what it does nowuse instead
GroupRuntime.onTick(Runnable)its work still runs every tick-millis (250 ms) while the loop runs, and on each hand-driven tick()GroupRuntime.onDue(name, work), returning the next deadline
GroupRuntime.tickPeriod()the period startTicking was givenGroupRuntime.loopRunning()
CapabilityProvider.requiresTick(), or an override of tick()the provider is stepped every 250 ms, the older wayimplement DueCapabilityProvider (custom capabilities)
CapabilityProvider.driverCadence(Duration)still told the 250 ms an older provider is stepped ata DueCapabilityProvider keeps its rules in time
@OnEstimate(settleTicks = n)n rounds of 1 ssettle = "PT40S" (@OnEstimate)
EmbabelBinder (for removal)binds the bean through the facadeAgentSpaces.bind(bean); the starter binds every @Agent bean (the second generation)
AgentSpacesProperties.Transport.getQuic()returns the QUIC block as its 0.6.0 typequicBlock()
Rust PeerEvent::GaveUpnever sent, since a peer never stops redialing; kept one release so a match on it still compilesPeerEvent::Unreachable, a reconnect window with no link (Rust)

Three settings changed meaning or stayed as they were:

  • agentspaces.tick-millis (250) now paces only the older tick-driven work in the table. It no longer sets how often a node runs. A deployment that set it to another value now runs the protocol's timers at their 250 ms values.
  • The ordered log does not follow the key either. A started node's Raft election timeout is 1.25 to 2.25 s and its heartbeat 250 ms, whatever tick-millis says.
  • agentspaces.coalesce-millis (20) is unchanged: frames to one peer within the window travel as one batch. The node arms its flush timer only while a frame waits.

Threads

  • The loop runs on a small pool of platform threads per process, agentspaces-loop-N, apart from the virtual threads your agents run on. It holds one thread at idle and at most min(8, max(2, cores / 2)).
  • One timer thread (agentspaces-timer) and one watchdog thread (agentspaces-watchdog) serve every node in the process.
  • Everything else, your handlers included, runs on virtual threads.
  • A build-time test fails the core's build on any new platform thread, fixed-rate schedule, or raw clock read that its allowlist does not name with a reason.

The watchdog and loop health

The watchdog checks every loop every 2 s, from outside it. When a loop has stopped, it restarts that loop without losing queued work.

  • loopHealth() on the PeerNode reads OK, DEGRADED (a job backed off after repeated failures, a job moved off the loop after repeated slow runs, or the node slowed under load), or DOWN (escalated).
  • Escalation follows three restarts of one loop within 10 minutes, or a job stuck for 2 minutes. agentspaces.watchdog.escalation chooses what happens.
  • report (the default) logs an ERROR, turns the health DOWN, and under Spring turns liveness BROKEN, so your supervisor restarts the process.
  • exit closes the node and exits the process with status 70. Use it on a host with no liveness probe.
  • Hung handlers. The watchdog names an @OrderedTake handler that has held its entry for a minute. Set agentspaces.watchdog.hold-limit to stop renewing a handler's take after that long, so another member takes the entry. It is unset by default.
  • loopStats() gives the counters: runs, wakes, late runs, slow runs, restarts.
  • onLoopHealth(listener) hears each change of the health. slowParticipants() names the jobs that ran over 100 ms, and logLoopTrace() logs the loop's last runs, for a loop that looks late or stuck.
  • Under Micronaut, the same health is the /health/liveness indicator (management). Under LangChain4j, FleetRuntime.loopHealth() reads it (time and loop health).

Under load

  • A job that falls due while the loop is busy runs next. That is normal, and loopStats() counts it.
  • The pool grows by a thread when runs wait, and a thread idle for 60 s ends.
  • At the pool's maximum, with runs still late, the node slows its purely local work by 2, then by 4. It renews its leases and re-issues its advertisements first. Its probes, its own keepalive, gossip, and the Raft heartbeat never slow.
  • Tuning is per process, and most deployments set none: agentspaces.loop.pool-max (0 for the default), .pool-idle-millis, .grow-lateness-millis, .stretch-lateness-millis, .stretch-cap, and agentspaces.watchdog.period-millis with its siblings. Each binds from YAML and also works as a JVM system property; a YAML value wins (which keys bind from YAML).

The appendix explains how the loop, the watchdog, and the slow-down work.

TTLs, the member TTL, and dial-only peers

A TTL is how long something stays valid unless it is renewed. Each renewal is a frame, so a short TTL makes a noisy fleet. The core keeps its TTLs at 60 s or more, unless there is a stated reason.

  • The member TTL is how long a silent member stays in this node's view. It is 45 s for a member that keeps itself alive, which every Java member does.
  • A member heard only through probes, such as a dial-only TypeScript, Python, Ruby, or Rust peer whose link another member holds, gets the larger of 45 s and 1.5 times this node's quiet probe cycle: 54 s at ten members, 66 s at twelve, 90 s at sixteen.
  • This node's own keepalive does not change. It still probes and refreshes its advertisement as a 30 s TTL needs, so members of older releases and other languages, which judge by 30 s, drop nobody early.
  • To set it, pass a TTL to GroupMembership.Config. A configured TTL replaces the 45 s floor, and the node keeps its own keepalive on that TTL.
  • Dial-only peers are reached through their seed. A dial-only peer names the member it dialled in its advertisement, and every other member sends its probes for that peer through that member. There is nothing to configure.
  • Keep a dial-only peer's seed up. If the seed goes silent, every view drops the peer within the member TTL plus one probe cycle.

The TTL floor

  • At start, a configured TTL, lease, or expiry under 60 s logs a warning that names the key. A value equal to the shipped default never warns.
  • agentspaces.ttl.strict=true refuses to start instead. Set it on production hosts.
  • To keep a short value on purpose, name its key in agentspaces.ttl.expert-overrides with a reason. On a bound method, put @TtlOverride(reason = "...") on the method instead.
agentspaces:
  ttl:
    strict: true
    expert-overrides:
      "[agentspaces.relay.path-ttl]": "a lab fleet that re-pins its relay paths quickly on purpose"

The appendix explains why the member TTL grows with the group and how a probe reaches a dial-only peer.

Membership status, retirement, and readinessPeerNodePeerNode.MembershipStatus

A member that goes silent drops from the view after its member TTL. The node then keeps trying to reach it, and it tells you where it stands in each group:

  • membershipStatus(groupId) on the PeerNode returns the group's state, when it began, the members in view, the lost members with their next retry, and the retired members.
  • onMembershipStatus(listener) hears every change of state. The listener runs on the node's loop and must be quick.
statewhat it means
JOININGno member yet since joining; the seeds and the locator are still being tried
CONNECTEDmembers in view, none lost
DEGRADEDmembers in view, and some lost ones being retried
RECONNECTINGevery member lost for less than two minutes; lost members, seeds, and the locator are retried
LAST_RESORTnobody for two minutes or more; post-retirement is trying the retired members
ISOLATEDnobody for two minutes or more, and nothing left to try: out of service in this group
ALONEno member and nothing to reach: no member ever, no seed, no locator (a sole founder, or a one-node setup)
node.onMembershipStatus(status -> {
    if (status.state() == PeerNode.MembershipState.ISOLATED) {
        System.err.printf("cut off from %s: %d lost, %d retired%n",
                status.group(), status.lost().size(), status.retired().size());
    }
});
PeerNode.MembershipStatus now = node.membershipStatus(runtime.id()).orElseThrow();

Lost members and retirement

  • A lost member is retried after 5, 10, 20, and 30 s, then 1, 2, and 5 minutes, then 5 s again, each wait spread by up to 10 % either way. At most eight lost members are dialed per round.
  • It retires after agentspaces.retirement.after (24h) without an answer. It goes onto the retirement list, which the node keeps in its state directory beside its admission memory. A fresh card from that member, or its revocation, takes it off the list.
  • Without retirement (agentspaces.retirement.enabled=false), a lost member is retried for ten minutes and then forgotten.
  • Post-retirement (agentspaces.post-retirement.enabled=true, off by default) makes the retirement list a last resort. When a group's view has been empty for two minutes and nothing else brought anyone back, the node introduces itself to retired members' last addresses.
  • Hand-wired, the same settings are PeerNode.Builder.retirement(boolean), retireAfter(Duration), postRetirement(boolean), and stateDirectory(Path).

Readiness

  • Under the Spring starter, readiness turns REFUSING_TRAFFIC while the node is ISOLATED in any group, and back to ACCEPTING_TRAFFIC once no group is. A load balancer then stops sending work to a node that cannot reach its fleet.
  • Liveness is never touched by membership, so an orchestrator does not restart a node only because its fleet is gone.
  • To turn it off, set agentspaces.health.refuse-traffic-when-isolated=false.

The appendix explains why lost members retire and why isolation touches readiness, not liveness.

Seeds, wakes, and takes

A node that joins through seeds keeps a link to one of them. These rules decide which seed it dials, how long it waits after a link drops, and what it does when the machine wakes from sleep. There is nothing to configure.

  • Seeds in list order. A round of dials starts the seeds 250 ms apart, in the order you listed them. A refused dial starts the next one at once.
  • Dials never hold the node. Each dial runs on a virtual thread of its own. A seed whose address swallows the connect costs the round 250 ms, not the 5 s connect timeout.
  • The first to answer wins. The node keeps the first seed that sends a verified frame. It closes the links still waiting and never dials the seeds not yet started. At most 16 dials wait at once.
  • The seed just lost goes last. After a seed drops, the next round tries the other seeds first.
  • The redial table. Between rounds the node waits 5, 10, 20, then 30 s, then starts again at 5 s. Each wait is spread by up to 10 % either way.
  • What restarts it. A link that held for 5 s or more: when it drops, the node redials at once and the table starts over. A shorter link waits the next step. Joining alone restarts nothing.
  • It never gives up. The node redials until you close it. A node with no seeds and no locator dials nothing.
  • New seeds from a locator join the round under way. They do not wait for the next step of the table.
  • A lost member is tried again after 5, 10, 20, and 30 s, then 1, 2, and 5 minutes, then 5 s again, each wait spread by up to 10 %. This goes on until it answers or retires, 24 h after the loss.
  • A seed that was a member is dialled by the rounds alone while nobody is in view, not also by the lost-member retry.
  • A silent seed. A node PINGs a seed it dialed and has heard nothing from for 45 s, whether or not it also listens. If nothing arrives within 2 s, it closes the link and fails over. A node that only dials out does the same on every link it dialed.
  • Bytes still arriving count. A seed sending a large frame over a slow link is answering. Its bytes keep the link open before the frame is whole.
  • A node that only dials out answers its own seed's anti-entropy as any member does. Asked by another member, it answers only for the entries where its own claim lost a race, so the winner can learn its completion. Nothing else it holds is sent.
  • seedLinkStats() on the PeerNode counts the dials, the late links closed, the PINGs, the silent links, and the wakes.

Waking from sleep

A laptop that sleeps stops its monotonic clock, but leases and expiries run on the wall clock. So a wake is checked at once rather than at the next timer.

A wake is a jump of the wall clock past the monotonic clock of more than 30 s, the keepalive bound. A frozen process is a wake too: a timer that fires more than 30 s late with no jump of the wall clock (a stop signal, a long GC or VM pause). Every client uses the same bound.

  • The redial table starts over.
  • With a link up, the node PINGs its seed. No answer within 2 s means the node fails over at once.
  • With no link, it dials at once.
  • Members are probed before they are judged. A member the node has not heard from for longer than the member TTL only because the node was frozen gets a PING, not a drop.
  • A take your @OrderedTake handler holds is checked at once. It has lapsed when its claim is no longer this node's (another member's claim won the entry) or its lease has run out on the wall clock. A take that has not lapsed is renewed at once. A lapsed take is never renewed again, and the handler's result is dropped: nothing is completed and nothing is written. binder.lateTakes() counts these.
  • The hold limit (agentspaces.watchdog.hold-limit) counts only time awake, so a sleep does not use it up.

Take rules

  • A take that cannot win is refused. Under LEASE_RACE and AUCTION a take publishes its claim, waits the space's settle window (200 ms by default), and wins only if its claim is still live. A take lease that is not longer than the settle window would always have lapsed by then. So take throws IllegalArgumentException at once, naming both values. Leave a margin above the window, since a busy machine wakes a take late.
  • A held take can lapse. It has lapsed when TakenEntry.held() is false, because another member's claim displaced it, or when its lease has ended on the wall clock.
  • A result after the lapse does nothing. It completes nothing and writes nothing. AgentBinder.lateTakes() counts these, and a connector's held operation follows the same rule (ConnectorRuntime.lateTakes()).

Races and advertisements

  • When two takers race and one loses, the winner asks the loser for its completion at once, then after 1, 2, 4, 8, and 16 s. The loser offers its claim again on the same kind of back-off. Both wait on the monotonic clock, so a clock step neither stalls nor rushes them.
  • A space's advertisement is re-published at two thirds of its TTL (10 minutes of the default 15), and at once after the clock jumps forward. A space stays findable for as long as it runs.

The appendix explains why the waits cycle through a fixed table and why a wake is checked at once.

aspace://guide/security · chapter 15

Security

Use this chapter to decide who may join your fleet, act in it, and read its data. Everything in AgentSpaces is signed. Most of what you decide about security is who holds which key, for how long, and who may take it away.

The chapter covers:

  • The trust model: what peers and agents prove.
  • The security levels, from a laptop to a regulated fleet.
  • Where keys live.
  • How agents get certificates.
  • Revoking anything that was certified.
  • Content encryption.

Each section names the cost of its guarantee.

The trust model in one page

This section explains what a signature proves in AgentSpaces, and what it leaves to other checks.

  • Peers are keys. A PeerId is the hash of an Ed25519 public key, so a peer is whoever holds that private key. No registry, no CA required.
  • Peers sign what they emit. Every advertisement, record, claim, and state transition a peer emits carries its signature, and so does every frame. Two cases skip the frame signature: a link whose peer is attested (frames ride bare there), and dev-local (a MAC under the session key after one signed hello).
  • Agents are names on a peer. An AgentId is <peerId>/<localName>. By default the peer signs for its agents, and a reader trusts the peer's labelling: PEER_ASSERTED.
  • Agents can have keys. Give an agent a key of its own, certified by its peer, and the agent signs its own records, claims, and transitions: AGENT_ATTESTED. Readers see which through Space.Issued.attestation().
  • What entry signatures prove. A record signature proves who wrote an entry. A claim signature proves who took it. A state signature proves who renewed, cancelled, or completed it, so a forged completion cannot delete work.
  • What channels and encryption prove. Channel attestation proves which peer is on the other end of a TLS or QUIC link. Content encryption decides who can read a payload.
  • What none of them decide. A signature proves who acted, never that they were allowed to. Eligibility is the Authorizer's question (profiles and authorization), and admission is each space's (space admission).
  • An attested agent acts only as itself. Once an agent signs with its own key, its peer can no longer act in its name: every renewal, cancellation, and completion of that agent's work must carry the agent's signature, or receivers refuse it.

Security levels

A security level is how much protection a node gives, from a laptop demo to a regulated fleet. Each level adds a guarantee and a cost. Pick the lowest level that covers your threats.

  • Mixing levels. You can mix nodes of adjacent levels in one fleet. Traffic between them gets the lower level's guarantee.
  • Except under require-attestation. It refuses nodes of lower levels outright.
LevelHow you get itDefends againstDoes not defend againstChoose it when
dev-localsecurity.profile: dev-localForged frames, records, and transitions: records, claims, and transitions stay signed, and after one signed hello per connection each frame carries a MAC under the session keyEavesdropping; anyone who can reach the port joins an OPEN groupA laptop, a test, a demo
signed over TCPtransport.tls.enabled: false under a non-dev profileThe same, with grants narrowing who may do whatEavesdropping; traffic analysisA trusted network where TLS is somebody else's job
attested channelsmtls (the default): TLS with identity-endorsed certificates (QUIC and DTLS too, from their listener blocks; peering)Eavesdropping and tampering on the link; frames ride bare on links whose peer is attestedA stolen peer key; an insider who is a legitimate memberMost fleets: no PKI to run, full link security
enterprise CAtransport.tls.trust-store plus require-attestation: trueUnenrolled peers: only CA-issued leaves attest, and the CA's revocation ejects a peer fleet-wideA compromised CA; an enrolled insider until revokedYou already run a CA and want joining to need enrollment
identity providermtls-oidc or zero-trustUnauthorized operations: each privilege needs a token scope from your IdPA stolen token, for its lifetimePrivileges must follow your directory, per operation and scope
Keep in mindzero-trust signs every frame on every hop even over attested links. That is about a thousand times the cost of serializing the frame, so it is the right setting only where you do not trust your own relays.

Keys and where they liveFileKeystorePeerIdentity

This section lists each key a peer holds and the property that says where it lives.

  • The peer key. agentspaces.keystore: /var/lib/agentspaces keeps peer.key (PKCS#8, mode 0600) and peer.pub (raw 32 bytes). Without a keystore every start is a new peer.
  • Safety checks. The files are written atomically. A half-written pair is refused with a message naming both files, and a private key that does not sign for the public file is refused.
  • Back it up. Back the directory up as you would a TLS private key. A peer key cannot be rotated in place, so you replace it by revocation with a successor (below).
  • Agent keys. agentspaces.identity.agent-keys: subordinate gives every bound agent a key of its own.
  • Keeping agent keys. Add agent-keystore: ./agent-keys to keep them across restarts at <dir>/<peer-id>/<agent>/agent.key. Without the keystore an agent gets a fresh key on each start. Its old records stay verifiable, and it has a new key from then on.
  • Agent names. Agent names that could escape the directory are refused, never sanitized.
  • Other languages. Python and TypeScript peers read and write the same signing-key layout (agent.key, agent.pub). The X25519 files are Java-only.
  • Encryption keys. Each peer also holds an X25519 key (peer-x25519.key beside the peer key), used only to receive content keys. The signing key never enters a decryption path.
  • Agent encryption keys. A starter-built subordinate agent gets its own X25519 key, certified alongside its signing key, and so does one built with the encryptionKeys overload of renewingSubordinate. A key holder can then hand a content key to the agent itself.
  • Your own key store. To keep keys in an HSM or a secrets manager, declare an AgentIdentityFactory bean returning your own AgentIdentity: anything that can sign and present a certificate will do.

Agent certificates

Give an agent a certificate of its own when you need to know which agent signed something, and not only which peer. A subordinate agent's certificate is AgentCertificate(agent, agentPublicKey, issued, ttl, peerSignature[, encryptionPublicKey]), signed by its peer. Only the peer an AgentId names can issue one.

# application.yml: every bound agent signs as itself
agentspaces:
  keystore: /var/lib/agentspaces
  identity:
    agent-keys: subordinate
    agent-keystore: /var/lib/agentspaces/agents
    agent-certificate-ttl: 24h
// by hand: a renewing identity over a fixed key, re-certified at half-life
AgentIdentity auditor = identity.renewingSubordinate("auditor", agentKeys, encryptionKeys,
        Duration.ofHours(24), InstantSource.system());
Space findings = replica.as(auditor);   // replica is a ReplicatedSpace: as(...) is on the concrete class          // writes, takes, and completions sign as the auditor

// examples/example-13-signed-agents: who said it, and how strongly the fleet can hold them to it
for (Space.Issued<Finding> issued : reader.findings().readAllIssued(Template.of(Finding.class), 100)) {
    System.out.println(issued.issuer().encoded() + " (" + issued.attestation() + ")");
}
  • When agents get certificates. At bind time.
  • From the starter. The starter's factory issues them when agent-keys: subordinate.
  • From your code. Use your own AgentIdentityFactory bean, the facade's third constructor argument, or PeerIdentity.renewingSubordinate(...) by hand.
  • From other languages. The Clojure bindings take :agent-keys :subordinate, and the Python and TypeScript clients have renewing_subordinate / renewingSubordinate.
  • Old signatures stay valid. A receiver judges a certificate at the moment the thing it certifies was signed. History therefore stays verifiable forever: a late joiner months later still accepts an agent's old findings. A certificate's expiry only stops new signatures.
  • The signing time must fit. A record's issue stamp, a claim's stamp, or a transition's signedAt must lie in [issued, issued + ttl). It may lead the receiver's clock by at most the HLC drift ceiling of ten minutes.
  • Renewal. A renewing identity keeps one key and re-issues its certificate at half-life, lazily on the next signature. It keeps its last 256 certificates so a long-held claim stays certifiable. The starter's subordinate agents renew; nothing to schedule.
  • A stolen key can back-date. A stolen agent key can sign with an old stamp, inside a window that was valid. Revoke a stolen key with key-compromise (next section).

The appendix explains how certificates are signed and why back-dating is possible.

OptionAttestationCostUse when
peer-signed (default)PEER_ASSERTEDNone; the peer's word names the agentAgents of one peer trust each other and nobody audits them separately
fixed subordinateAGENT_ATTESTEDOne certificate; new signatures stop when it lapsesShort-lived jobs and tests (identity.subordinate(name, issued, ttl))
renewing subordinateAGENT_ATTESTEDA new key each startLong-running agents whose identity is the process
persisted renewingAGENT_ATTESTEDA key file per agent to protect and back upAn agent's identity must outlive restarts: audit trails, per-agent grants, per-agent key wrap

Revoking anything that was certifiedRevocationView

Revoke a peer, an agent, an agent key, a channel leaf, or a join credential when it must stop acting in the fleet. A revocation is a signed advertisement that reaches every member, late joiners included. A member holds it for as long as it runs; its TTL bounds re-gossip, never the revocation.

  • At most 4,096 targets per registry. There are two registries, one for peers and one for everything else certified. Beyond the limit, a registry refuses a new target with an error in the log. It never evicts a stored revocation to make room.
  • One record per target. Exactly one record per target survives, chosen by authority first: the founder, then a CA-rooted record with evidence, then an agent's own peer, then anyone your validator admits. A later statement from someone less authoritative never erases the founder's.
TargetIssued byCallEffect
a peerthe founder; revoke also from any member carrying CA evidence (founder-or-ca), while rotate stays with the founderruntime.revoke(peer, reason); rotate(old, successor, reason)Refused at dispatch, evicted, its link closed; its entries are refused by replicas that do not hold them
an agentits own peer, or the founderrevokeAgent(agent, reason)Every key of the agent, under the freeze rule
an agent keyits own peer, or the founderrevokeAgentKey(agent, key, reason)Only that key at receivers; a replacement key of the same agent still verifies. Locally the agent is unbound until it restarts with a new key
a channel leafthe founderrevoke(Target.x509Leaf(...), reason, null)Every link presenting that certificate is cut, now and on each later handshake
a join credentialthe founderrevokeJoinCredential(credential, reason)Admits nobody again; the member it admitted is evicted

What a revocation does

  • The freeze rule. What a replica already holds stays.
  • Under key-compromise. Nothing the target signs is accepted from then on, whatever its claimed time, because a stolen key can back-date.
  • Under any other reason. Under retired, superseded, privilege-withdrawn, or unspecified, signatures made before the revocation's effective instant still verify. A late joiner receives the agent's history and nothing after.
  • Claims, under any reason. Claims are refused, so a revoked holder's take lapses and the entry returns to the space.

Where it is enforced

  • Space merges and the ordered log.
  • Discovery: a revoked agent's cards are purged.
  • Key wrap: a revoked agent is served no key.
  • The vote tally: its ballots stop counting at the next recount, so a decision can reopen.
  • Each group's authorizer.
  • The local node: a revoked local agent is unbound, and the node refuses to write or take as it.

CA-rooted revocation

Use this when your CA's CRLs should eject peers. Set transport.tls.revocation-validator: founder-or-ca. The node re-reads its CRLs every crl-refresh (5m).

  • Revoking reasons. A CRL may revoke a connected peer's leaf for keyCompromise, cACompromise, privilegeWithdrawn, cessationOfOperation, or unspecified. The node then cuts the link and roots a peer revocation itself, carrying the chain and the CRL as evidence.
  • Other members accept the evidence. Any member running founder-or-ca over the same anchors accepts it on the evidence alone, judged at the revocation's own issue time. So even a member without a fresh CRL converges.
  • The default ignores it. A member on the founder-only default ignores it.
  • Other CRL reasons. Any other reason (superseded, affiliationChanged, certificateHold, aACompromise) only stops the leaf from attesting.
// a compromised agent: refuse everything its key signs, from now on
runtime.revokeAgentKey(agent, agentPublicKey, CredentialRevocation.KEY_COMPROMISE);
// a decommissioned agent: keep its history, accept nothing new
spaces.group("fleet").revokeAgent(agent, CredentialRevocation.RETIRED);

Playbooks

  • A lost laptop. The founder revokes its peer with rotate(old, successor, "lost") once the replacement has a key, or revoke at once if not. The peer revocation already refuses everything its agents sign, so no per-agent revocation is needed. Then rotate the content key so it reads nothing new.
  • A compromised agent. Its peer revokes the agent key with key-compromise, then gives the agent a fresh key (delete its keystore entry and restart). Rotate the content key if the agent held it.
  • Decommissioning a node. Revoke its agents as retired so their history stays and nothing new lands, then let its membership lease lapse. Revoke the peer only if its key may outlive the node.

Who is the founder

Several actions above belong to the group's founder: peer, channel-leaf, and join-credential revocations. So does a content-key rotation without a key-rotator grant. Who the founder is depends on how the group started:

  • membership: open, the starter default. The group has no usable founder. The starter signs its advertisement with a throwaway key it generates and does not keep. So no peer can issue these revocations, and the lost-laptop playbook has nobody to run it.
  • membership: invite. The founder is the peer named by groups[].founder, or this peer when none is named.
  • Outside the starter. A group founded in code with a kept founder key (PeerNode.joinGroup(SignedGroupAdvertisement, ...)) has one too.
Decide earlyDecide this before the fleet holds data. An open starter group has no founder to run the actions above.

An open starter group can still use two settings in place of a founder:

  • transport.tls.revocation-validator: founder-or-ca lets CA evidence revoke a peer. It needs the enterprise-CA trust-store.
  • security.grants.key-rotator names the peers that may rotate the content key.

An agent's own peer can revoke its agents and agent keys without a founder.

Keep in mindRevocation is eventually consistent. A member that has not yet heard of it still accepts the target until anti-entropy delivers it, typically within a few gossip periods.
  • Lost history under key-compromise. A late joiner never sees the compromised key's history; that is the cost of the guarantee.
  • Other languages. Python and TypeScript peers apply peer, agent, and agent-key revocations. CA-rooted ones are Java-only for now.

Content encryption and rotationGroupKey

Encrypt a group's payloads when some members, or the relays that serve the group, must not read them.

  • Content keys. A group's content-key seals every payload with AES-256-GCM. Members without the key still verify, store, and forward everything and read nothing. That lets relays and rendezvous peers serve a group they may not read.
  • Handing out the key. The key-wrap capability hands the key to members your authorizer permits as KEY_HOLDER, sealed to each member's X25519 key.
  • Epochs. Each group has one ring of numbered keys (epochs), shared by its spaces. A rotation mints the next epoch with a signed proof and a cutover instant. Writers switch at the cutover, and readers open each record with the epoch it names.
  • Who may rotate. Members install a new epoch only from the founder or a peer granted key-rotator (under the OIDC profiles, the aspace:key-rotate scope), whoever relays it.
  • The same grants everywhere. Every member must carry the same key-rotator grants, because each member vouches for rotators by its own configuration.
  • How to rotate. Configure groups[].content-key-rotation.rotate-every to rotate on a schedule, or call rotateContentKey(delay). With a keystore, the ring survives restarts.
  • Rotate on time. One key is good for about 232 encryptions, and every writer in the fleet shares that budget. Rotate by period, chosen so the whole fleet's write rate stays well below the bound. The appendix explains where the bound comes from.
  • Per-agent key wrap. A subordinate agent with a certified X25519 key can ask for content keys as itself (requestAs). The holder then judges the agent itself rather than only its peer, and seals the key to the agent's own key, so a sibling agent on the same peer learns nothing.
  • What rotation can and cannot do. Rotation is what denies future reads. An agent or peer revoked or no longer granted gets no epoch minted after its removal, but it keeps whatever epochs it already held, and old entries are not re-encrypted.
agentspaces:
  security:
    grants:
      key-rotator: ["<rotator peer id>"]       # the same list on every member
  groups:
    - name: research-fleet
      content-key: "<base64 of 32 bytes>"
      content-key-rotation:
        rotate-every: 30d                 # only on a peer that may rotate
        writer-grace: 1h                  # a writer missing the new epoch stops sealing after this

Things to think about

Check these points before a fleet goes to production, then use the checklist for your level.

  • Clocks. Certificates and revocations are judged against hybrid logical clocks with a ten-minute drift ceiling. Keep NTP running; a node whose clock runs more than ten minutes ahead has its agent signatures and revocations refused, and one running far behind sees fresh certificates as not yet valid.
  • Mixed versions. Upgrade every node before turning on agent-keys: subordinate or rotation. An older node cannot verify agent-signed states or epoch-tagged records and drops them. A fleet that never opts in is unaffected; the appendix explains why.
  • Plaintext metadata. Encryption covers payloads only. Entry types, tags, issuers, leases, and timing are visible to every member, encrypted group or not. Do not put secrets in tags.
  • Accepted risks. The design accepts four risks: Sybil exposure of OPEN groups, the back-dating window, metadata visibility, and an insider's reach until revoked. Know them before a security review.
LevelChecklist
dev-localNever on a shared network; use an INVITE group if the port is reachable
attested channelsSet keystore so the PeerId is stable; back up peer.key; set grants for privileged operations (raft-voter, key-holder, key-rotator, directive-issuer)
with agent keysagent-keys: subordinate and an agent-keystore; per-agent grants by AgentId where agents differ in privilege; a revocation runbook for agent keys
enterprise CAtrust-store, crls, require-attestation: true; revocation-validator: founder-or-ca so the CA's word ejects; a CRL publication cadence shorter than crl-refresh
encrypted groupsDistribute the epoch-0 key out of band; enable content-key-rotation with a rotate-every and identical key-rotator grants (or the aspace:key-rotate scope under OIDC); a keystore on the rotators
identity providerShort token lifetimes with token-file refresh; scopes per operation; remember revocation still applies on top of a valid token

Guardrails

agentspaces-guardrail (v0.1.24) is a small module with no dependency beyond the JDK: the GuardrailProvider SPI (check(kind, content, context) returning pass, refuse, redact with the replacement, or quarantine), the GuardrailPolicy and GuardrailFinding records, a built-in provider (prompt-injection patterns, personal-data classes, term and domain lists, a schema check against a field list), and Guardrails.apply, the one evaluation path: the policy's checks in order, a throwing or slow provider yielding the policy's onError. A gateway applies a policy to prompts and completions; a door applies it to entries written in named spaces; a peer that advertises aspace:cap/guardrail offers checks to others. The core keeps no content and sends nothing anywhere; a vendor adapter behind the SPI does the calling.

aspace://guide/console · chapter 16

The fleet consoleDirectiveGateConsoleViewCustomizer

The fleet console is a read-only peer that shows you the whole fleet. Turn it on for any fleet somebody has to operate. It serves:

  • A web UI at /, in a single file.
  • A HAL+JSON API under /api/v1, walkable from the root by any hypermedia client.
  • An SSE activity stream at /api/v1/events.

All of it is derived from the replicated coordination state, with zero instrumentation in any agent. The console binds to loopback by default, as the A2A gateway does. Two properties turn it on (the starter).

Commands

Two more properties add command-and-control. The console can then:

  • Dispatch tasks, and cancel what the console dispatched.
  • Pause, resume, or drain workers.

The console peer executes every command under its own signed identity. It attributes each command to the operator the credential names: the token holder's fixed name, or the JWT subject. It records each command in an audit space as a signed entry, leased for 24 hours by default.

Operator sign-in

Operators authenticate one of two ways:

  • A static token. command.token gates the HTTP command routes, and always takes precedence when set.
  • Your identity provider. Leave the token blank and configure security.oidc.*. The console then validates each request's bearer JWT against your identity provider. The token must carry aspace:console:operate, and the command is audited under the token's own subject rather than a name the request declares.

Directives travel through the fleet-control space, and the audit trail lands in c2-audit. Both names are properties, and both spaces belong in the group's spaces list.

Extending the console

Extend the read side with two kinds of bean:

  • ConsoleViewCustomizer tells the default generic view what the application's entries mean, worker attribution above all.
  • ConsolePanel. Every such bean becomes one more section on the page and one more document under /api/v1/panels.

One panel ships with the module and is registered for every fleet: TrafficPanel. It shows the wire as the console peer sees it, so the traffic numbers of the performance notes and the robustness counters are readable on a live fleet without an audit harness. It shows:

  • Frames and bytes by kind, as rates over the UI's polling window.
  • The signed, session, and bare split.
  • The frames dropped as stale, replayed, or unverifiable.
  • Each group's view, suspects, anti-entropy rounds, and gossip-tree figures.

Extend the command side with ConsoleCommand beans, whose typed fields render as forms.

Workers that obey

Workers honor directives through a DirectiveGate. Under the starter, call gates.attach(space, worker) on the DirectiveGates bean. Consult gate.paused() and gate.draining() in the work loop.

  • Grant the console on every worker. A gate obeys whoever the group's authorizer permits DIRECTIVE_ISSUER. Under the membership profiles that is every admitted member, unless security.grants.directive-issuer names the console peer. So set that grant on every worker.
  • Hand-wired gates. DirectiveGate.attach(space, worker, consolePeerId) pins one peer instead.
  • Clock limit. Directives stamped more than five minutes ahead are ignored.
// Teach the generic view what your entries mean. Worker attribution above all:
// without this the console can show that work happened but not who did it.
@Bean
ConsoleViewCustomizer researchConsole() {
    return (builder, spaces) -> builder
            .results("findings", Finding.class, f -> ((Finding) f).worker());
}

// One panel bean = one section in the UI and one document at /api/v1/panels.
@Bean
ConsolePanel storyPanel(ConsoleView view) {
    return new ConsolePanel() {
        @Override public String id()    { return "story"; }
        @Override public String title() { return "How this console works"; }
        @Override public Object data()  {
            return Map.of("source", "replica state and leased advertisements only",
                          "eventsObserved", view.lastSeq());
        }
    };
}
// A worker that obeys the console. The gate is a subscription on the control
// space; consult it at the top of the loop, and close it when the worker stops.
try (DirectiveGate gate = gates.attach(controlSpace, "worker-1")) {
    while (!Thread.currentThread().isInterrupted()) {
        if (gate.draining()) {
            return;                       // commanded to drain: stop for good
        }
        if (gate.paused()) {
            Thread.sleep(200);            // commanded to pause: hold off taking
            continue;
        }
        Optional<TakenEntry<TaskEntry>> taken = tasks.take(Template.of(TaskEntry.class),
                Lease.of(Duration.ofSeconds(30)), Duration.ofSeconds(2));
        taken.ifPresent(t -> tasks.complete(t, work(t.entry()), RESULT_LEASE));
    }
}

The console needs no instrumentation, no agent, no sidecar, and no export. The appendix explains why the coordination state is enough.

Run examples/example-09-fleet-console to drive a live fleet: pause a worker mid-run and watch its queue hold.

Where it livesConsoleViewCustomizer, ConsolePanel and ConsoleCommand are @Beans collected by the console autoconfiguration. They need no @AgentSpec and get no card. On a peer where the console is off they are plain beans, so the same jar runs with and without it.

The DirectiveGate is the opposite: it belongs inside the worker, because pausing is something a work loop does for itself.

Keep in mindClose the gate when the worker stops. The gate is a subscription with a year-long lease that is never renewed, so an unclosed gate lingers after the worker is gone.
  • Pausing is authorized. A directive gate honors only issuers the authorizer permits DIRECTIVE_ISSUER. Grant it to the console peer on every worker under the membership profiles, or use the aspace:directive-issuer scope under OIDC. Pausing a fleet is then an authorized operation, and nobody else can do it by writing into the space.
  • Future-stamped directives are ignored. The gate ignores directives stamped more than five minutes ahead.
  • @SpaceTake workers have no gate hook. A fleet that must stop claiming work while paused should use a loop that checks the gate before taking, as above.
  • Do not pause by returning early. Returning early from a take method completes the entry and discards its work.
aspace://guide/gateways · chapter 17

Gateways and dataa2a packageconnect package

This chapter covers two edges of the fleet, where outside clients and data sources connect. The A2A gateway lets an outside client drive agents through the standard protocol. The connector SDK lets a data source join as a peer.

The MCP edges live with the frameworks (Spring AI, Micronaut). The Python, TypeScript, and Clojure clients are chapter 20.

The A2A gateway

Use the A2A gateway (agentspaces-a2a) to let outside A2A clients reach your agents. One gateway peer opens the door for the whole fleet, so individual agents never expose an inbound endpoint.

The gateway serves these endpoints:

  • /.well-known/agent-card.json, the standard A2A discovery endpoint, serves one fleet card. Its skills are the union of every agent's skills.
  • /agents lists every discovered AgentCard.
  • /agents/{name} serves each agent's own card.

It speaks the task protocol as JSON-RPC over HTTP, with SSE streaming and push notifications. Since 0.7.0 each agent's one URL serves both A2A 1.0 and 0.3, chosen per request by the A2A-Version header. A request with no header gets 0.3, so existing clients keep working.

  • A2A 1.0: SendMessage, GetTask, CancelTask, SendStreamingMessage, SubscribeToTask, and the four push-configuration methods. ListTasks is refused as unsupported, since the binding does not scope tasks to a caller, and GetExtendedAgentCard as not configured.
  • A2A 0.3: message/send becomes a leased task entry, tasks/get reads state from the space, and message/stream and tasks/resubscribe stream over Server-Sent Events.
  • Either version: a sent message becomes a leased task entry, and a lapsed lease honestly reports the task as submitted again.
  • The card is an A2A 1.0 card. Its supportedInterfaces list 1.0 and then 0.3. The 0.3 fields (url, preferredTransport, protocolVersion) describe the 0.3 interface, and the AgentSpaces identity rides in capabilities.extensions.

Securing the gateway

  • Loopback by default. The gateway binds to loopback by default.
  • Discovery is open. Discovery GETs stay open.
  • Tasks need a token. The task endpoints take a constant-time static bearer token, or an identity-provider JWT carrying aspace:a2a:client.
  • Webhooks. Push-notification webhooks validate against a private-address denial, with an explicit allowlist override.
  • Results name the issuer. Task results carry the authenticated issuer alongside whatever the worker declares about itself.
// One gateway peer fronts the whole fleet: it serves one fleet card, lists
// every discovered AgentCard as an A2A agent card under /agents, and binds
// the task protocol to a space.
try (A2aGateway gateway = new A2aGateway("research-fleet", "AgentSpaces demo",
                () -> discovery.find(AgentCard.class, card -> true))
        .taskBinding(new A2aTaskBinding(tasks))) {
    int port = gateway.start(8080);
    // POST /agents/{name}  {"method":"message/send", ...}  -> a leased task entry
    // POST /agents/{name}  {"method":"tasks/get",   ...}  -> state read from the space
}
Where it livesOn one peer, wired at startup and closed at shutdown, as a @Bean with a destroy method or a try-with-resources in a plain-Java peer. Individual agents know nothing about it and need no change to become reachable: the gateway serves whatever cards discovery is holding, so an agent becomes reachable over A2A by joining the fleet.

The connector SDK and DataQueryClient

Use agentspaces-connect-core to make a data source a peer. The SPI and the protocol are Apache 2; the module is marked EXPERIMENTAL.

  • AssetProvider describes what the source holds and answers queries for it.
  • ConnectorRuntime publishes leased AssetCards and serves aspace:cap/data-query through the space.
  • DataQueryClient gives pull-once semantics, keyed on a recomputed canonical query hash.
  • MaterializingAssetProvider goes the other way: it pushes source changes into a space as leased entries.
  • DataSpaces wires the block exchange, so bulk results travel content-addressed.
// examples/example-10-data-fleet -- DataFleet, trimmed. The provider peer publishes
// an AssetCard and answers queries for it; keep the clients inside the try so the
// connector is still serving when they fetch.
try (ConnectorRuntime connector = new ConnectorRuntime(dataSpace, discovery, identity,
        "pg-connector", ordersTable, groupId, InstantSource.system(),
        Duration.ofMinutes(1))) {
    connector.start();

    // Any analyst peer finds it by meaning (semantic discovery), then
    // fetches -- pull-once, so the second identical query anywhere in the fleet
    // is served from the space.
    AssetCard card = (AssetCard) semantic.remoteQuery("who holds customer order history?", 3,
            Duration.ofSeconds(2)).get(0).advertisement();
    DataQueryClient client = new DataQueryClient(dataSpace, "analyst-a");
    DataQueryClient.Fetched page = client.fetch(card.asset(), Map.of("region", "eu"),
            Duration.ofSeconds(10)).orElseThrow();
    page.result().rows();     // page.fromCache() is true when nobody re-ran the source
}

Asset operations, connector cells, and celldAssetInvocations

A query reads an asset. An operation changes it. Use asset operations when an agent must change what a connector holds. The capability aspace:cap/asset-invoke adds that second verb without touching the AssetCard.

An operation runs in these steps:

  • The card lists the operations. The card's open access map lists read-ops and invoke-ops.
  • An agent writes the request. It writes an AssetInvocation(v, asset, operation, params, invocationId) into the data space. v is the protocol version; AssetInvocation.of(asset, operation, params) fills it and mints the id.
  • One connector takes it. The connector takes it under the claim lattice, so exactly one connector runs it, and a crashed one lets it reappear.
  • The connector answers. It runs the operation, writes the AssetInvocationResult, and completes the take.

Keep these rules in mind:

  • Retries are safe. The invocationId is the client's and stays constant across retries. A connector that remembers results answers a retry without running the target again.
  • Only listed operations run. An operation absent from the card's invoke-ops is answered with an error naming the rule, and never run.
  • Scopes under an authorizer. The requester needs the scope aspace:connector-invoke:<asset>:<operation>. The scope aspace:connector-serve:<asset> belongs to the connector's own peer.
  • Serving is scoped too. The runtime advertises only the assets its peer holds that scope for. A DataQueryClient built over an authorizer trusts only results from a peer so permitted.
  • Clients. AssetInvocations.invoke(space, card, operation, params) is the Java client. RemoteActions.assetOperations() lists every foreign card's operations beside the agent actions, so a planner sees reserveStock on workers://inventory/do/Inventory as an action it may take.

Connector cells: celld and Cloudflare Workers

The same protocol turns a celld or Cloudflare Workers deployment into a fleet member. celld is Deno's self-hosted runtime for Workers and Durable Objects. Durable Objects are stateful JavaScript objects with SQLite storage, alarms, and a single live instance per name.

The design treats each one as an asset. It is not an agent. @agentspaces/workers runs a connector cell: a Durable Object that joins the group as a non-agent member. The cell:

  • Runs on its own storage. Its identity and state live in its own SQLite storage, its tick runs on the alarm, and it opens an outbound wss to the seeds.
  • Reads a manifest of what the deployment allows.
  • Publishes one AssetCard per Durable Object class or named instance, KV namespace, D1 database, R2 bucket, Queue, Workflow, and route group. Each card has the URI workers://<application>/<kind>/<name>.
  • Runs nothing the manifest does not list. Operations are allowlisted by name, and parameters validated against declared names. D1 queries are named and parameterised. A refused request is answered with an error naming the rule.
  • Runs each invocation once. Its once(invocationId, fn) records each invocation's result in SQLite, so a retry returns the stored result. That makes an asset operation exactly-once end to end.

One wrangler.json deploys the same bundle to celld, workerd, and Cloudflare. The connector runtime it builds on is @agentspaces/connect, the TypeScript twin of this module, byte-identical on the wire.

For a deployment you cannot change, use agentspaces-connect-celld (a root project on this module, on Maven Central at 0.6.0, its current release). It runs the same mapping in Java:

  • A manifest of allowlisted routes, with a bearer or mTLS credential.
  • GET routes as read operations, and POST routes as invoke operations carrying Aspace-Invocation-Id.
  • The same cards and the same refusals.
Keep in mindThe trust boundary is the connector's identity. It holds the authority over the operations it lists, the manifest is the allowlist, and the fleet's authorizer grants who may ask.
  • Cell administration. The celld bucket (or the Cloudflare account) administers every cell.
  • Plaintext peer traffic. celld's own peer traffic is plaintext on the operator's network.
  • What the fleet sees. The fleet sees a member with cards, never the runtime behind it.

People in the loop: connect.hitlconnect packageHitlClientApprovalGate

Some actions need a person to approve them first, such as a payment or a deletion. 0.7.0 adds open conventions for this (SPEC v0.1.38) and the code for both ends in agentspaces-connect-core, package ai.badmonkey.agentspaces.connect.hitl. Nothing here is a new record or field, so there is no flag day.

  • A desk is a group of people who decide. It is an AssetCard whose shape is hitl:<kind>, one of approval, confirm, review, choice, or input. Its access map says who decides and how: deciders, quorum, decide-within, on-timeout, and more (Hitl holds the names).
  • An agent asks the desk with an asset call, and the desk answers with one signed result that carries the decision. A decision counts only when the desk's own issuer wrote it.

Asking: HitlClient

  • resolve(reference, cards, policy, trust) finds the desk. A full card id names that issuer's live card or nothing. A #name resolves only among the issuers you trust (Trust.pinned(issuers)); with none pinned (Trust.openCore()), only when exactly one live issuer offers the name and the group's membership is not OPEN.
  • ask(desk, new HitlClient.Ask(...)) builds the call. The question is rendered from the arguments by your own template, never by a model, and a hash of the arguments binds the decision to this one call.
  • request(space, desk, ask, wait) writes the ask and completes when the desk decides. A requester that should not hold a thread for a person calls decided(space, desk, invocationId) on its next pass instead. cancel(...) withdraws an ask.

Enforcing: ApprovalGate

  • An operation can require approval on its own card. When an AssetCard's access map says hitl.<operation> = <desk>, the operation runs only with a person's approval, whatever agent calls it.
  • The caller passes approval=<invocationId>. The connector's ApprovalGate.refusal(card, call) reads that decision from the desk's issuer and admits the call only when it approves, its arguments' hash is this call's, it is still valid, and it was not used before. One approval runs one call.
Keep in mindA decision can move money, so a requester never accepts a desk an attacker could stand up. With no pinned issuers, a #name desk does not resolve in a group whose membership is OPEN. Pin the issuers you trust, or name the desk by its full card id.
aspace://guide/testing · chapter 18

Testing, performance, conformance

Use these tools to test your own fleet the way AgentSpaces tests itself. Every promise this guide makes is pinned by a test somewhere, and the same tools are yours:

  • A test-support module with a clock you advance by hand and a network you partition on purpose.
  • A ladder of harnesses, from one binder on a local space to three peers over TCP.
  • A performance project, kept apart from the shipped artifacts.
  • Golden vectors that every implementation reproduces byte for byte.

The bill of materials manages the versions of all of it.

agentspaces-test-supportTestClockSimNetwork

Add agentspaces-test-support to your tests to control time and the network. Its stability is API, for tests. It ships five things:

  • VirtualTime is a time source that moves only when the test advances it. Build a node on it with PeerNode.builder(identity).time(time) and start the loop. advance(Duration.ofMinutes(10)) then runs every deadline in those ten minutes in order and returns once the work it released has finished. Probe timeouts, member TTLs, settle windows, take timeouts, and lease renewals all run in virtual time, so a test of a 30-minute idle group runs in a fraction of that and asserts exact times. node() and offset(skew) give one node its own skewed or suspended clock.
  • TestClock is an InstantSource you advance by hand. Create it with TestClock.create() or startingAt(instant), then call advance(duration). Leases, certificates, settle rules, and card TTLs are then judged against an instant the test controls.
  • SimNetwork is a deterministic in-JVM transport fabric. register(nodeId) returns a Transport a PeerNode listens and dials on with no socket.
  • TestCa is a miniature certificate authority for the enterprise-CA channel mode. TestCa.create() mints a self-signed CA. issue(identityKeyRaw) issues a leaf that carries an Ed25519 identity key in its subject, and crl(leaves...) issues a CRL that revokes chosen leaves.
  • Fixtures holds shared records (TaskEntry, FindingEntry) and agent(name).

On a SimNetwork, attest(nodeId, peerId) makes a channel count as attested for a peer. partition(a, b) and heal() split the network and mend it. That is how the lease race, the ordered log, and anti-entropy are tested under a partition in milliseconds.

Everything that takes a clock takes an InstantSource. The Micronaut library takes it as a bean, and the Python and TypeScript peers take an injectable clock the same way.

Prefer VirtualTime to sleeping: a test should never wait out a real timer. With a TestClock you drive the node yourself with tick(), and that loop must advance the clock, or nothing it judges by time moves. Capability rounds can also be stepped by hand: group.capabilities().detachFromPeerTick().cadence(period) and protocolTick() make each round an exact step (chapter 12).

The harnesses

Use these harnesses as a ladder, from the fastest test to the most realistic. There are four rungs, and each catches what the one below cannot. The workflow guide's chapter 13 walks a nine-stage flow up all of them.

HarnessWhat it exercisesExampleUse it for
A LocalSpace and one binderthe binding's logic: filters, joins, folds, leases under a test clockthe binder's own tests, such as AgentBinderGatherTestevery stage, in milliseconds; no replication, so no lease race and no outrun part
Three peers on a SimNetwork and a TestClockreplication, the lease race, the ordered log, the voteAgentBinderJoinClusterTest, AgentBinderReduceClusterTestthe fleet-wide promises: once per key, exactly once, quorum
The same under CPU load, with many keys and the debug log captured per keythe timing a test clock hides: a ticket outrunning a part, a lease lapsing under a drainAgentBinderJoinClusterStressTest with -Djoin.stress=trueany flake in a fleet-wide test; treat one failure in eight as a bug until its timeline says otherwise
Three peers over TCP, the real examplethe whole flow as deployedClaimsFlowTest (example 18), every example's flow testthe acceptance run; ten green runs after any timing change

Two more rungs span languages:

  • A stub peer with no socket, in Python or TypeScript.
  • A Java coordinator with Python and Node workers in their own processes. The cross-language council is that one.

Above the core, other projects run their own suites:

  • integration-tests/spring-boot-it boots the quick start through the starter.
  • integration-tests/embabel-it plans against the real Embabel platform.
  • The Spring AI repository runs context tests for configuration, and TCP flow tests for tools, crash recovery, streaming, routing, retrieval, usage, and MCP (Spring AI).
  • The Micronaut library runs context tests that switch most of its features on and off with their properties (Micronaut).

The checked-in examples use scripted models and run without provider credentials. So coordination is tested first, and a live provider is added as a separate check.

Performance: agentspaces-perf

Use agentspaces-perf to measure what operations cost and how a real fleet behaves. It is a standalone project on the published artifacts, kept apart so measurement code never leaks into the shipped jars. mvn package writes target/benchmarks.jar with two kinds of harness.

The JMH microbenchmarks cover the layers whose per-operation cost multiplies through the whole fabric. Run them from the jar, since each fork is a fresh JVM.

  • CborCodecBenchmark: encode and decode, small records and 16 KiB blobs.
  • CryptoBenchmark: SHA-256, Ed25519 sign and verify, AES-256-GCM seal and open at 256 B, 4 KiB, and 64 KiB.
  • HlcBenchmark: the hybrid logical clock.
  • TemplateBenchmark: matching, the inner loop of read, take, and notify routing.
  • LocalSpaceBenchmark: the verbs at 100 to 10,000 entries.
  • CrdtBenchmark: full-state, per-entry, and take-claim merges.
  • WireCodecBenchmark: a complete signed frame, encode plus sign, decode plus verify.

The stress harnesses start a real fleet in one JVM and print latency percentiles. Every peer has its own node, identity, TCP listener, gossip, and replica. System properties such as -Dpeers=3 -Dworkers=2 -Dtasks=200 shape each one.

  • FleetThroughputStress: contended takes, write-to-take latency.
  • GossipPropagationStress: time until a write is visible on every peer.
  • ChurnRecoveryStress: a peer dies, writes continue, a newcomer catches up.

Its mvn test runs each harness at toy scale to prove the fleets start and the reports carry data. It verifies that the harnesses run; the numbers come from a full run.

Conformance: agentspaces-spec, the golden vectors, and the BOM

Use these to check that an implementation speaks the protocol exactly as the reference does. The agentspaces-spec project is the language-neutral half of AgentSpaces. Every implementation claims conformance to it, and it holds the golden vectors:

  • golden.json holds the vectors: named byte strings and values.
  • To reproduce. A conforming implementation reproduces every non-adversarial vector exactly: keys, ids, HLC stamps, frames, envelopes, signatures, records, claims, deltas, the founding document.
  • To refuse. It refuses every hostile adv_* input: a transplanted claim, a NaN bid, an eternal lease, deep nesting, a frame for the wrong destination.

Each implementation keeps a vendored copy and runs its gate offline:

  • Java: tools/golden/golden.json, through GoldenVectorsConformanceTest, AdversarialVectorsTest, SignedAgentVectorsClusterTest, and VoteVectorsConformanceTest (with -Dgolden.required=true).
  • Python: tests/golden.json, through test_golden.py and test_adversarial.py.
  • TypeScript: test/golden.json, through golden.test.ts.

The copy in agentspaces-spec is the source, and the others are derived from it. sync-golden.sh refreshes them, and verify-all.sh at the workspace root refuses when any copy differs. Never edit a vector by hand: the generator reloads the fixed key material and changes only the vectors whose inputs changed.

The model wire records have a gate of their own, wire-golden.properties inside agentspaces-model-wire.

The bill of materials

Import the bill of materials, agentspaces-dependencies, once, as the quick start shows. Then leave the version off every core dependency. It manages the version of every core module:

  • Foundations: agentspaces-common, -api, -identity, -identity-tls, -auth-oidc.
  • Spaces and peering: -space, -peering.
  • Transports: -transport-quic, -transport-dtls, -transport-http, -transport-webrtc.
  • Higher layers: -discovery, -capabilities, -agent, -a2a, -connect-core, -console.
  • Spring and Embabel: the Spring Boot autoconfigure and starter, and embabel-agentspaces.
  • Tests: agentspaces-test-support.

It also manages the third-party libraries the suite is tested against: the Jackson BOM, Caffeine, Nimbus JOSE+JWT, and Bouncy Castle.

The libraries that release from their own repositories carry their version explicitly: agentspaces-springai, agentspaces-micronaut, agentspaces-langchain4j, agentspaces-model-wire, agentspaces-clj, and agentspaces-groovy.

The open commerce records, Mandate and Order with the AP2 chain check Mandates.verify, are ai.badmonkey.agentspaces:agentspaces-commerce:0.6.0, which releases from its own repository too. It did not change for 0.7.0, so 0.6.0 is its current release.

aspace://guide/examples · chapter 19

Examples and applications

Use the examples to see each feature run before you build your own. Every snippet in this guide is cut from a checked-in source, and the sources come in three sizes:

  • Numbered examples each add one layer or one idea.
  • Example applications are complete fleets.
  • Framework fleets: one fleet per framework library.

All of them run on a laptop with no API keys. Each has a flow test that drives it end to end over real TCP, except examples 01 and 11, which run on a LocalSpace in one process.

The numbered examples

Sixteen graduated examples live under agentspaces/examples: 01 to 14, 18, and 20.

  • Run one: mvn -q -pl examples/<name> exec:java runs the live demo.
  • Walk through them: examples-guide.html beside them is the narrative walk-through.
#exampleadds
01hello-spaceLocalSpace: write, read, take, complete, leases
02research-fleetReplicatedSpace over TCP; closing and reopening a space by name; the cross-language council
03discovery-cardsAgentCards and discovery
04auctionthe AUCTION strategy and @BidFunction, one bidder per space per peer
05quorumaggregate then vote: @Ballot members, an @OnDecision supervisor, a council of seats on one peer counted per granted agent
06wan-rendezvousthe rendezvous role across a WAN
07a2a-fleetthe A2A gateway over a fleet
08intake-fleetextraction as @SpaceNotify, a @Ballot voter, an @OnDecision auditor
09fleet-consolethe console and command-and-control
10data-fleetthe connector SDK and semantic discovery
11quickstartthe whole programming model in one file: the plain-Java form of the quick start
12exactly-once-deskORDERED takes: OrderedTakes.over(...) and an @OrderedTake clerk
13signed-agentssubordinate agent keys, attestation, two annotated agents on one peer
14gossip-learningthree local models converge on the fleet mean on the peer's loop alone
18agentic-workflowa nine-stage claims flow: fan-out, a duplicate-safe join, an auction, a vote gate, an exactly-once payment, fleet sensing, and entries that mirror an ontology; the workflow guide walks it
20enterprise-bootstrapthree seeds behind one DNS name: a worker that knows only the name expands it to every address, dials them all, asks the bootstrap chain again when its view of the group is empty, and keeps the trace of what each locator answered

Examples 15, 16, 17, and 19 live with the framework libraries, below.

The example apps

Eight standalone applications live under agentspaces-example-apps, and each has a guide with diagrams of its agents, spaces and runs; the example apps hub compares them. Each is a complete fleet on the shipped libraries: a self-contained Maven project with its own pom.xml, a run-demo.sh, and a flow test over real TCP. So you can lift any of them into its own repository as is.

Start with the four teaching fleets and read them in this order; each adds one coordination idea to the one before.

appteachescore feature
agentspaces-petclinic-fleet (start here)service choreography: a nurse, a scheduler, and two vets coordinate purely by watching one shared space, and the scheduler's slot book is a @SpaceReduce accumulator@SpaceNotify methods on plain objects
agentspaces-code-fleetcost-aware allocation and kill tolerance: a repository's issues become task entries, coding agents bid by expertise and price, review agents take the finished changes, and a worker that dies mid-migration lets its lease lapsethe AUCTION strategy: @BidFunction + @SpaceTake
agentspaces-audit-fleetcollective decisions with a signed record: a release audited by discipline specialists, every finding adjudicated by a quorum vote of the whole panelaspace:cap/vote (QUORUM)
agentspaces-intake-fleetevidence as ballots and a provenance chain a regulator can walk: content-addressed scans, parallel extractors, a quorum over the signed extractions, human review for the doubtful ones, a signed filingcontent addressing + signed entries

Every agent in them is a plain object with @SpaceNotify, @SpaceTake, @BidFunction, @Ballot, or @OnDecision methods. The facade binds them, as the Spring starter binds beans. Each agent signs with a certified key of its own:

  • Intake and code fleets. They build the facade with an identity factory that calls identity.renewingSubordinate(...) for each agent. Their @SpaceRef handles are per-agent views too.
  • Audit fleet. Each of its four peers writes its spaces as one renewingSubordinate agent named for the peer, so the scanner and the panelist on a peer share one certified key.

Larger applications

The four showcase apps and Party Bus sit beside them, and each has a guide: Ops Center, Spring AI and Jev, Superfriends, Browser Council, and Party Bus.

agentspaces-partybus takes the Embabel travel planner and puts it on a bus: thirty-four agents using every coordination type at once. It has its own guide. On the bus:

  • Scouts drain a bag of research tasks.
  • Planners bid for each day in an auction.
  • A safety panel decides advisories by signed quorum.
  • Travelers vote and report energy, and the fleet paces the trip from it.
  • Booking clerks confirm exactly once through the ordered log.
  • An operator works at a command turret.

agentspaces-example-apps/opscenter is the autonomous operations center flagship. It runs standalone on the 0.7.0 artifacts, Spring AI 2.1, and Embabel 1.5 under a profile. ./run-demo.sh runs it on scripted models, and OPENAI_API_KEY switches to live ones. In the demo:

  • An incident lands on a shared board, and specialists claim the parts they understand.
  • A worker dies mid-job, and its task comes back.
  • Three judges disagree, and a quorum decides.
  • A person approves, and the irreversible step runs exactly once.
  • The closed incident carries every piece of evidence, signed by the agent that produced it.

Three more applications live under examples/:

  • superfriends. Grok, GPT, and Claude arrive on three different Java frameworks and join one fleet. It shares a model service, a chat memory, and a usage ledger over the model wire. Then they run a research desk where the three models vote and the paper trade runs once on an ordered log.
  • browser-council. A committee of senators votes on motions. Its members run in two Java peers, a web page, a resident browser tab, a Node process, and a Durable Object on workerd. An ordered log minutes every decision once, and loses its leader mid-session.
  • agentspaces-springai-jev-eg. It drafts a customer reply with Claude Haiku on a peer that holds no API key, through a model server that does. TypeSafe Jev judges the draft on another peer, and a failed draft goes back as a new ticket.

The framework fleets

Each framework library ships its own fleet, in its own repository:

  • Example 15, agentspaces-springai/examples/springai-fleet. A summarizer, a translator, and an orchestrator whose model calls them as tools, as three Spring Boot applications. springai-patterns beside it holds the judges, the token-priced auction, and the extraction ensemble of the Spring AI chapter.
  • Example 16, agentspaces-micronaut/examples/micronaut-fleet. An orders service that is both an agent and a data source, and an analyst that drives it. The analyst uses the task space, the data space, and @Client("orders") resolved through the fleet.
  • Example 17, micronaut-ai-fleet. It adds a LangChain4j worker, a keyless orchestrator, and an MCP gateway on three peers.
  • Example 19, agentspaces-langchain4j/examples/langchain4j-fleet. The same worker and orchestrator with no application framework at all. Its flow test leaves a worker stuck mid-task and watches another finish it.
Where to go nextThis guide is the reference; the workflow guide composes the pieces into one flow. The A2UI guide builds a front end from an AppCard, the open widget library, and the A2UI renderers. The Tutorial Notebook builds a small fleet step by step, in six languages.
aspace://guide/other-languages · chapter 20

Other languages

Use the Python or TypeScript client to run a peer outside the JVM. Use the Clojure or Groovy bindings to write JVM peers in those languages. The Ruby peer (20.7) and the Rust peer (20.8) also run outside the JVM.

Each language has its own guide, written for newcomers: Clojure, Groovy, Python, Ruby, Rust, and TypeScript. Start there; the sections below summarize each language for readers who know the Java chapters.

The wire protocol is CBOR plus Ed25519 (wire version 3, enforced), with nothing Java-specific. The project ships wire-compatible Python and TypeScript peers, proven byte-identical against shared golden vectors that cover every wire structure. They refuse the same hostile inputs as the Java implementation. The appendix explains how wire version 3 encodes signed maps.

Both clients can:

  • Join by seed, or by GroupId with the founding document verified.
  • Write signed entries.
  • Take under the claim lattice, as Java does.
  • Read through anti-entropy.

Both also speak the agent-identity model of agent certificates:

  • Certificates. They verify agent certificates at signing time.
  • The two-key rule. They apply it to records, take-claim proofs, and state transitions: an attested agent's transitions must be its own.
  • Revocations. They apply peer, agent, and agent-key revocations at merge.
  • Acting as an agent. They can write, take, and complete as a renewing subordinate agent themselves (renewing_subordinate / renewingSubordinate), with a keystore in Java's layout.
  • Cards. The cards they build carry agentPublicKey, declared actions, and the agent's certificate.
  • Votes. They tally QUORUM ballots at either granularity (agentspaces.vote, vote.ts).
  • Testable time. Their Peer takes an injectable clock, so time-bound material is testable against a fixed instant, as Java's TestClock is.

run-trilingual-demo.sh races workers in all three languages on one space. The cross-language council is the test that the layers above the wire agree.

Clojure and Groovy sit on the JVM and consume the Java artifacts directly. So each is a binding over the reference implementation and gets the wire for free.

The Space API in Python and TypeScript

Both clients carry the AgentSpace and the capability services (the annotations, the Space API, the capability services) in their own idiom.

  • Entries. An @entry class names its wire schema: a Java record's binary class name plus #v1 under the default registry, or the namespace a schema registry assigns.
  • Spaces. A Space holds write, read, read_all (readAll in TypeScript), entries, take, complete, and watch. entries is the metadata view: id, tags, issuer, lease, whether taken.
  • Templates. A Template matches fields and tags with the Java matchers eq, ne, gt, gte, lt, lte, and contains, or with any function.
  • The other matchers. Python spells the rest in_, is_null, and not_null. TypeScript spells them oneOf, isNull, and notNull.
  • Watches. A watch delivers WRITTEN, TAKEN, COMPLETED, EXPIRED, and REAPPEARED once per entry and kind. In TypeScript it is an EventEmitter or an async iterator.
  • Expired and reappeared. EXPIRED means the write lease lapsed on an open entry. REAPPEARED means a take claim lapsed and the entry is available again.
  • The current take. The in-flight take is a context variable: TakeContext.current(), over AsyncLocalStorage in Node.

The binder in Python and TypeScript

The binder runs the loops AgentBinder runs, over decorated methods in each language's own form (below). The return conventions are the Java binder's:

  • None or null writes nothing.
  • A Tagged is written with its tags.
  • A list or array is the fork.
  • A Motion opens a vote once per proposal id.
  • The take completes before a fork or a motion runs.

The binder publishes the AgentCard, with its declared actions and the agent's certificate, on bind.

Capabilities over the pipes

The layer-4 pipes (PIPE_DATA frames addressed to a member) carry three capabilities:

  • Push-sum (Aggregate): avg, roster sum and count, min, max, Settle, await_settled, on_estimate.
  • Semantic discovery (Semantic): query, remote_query, and the answer to a peer's query. The hashing embedder computes Java's vectors to the bit, so the two sides rank alike.
  • Remote actions: actions from the cards on the ads stream, and invoke through the task space with the shared-fields correlation.

A dial-only peer sends a capability frame only to a member it can reach: the seed it dialed, never one it only heard of. The seed drops an addressed frame and does not relay it.

Ordered takes, joins, and votes

The ordered log reaches both clients as a Raft client. The voter runs on the JVM and, as @agentspaces/ordered, on a Node service.

  • TypeScript binds it with @orderedTake, @spaceReduce, and the LEASED and ORDERED modes of @spaceJoin. The residency of the host decides which of them it may carry (20.6).
  • Python takes through the log with Space.take(template, through=OrderedLog(Pipes(peer))). It has no decorators for the ordered take, for @SpaceReduce, or for the fleet-wide join modes, so @space_join runs in LOCAL mode only.
  • MAJORITY_GOSSIP is in both clients: cast_preference and leader in Python, castPreference and leader in TypeScript.
ONE GROUP: GroupId = hash(founder-signed founding document)Java peeragentspaces (the reference)Python peeragentspaces-pythonTypeScript peeragentspaces-typescriptCBOR frames, Ed25519 envelopesthe same framessigned records, take claims, state transitions, cardswire version 3: canonical CBOR, shorter UTF-8 keys first, bytewise between equal lengthsso the signed bytes of a structure depend on its content alone, in every languagejoin by seed or by GroupIdthe founding document verified firstwrite, take, complete, watchunder the same claim latticeagent certificates, revocationsjudged at signing timePINNED BY GOLDEN VECTORS: agentspaces-spec/golden.jsonthe shared vectorsreproduced exactly, the hostile ones refusedJavaGoldenVectors*Test suitesPythontests/test_golden.pyTypeScripttest/golden.test.tssync-golden.sh copies the source into each repository; verify-all.sh refuses when any copy differs
The wire. A Java, a Python, and a TypeScript peer in one group exchange the same CBOR frames under the same Ed25519 signatures, and each repository proves it against a vendored copy of the shared golden vectors, so a structure signed in one language verifies in the others.

20.1 Python

Main documentationThe Python guide is the main documentation for Python: how to build agents step by step, the features specific to the language, and complete examples. This section summarizes it for readers who know the Java chapters.

Use agentspaces-python to write a peer in Python. It decorates plain methods: @agent on the class, then @space_take, @space_notify, @bid_function, @ballot, @on_decision, @on_estimate, @propose, and @space_join on methods.

  • Attributes. The cue, the entry type a method reacts to, is read from the parameter annotation. The attributes are keyword arguments in snake case (lease, where with the matchers, prefix, parts as a list of Part).
  • Entries. An @entry class names its wire schema.
  • Certified agents. Binder(peer, agent=identity.renewing_subordinate(name, ttl)) binds as a certified agent.
  • Capabilities. Aggregate(Pipes(peer)), Semantic, and the remote actions sit on the capability pipes.
  • The current take is a context variable, TakeContext.current().
@entry("ai.badmonkey.agentspaces.examples.fleet.ResearchFleet$ResearchTask#v1")
@dataclass
class ResearchTask:
    topic: str
    priority: int

@agent("researcher", description="Researches topics", goals=["research"])
class Researcher:
    @space_take("tasks", lease="30s", where={"priority": gte(1)})   # take, call, complete with the result
    def research(self, task: ResearchTask) -> Finding: ...

    @ballot("votes", prefix="council:")                             # one ballot per proposal, None abstains
    def judge(self, proposal: Proposal) -> str | None: ...

    @space_join("intake", key="claim_id", parts=[Part(Fraud), Part(Coverage)])
    def assemble(self, j: Joined) -> Assessment: ...               # once per key, LOCAL mode

bound = Binder(peer, agent=identity.renewing_subordinate("py-worker", "PT24H")).bind(Researcher())
aggregate = Aggregate(Pipes(peer)); aggregate.start("load", 12.5); aggregate.run()

Finding the fleet. A client dials one seed and gossips from there, so the only question is which address. You have two ways to find it:

  • A list of seeds. peer.connect_any(seeds) dials a list in order.
  • A beacon document. peer.bootstrap(url, group_id=..., beacon_peer=...) reads a beacon document instead. It needs a founding, so it joins a group that has one.

bootstrap works in these steps:

  • It fetches the document, over HTTPS unless allow_plain.
  • It verifies the signature, and pins the signer when beacon_peer is given.
  • It checks the group's signed founding against group_id.
  • It dials the document's tcp and tls seeds in priority order, and fetches the document again when it has to reconnect.

For a group started from a text, derive the id with group_id_from_founding. Then take the seeds from the document yourself with beacon.fetch_beacon_document, group_from_document, and seeds_of.

# a group with a signed founding: the id and the document's URL are all you need
peer = Peer(identity, group="aspace://q9c2b...")
url = "https://partner.example/.well-known/agentspaces/beacon.json"
founding = peer.bootstrap(url, group_id="aspace://q9c2b...",
                          beacon_peer="z6Mk...")

# a group started from a text: the id from the text, the seeds from the document
peer = Peer(identity, group=group_id_from_founding(b"research-fleet-v1"))
url = "https://agentspaces.corp.example/.well-known/agentspaces/beacon.json"
doc = beacon.fetch_beacon_document(url)
group = beacon.group_from_document(doc, name="research-fleet")
peer.connect_any(beacon.seeds_of(group))
Where it livesagentspaces-python/agentspaces/space.py, agents.py, vote.py, and capabilities/; the socketless tests tests/test_layer34.py, test_layer4.py, and test_verbs.py; the golden gate tests/test_golden.py and test_adversarial.py; demo_council_worker.py for a councillor in the cross-language council.

20.2 TypeScript

Main documentationThe TypeScript guide is the main documentation for TypeScript: how to build agents step by step, the features specific to the language, and complete examples. This section summarizes it for readers who know the Java chapters.

Use agentspaces-typescript to write a peer in TypeScript. It uses stage-3 decorators with the cue type as the first argument, since TypeScript keeps no parameter types at runtime: @agent, @spaceTake(Type, space, options), @spaceNotify, @bidFunction, @ballot, @onDecision, @onEstimate, @propose(Type, space, voteSpace, options, quorum, more), and @spaceJoin.

  • Return types. Name produces explicitly where the card cannot read a return type.
  • Watches. A watch is an EventEmitter or an async iterator (space.events(template)).
  • The current take rides AsyncLocalStorage.
  • Certified agents. new Binder(peer, { agent: identity.renewingSubordinate(name, ttl), aggregate }) binds as a certified agent, with the aggregate the @onEstimate methods watch.
@agent("researcher", { description: "Researches topics", goals: ["research"] })
class Researcher {
  @spaceTake(ResearchTask, "tasks", { lease: "30s", where: { priority: gte(1) }, produces: Finding })
  research(task: ResearchTask): Finding { ... }

  @propose(Claim, "claims", "votes", ["approve", "deny"], 2, { prefix: "claim:", key: "claimId" })
  ask(claim: Claim): string | null { ... }                      // one vote per key

  @onEstimate({ epochs: "load", settle: "2s", tolerance: 0.01, resultSpace: "reports", produces: Report })
  settled(estimate: Estimate): Report { ... }
}
const bound = new Binder(peer, { agent: identity.renewingSubordinate("ts-worker", "PT24H"), aggregate }).bind(new Researcher());
for await (const e of space.events(new Template(Finding, {}, { region: "eu" }))) { ... }

Finding the fleet. peer.connectAny(seeds) dials a list in order. peer.bootstrap(url, { groupId, beaconPeer }) reads a beacon document, and it needs a founding. It works in these steps:

  • It fetches the document with the runtime's fetch.
  • It verifies the signature and honors the pinned signer.
  • It checks the group's signed founding against groupId.
  • It dials the document's seeds of every scheme the peer dials. A browser dials ws or wss, so a document whose seeds are all tls names nothing a browser can reach.

For a group started from a text, derive the id with groupIdFromFounding, a top-level export. Take the seeds from the document with beacon.fetchBeaconDocument, beacon.groupFromDocument, and beacon.seedsFor. The package exports the beacon helpers only as the beacon namespace.

// import { beacon, groupIdFromFounding } from "@agentspaces/client";
// a group with a signed founding: the id and the document's URL are all you need
const url = "https://partner.example/.well-known/agentspaces/beacon.json";
const group = await peer.bootstrap(url,
  { groupId: "aspace://q9c2b...", beaconPeer: "z6Mk..." });

// a group started from a text: groupIdFromFounding("research-fleet-v1") is the
// id, and the document supplies the seeds
const home = "https://agentspaces.corp.example/.well-known/agentspaces/beacon.json";
const doc = await beacon.fetchBeaconDocument(home);
const entry = beacon.groupFromDocument(doc, { name: "research-fleet" });
await peer.connectAny(beacon.seedsFor(entry, ["wss"]));
Where it livesagentspaces-typescript/src/space.ts, agents.ts, vote.ts, and capabilities/; the socketless tests test/layer34.test.ts, layer4.test.ts, and verbs.test.ts; the golden gate test/golden.test.ts; demo/council.ts for a councillor in the cross-language council.

20.3 Clojure: defagent and the capability namespaces

Main documentationThe Clojure guide is the main documentation for Clojure: how to build agents step by step, the features specific to the language, and complete examples. This section summarizes it for readers who know the Java chapters.

Use agentspaces-clj to write JVM peers in idiomatic Clojure (github.com/badmonkeyai/agentspaces-clj, installed from a clone: Clojars has 0.6.0, and clojure -T:build install in the clone puts 0.7.0 in ~/.m2 for {:mvn/version "0.7.0"}). It lives outside the Maven reactor and consumes the published artifacts by coordinates. It gives you:

  • Maps in and out, over record entry types.
  • A keyword :where DSL.
  • fleet/start from a config map whose keys follow the Spring starter's properties; the README's §12 table maps each key, and two differ by name: the SWIM tuning is :membership-tuning and the membership policy is :policy, where the starter has membership.

agentspaces.agents/defagent defines an agent as one form: the spec map and one clause per verb (take, notify, bid, ballot, on-decision, ordered-take, on-estimate, propose, join, reduce). Each clause has:

  • The parameter types.
  • The annotation's attributes in kebab case: nested @Part maps under :parts, and :mode as :local, :leased, or :ordered.
  • A return hint.

The macro generates the annotated interface (the card and remote callers read the declared types there) and a constructor reifying it. So agents/bind! hands the object to the Java binder unchanged, and every annotation binds.

  • Capabilities. fleet/start takes a :capabilities block (:vote, :aggregate, :ordered with its members, :semantic, :learn).
  • Procedural forms. The namespaces vote, aggregate, ordered, semantic, learn, and remote are the procedural forms over the same capabilities.
  • Templates and metadata. core/template takes :tags, and space/read-entries is the metadata view.

Babashka. agentspaces-bb reads a fleet from a shell: bb as queries a fleet console's HAL+JSON API and prints JSON, and bb as serve starts a JVM peer that hosts one space for development. It is a console client, and it cannot take work. The Clojure guide's Babashka section covers it.

(defagent Researcher
  {:description "Researches topics" :goals ["research"]}
  (take research [^ResearchTask task] {:space "tasks" :lease "30s" :tags ["region=eu"]}
    ^Finding (Finding. (:topic task) (str "researched " (:topic task))))
  (ballot judge [^VoteCapability$Proposal p]
    {:space "votes" :prefix "council:"} ^String (identity "yes"))
  (join assemble [^Joined j] {:space "intake" :key "claimId" :mode :leased
                              :parts [{:value Fraud} {:value Coverage}]}
    ^Assessment (Assessment. (.key j) "pay")))

(def system (fleet/start {:bind "127.0.0.1:7461" :agents true
                          :capabilities {:vote {:space "votes"} :aggregate true}
                          :group {:name "claims" :founding "claims-v1" :spaces [{:name "tasks"} {:name "votes"} {:name "intake"}]}}))
(def bound (agents/bind! system (->Researcher)))
(vote/propose! system {:id "council:ship" :question "ship?" :options ["yes" "no"] :quorum 2})
(aggregate/await-settled system "load" {:settle "3s" :tolerance 0.01})

20.4 The cross-language council

Run CouncilFleet (example 02) to see that the layers above the wire agree across languages. It has a coordinator and two workers:

  • The coordinator is Java, on TCP, with the task and vote spaces, discovery, and push-sum, votes, and semantic discovery on one set of pipes.
  • The workers. demo_council_worker.py and demo/council.ts bind a decorated councillor in each client.

The coordinator writes tasks, proposes council:ship at a quorum of every member, starts the load epoch, and waits. Then:

  • Both workers take tasks.
  • The vote decides at three ballots.
  • The epoch settles at the mean of the three contributions.
  • A semantic query over the pipe ranks both workers' cards.
  • A remote action a worker's card declares is served.

CouncilCrossLanguageTest runs it with the two workers in their own processes, as a step of verify-all.sh. run-trilingual-demo.sh plays it as its second act after the research race.

20.5 Groovy: one-file peers, the two DSLs, and await

Main documentationThe Groovy guide is the main documentation for Groovy: how to build agents step by step, the features specific to the language, and complete examples. This section summarizes it for readers who know the Java chapters.

Use agentspaces-groovy to write peers in Groovy, from one-file scripts to compiled classes. It is a standalone project on the published 0.7.0 artifacts (Apache Groovy 6.0.0, Java 21 bytecode). It sits where Clojure does: on the JVM, over the Java binder, with nothing reimplemented.

A Groovy class carrying the Java annotations, dynamic or @CompileStatic, already binds through FleetRuntime.bind, the Spring Boot starter, or the Micronaut library. The project tests that floor and builds on it. Groovy records are Java records, so a Java peer names and builds the same entry type.

The one-file peer. FleetScript is a script base class:

  • fleet { } starts the peer.
  • agent(name) { } describes a worker as one closure per verb (take, notify, bid, ballot, onDecision, orderedTake, onEstimate, propose, join, reduce).
  • bind hands it to the Java binder.
  • serve() blocks until SIGINT or stop().

The fleet DSL's keywords are the starter's property names, camel-cased. There are two aliases and no other sugar: a millis property without its suffix takes a duration (coalesce '20ms' for coalesce-millis), and the singular group and space, which add one list element.

@Grab is a development convenience: pin the version, and ship a jar in production. The appendix explains how the two DSLs reach the Java binder.

@Grab('ai.badmonkey.agentspaces:agentspaces-groovy:0.7.0')
@Grab('ai.badmonkey.agentspaces:example-02-research-fleet:0.7.0')   // the two records below; unpublished, install it from a core checkout
import ai.badmonkey.agentspaces.examples.fleet.ResearchFleet.ResearchTask
import ai.badmonkey.agentspaces.examples.fleet.ResearchFleet.Finding
@groovy.transform.BaseScript ai.badmonkey.agentspaces.groovy.FleetScript _

fleet {
    bind '127.0.0.1:7591'                       // agentspaces.bind
    security { profile 'dev-local' }            // agentspaces.security.profile
    group('research-fleet') {                   // agentspaces.groups[0]
        founding 'research-fleet-demo-v1'
        seeds '127.0.0.1:7590'
        space 'tasks'
    }
}

bind agent('summarizer', description: 'Summarizes research tasks') {
    take(ResearchTask, space: 'tasks', lease: '30s', returns: Finding) { ResearchTask t ->
        new Finding(t.topic(), "summary of ${t.topic()}", 'groovy')
    }
}

serve()                                         // until Ctrl-C or stop()

The class form, checked at compile time. FleetChecker is a type-checking extension for @TypeChecked and @CompileStatic code. These mistakes fail to compile, in the binder's own words:

  • A where entry that names no component of the cue record.
  • A lease that does not parse.
  • A @Ballot that returns anything but String.
  • A DSL closure whose parameter disagrees with the cue.
  • @Memoized and @ActiveMethod beside a verb.

It also lets the fleet DSL compile statically. Prefer the class form for anything that ships in a jar or runs under a host. Use the DSL for scripts, tests, and agents assembled at run time. Both publish the same card.

@CompileStatic(extensions = 'ai.badmonkey.agentspaces.groovy.FleetChecker')
@AgentSpec(name = 'pricer', description = 'Prices an order', goals = ['price orders'])
class Pricer {
    @SpaceTake(space = 'tasks', lease = '10m', where = ['priority=1'])
    Quote price(PriceRequest r) { new Quote(r.item(), r.quantity(), 4.25d * r.quantity()) }

    @Ballot(space = 'votes')
    String judge(VoteCapability.Proposal p) { p.question().contains('ship') ? 'approve' : null }
}

def runtime = Fleet.start(Path.of('agentspaces.yaml'))
runtime.bind(new Pricer())

The Space API, in Groovy. An extension module adds the verbs with named arguments:

  • The where: map DSL. A plain value is eq. anyOf stands for the Java in, a Groovy keyword.
  • Coercion. Durations and leases coerce from strings ('10m' as Lease). Records come from maps and go back: every record class gains Task.from(map) (an extension on Class<T>, the way newInstance() is, dynamic or @CompileStatic), and record.toMap() is the way back. Numbers in where: filters compare by value whatever their boxed class, so gte(2) matches a long component.
  • Filter closures. The filter closure of read, all, entries, and notify runs after the template matched, on this replica only.
  • No filter closure on take. A take claim is judged by the fabric's template, so take takes where: and tags: and no filter closure.
  • Async twins. Every blocking verb and client wait has an Async twin returning a CompletableFuture on a virtual thread. Groovy 6's await takes it unchanged.
  • Mind await precedence. await binds looser than member access, so write (await x).size().

The incubating groovy.concurrent toolkit lives in a second artifact, agentspaces-groovy-concurrent. It offers a channel fed by one subscription for for await, broadcast, select recipes, and dataflow twins. Closing a channel unsubscribes, and a channel closes itself when its lease would lapse.

FleetShell opens groovysh over a running peer, with fleet, spaces, space(name), and agent bound. It refuses a configuration that serves the console or the A2A gateway.

import static ai.badmonkey.agentspaces.groovy.Where.*

space << entry                                        // the space's default lease (10m; space.defaultLease = '2h')
space.write(entry, lease: '10m', tags: [region: 'eu'])
space.read(Task, where: [priority: gte(2), topic: anyOf('a', 'b')], tags: [region: 'eu'])
space.read(Task) { priority > 2 }                     // a filter over the decoded entry, on this replica
space.all(Task, limit: 50)                            // an unmodifiable List: GINQ-ready; toSorted, never sort in place
space.take(Task, lease: '10m') { Task t -> new Quote(...) }   // take, run, complete; null completes without a result; a throw lets the lease lapse
space.notify(Task, lease: '1h', on: 'written') { SpaceEvent e -> ... }
votes.propose(id: 'm-1', question: 'ship?', options: ['yes', 'no'], quorum: 2)

Optional<Task> first = await space.readAsync(Task, where: [topic: 'x'])      // every blocking verb has an Async twin
def decision = await votes.decisionAsync('m-1')
for await (e in space.channel(Finding, lease: '1h')) { println e.entry().summary() }   // agentspaces-groovy-concurrent

Example 21 (agentspaces-groovy/examples/groovy-fleet) runs on example 02's research fleet beside its Java peers. It has a script worker, a CSV-to-report intake script, a statically compiled planner, and a Java RemoteActions caller invoking the script's card.

The Groovy constructs that meet the binder are tested one per row:

  • A map coerced to an annotated interface binds.
  • A trait's annotated method binds through the implementing class.
  • @Delegate to an annotated interface exposes the verb.
  • A closure property is not a verb.
  • @Memoized binds but caches per equal cue.
  • A Java map renders Groovy-style inside a GString.

The desktop console. agentspaces-groovy-console is a desktop notebook for Groovy and Clojure peers, in the same repository. It puts code cells beside a fleet explorer, a typed space browser, and a message composer, and each notebook tab runs its own peer.

  • Groovy and Clojure cells. A cell's language switches between the two, and Clojure cells see the same running peer.
  • The Recipe Book inserts working starters, among them the workflow starters below.
  • Joining and publishing. It joins by seeds or a beacon, publishes its own join beacon, and publishes a notebook's workflow as a card.
  • Running it. Build the repository and run console/bin/agentspaces-groovy-console, or package a native app image that carries its own Java.

The console guide covers it step by step.

The Workflow API. A workflow is a named set of ordinary agent bindings: each stage takes, watches, joins, or reduces typed entries, and the Java binder supplies the claims, leases, completion, and the real AgentCard. No model is needed. The API is ai.badmonkey.agentspaces.groovy.workflow in the Groovy library, and the same artifact carries the Clojure namespace agentspaces.workflow. It needs no console:

import ai.badmonkey.agentspaces.groovy.workflow.Workflows
// Request, Prepared, and Report are records, each with a runId component

def flow = Workflows.workflow('readiness-report', version: 1) {
    defaults(space: 'work', key: 'runId', lease: '2m', resultLease: '10m')
    take('prepare', Request, returns: Prepared) { input -> new Prepared(input.runId(), input.value() * 2) }
    take('report', Prepared, returns: Report) { input -> new Report(input.runId(), 'value ' + input.value()) }
}
def running = flow.start(groupContext)                 // binds the stages; one AgentCard for the workflow
try {
    def submitted = running.submit(new Request(UUID.randomUUID().toString(), 7))
    println submitted.await(Report, timeout: '10s')       // Optional<Report>
} finally {
    running.close()                                     // unbinds the stages; queued entries stay
}

Clojure writes the same workflow with (wf/workflow {...}), (wf/start! definition group), and (wf/submit! running entry). Every stage's input carries the workflow's flow and flowVersion tags, so two versions can share a space without consuming each other's work. A timeout stops the wait, not the work.

20.6 JavaScript everywhere: residency, the browser, Node, and the stores

Main documentationThe TypeScript guide is the main documentation for TypeScript and JavaScript hosts (Node, the browser, and Workers cells): how to build agents step by step, the features specific to the language, and complete examples. This section summarizes it for readers who know the Java chapters.

Use the TypeScript client to run a peer in a browser, a worker, or Node. From 0.4.0 it is a portable core: the same Peer loads in a page, a Web Worker, a Cloudflare Worker, Deno, Bun, and Node 22.

  • No Node modules. Its main entry imports no Node module, crypto runs on the noble libraries, and bytes are Uint8Array.
  • A platform port. A Platform port supplies the clock, timers, key store, and residency.
  • Transports. It dials ws, wss, http, and https with the runtime's own WebSocket and fetch, and tcp and tls on Node (import "@agentspaces/client/node").

The fleet verbs are all there:

  • Leased push subscriptions and fold-driven takes.
  • The filter grammar (priority>=3, region in eu,us), identical in Java, Python, and TypeScript.
  • MAJORITY_GOSSIP and the Raft client.
  • @orderedTake, the LEASED and ORDERED @spaceJoin modes, and @spaceReduce.

A host's residency is the kind of host it is, and it decides what the host may carry:

ResidencyHostCarriesPackage
visitora page, a short-lived scriptwatches, takes, @spaceNotify, @orderedTake (as a Raft client), LOCAL joins, gossip shares, the store adapters@agentspaces/client
residenta SharedWorker or Worker holding a Web Lockthe above plus the keeper duties: LEASED and ORDERED joins, @spaceReduce@agentspaces/browser
cella Durable Object on celld, workerd, or Cloudflarekeeper and connector duties@agentspaces/workers
servicea Node processeverything: listeners, relay, the Raft voter, the ordered-log coordinator@agentspaces/node, @agentspaces/ordered
  • Bind errors name the fix. Binding a verb the residency cannot host fails at bind time, naming the verb, the residency, and the package that can.
  • Unknown hosts are visitors. An unknown class ranks as a visitor.
  • The residency hint is not trusted. A host reports its class as the hint js.residency, which peers show but never trust.
  • Slow hosts step down. A host whose tick drifts beyond twice its period three times running drops to visitor duties: voters suspend, keepers close, held claims lapse. It takes them back after sixty seconds of cadence.

A browser peer. A page connects to the resident host. The host runs the peer once per identity per origin (the Web Lock agentspaces:<group>:<peerId>) and keeps keys and a state snapshot in IndexedDB. When the last page hides or freezes, it stops renewing and closes its socket. It resumes with the same identity when a page returns. Two tabs are one member with one connection.

// the page: @agentspaces/browser
const host = await connect({ group, seeds: ["wss://fleet.example:7443"], worker: "/agentspaces-worker.js" });
const tasks = host.space("tasks");
for await (const e of tasks.events(new Template(Finding, {}, { region: "eu" }))) { ... }
const taken = await tasks.take(new Template(ResearchTask, {}, {}, ["priority>=3"]), "30s");

A Node service. agentspaces-node run fleet.yaml reads the agentspaces: subtree of the same fleet file a Java member reads. It then:

  • Listens on tcp and ws, and dials its seeds.
  • Serves anti-entropy and relays rumors for the browsers behind it, in Java's own digest formats.
  • Runs its housekeeping as due work on its peer's loop, and drains on SIGTERM.

Give a group an ordered-logs block and it hosts a Raft voter (@agentspaces/ordered) byte-identical to the Java one, with its term, vote, and entries in a file store. A desk of two Java voters and one Node voter completes every job exactly once when the leader dies, in either language.

# fleet.yaml: Java and agentspaces-node read the same file; only Node binds ordered-logs
agentspaces:
  keystore: keys
  bind: 0.0.0.0:7500
  transport:
    ws: { bind: 0.0.0.0:7501, allowed-origins: [ "https://app.example" ] }
  groups:
    - name: council
      founding: council-v1
      seeds: 10.0.0.5:7460
      spaces: [ tasks, votes ]
      ordered-logs:
        - { space: tasks, members: [ zJavaVoterA, zJavaVoterB ], log-dir: log/tasks }

The store adapters. An application on automerge-repo or Yjs changes one constructor argument: new Repo({ network: [new AgentSpacesNetworkAdapter(pipes)] }) or new AgentSpacesProvider(pipes, "room", doc).

  • Members of the group become the library's peers under their PeerIDs.
  • Sync messages travel as signed PIPE_DATA frames (aspace:cap/automerge, aspace:cap/yjs), and the document formats are untouched.
  • AgentSpaces adds signing, membership, and relay.
  • Both run at the visitor residency and need no ordered log.

Python. The Python client has most of these verbs and the connector clients, on the same golden vectors: leased notify, fold-driven takes, filters=, MAJORITY_GOSSIP, and the Raft client through Space.take(..., through=log). It has no @orderedTake, @spaceReduce, or LEASED and ORDERED join decorators, which TypeScript has. It stays a tcp dialer that skips the other schemes.

Where it livesagentspaces-typescript/: the core in src/, and the hosts and adapters as workspace packages under packages/ (node, ordered, browser, connect, workers, automerge, yjs, webrtc). The Java side is in agentspaces-transport-http and agentspaces-connect-core.

The conformance subset runs in Chromium, Firefox, WebKit, Deno, Bun, and workerd. A suite skips an engine that is not installed, unless AGENTSPACES_RUNTIMES_REQUIRED=1 (Deno, Bun, workerd) or AGENTSPACES_BROWSERS_REQUIRED=1 (the browsers) is set.

Keep in mindA browser member is as reliable as its tab. A page's claims lapse when the tab is hidden long enough, and that is by design. Put anything that must outlive a tab on a Node service or a cell. The hub a browser dials must list its origin; an empty allowlist refuses every browser on purpose.

20.7 Ruby: a wire peer, class macros, Rails, and JRuby

Main documentationThe Ruby guide is the main documentation for Ruby: how to build agents step by step, the features specific to the language, and complete examples. This section summarizes it for readers who know the Java chapters.

Use agentspaces-rb to write peers in Ruby. It is a standalone project of five gems, installed from a clone (they are not on RubyGems). Ruby reaches a fleet two ways, and both run the same agent classes:

  • On MRI (Ruby 3.3 or newer), agentspaces is a pure-Ruby wire peer, as the Python and TypeScript clients are. It reproduces every golden vector byte for byte, dials tcp, tls, ws, wss, http, and https (with session attestation where the transport attests nobody), and needs no native extension.
  • On JRuby, agentspaces-jruby binds the same classes through the Java binder, with every transport and the ordered verbs; fleet.ordered(space, members:) forms a node’s member of the ordered log from Ruby.

Entries are Data classes with typed fields. Ruby members are snake_case and travel under camelCase wire names, so order_id is the Java component orderId. An agent is a class whose macros sit above the methods they bind. Every macro checks its options when the class loads, and agentspaces check app/agents runs those checks with no fleet.

require "agentspaces"

Order    = AgentSpaces::Entry.define("shop.Order#v1",    order_id: String, item: String)
Shipment = AgentSpaces::Entry.define("shop.Shipment#v1", order_id: String, item: String, by: String)

class Fulfiller
  include AgentSpaces::Agent
  agent "fulfiller", description: "Ships orders"

  take Order, space: "orders", lease: "30s", produces: Shipment
  def ship(order) = Shipment.new(order_id: order.order_id, item: order.item, by: "fulfiller")
end

AgentSpaces.serve(group: "shop", founding: "shop-v1", seeds: ["127.0.0.1:7700"]) do |peer|
  peer.bind(Fulfiller.new)                     # until SIGINT or SIGTERM, then drain
end

The Space API, in Ruby.

  • Matchers. A where: value can be a plain value, a Range (priority: 3..), an Array (one_of), nil, a Regexp, or a clause string of the portable grammar ("priority>=3"). A Regexp or a block filter runs on this replica only, and a Regexp runs under a timeout.
  • Blocks as take bodies. space.take(Order) { |o| Shipment.new(...) } completes with the block's result, or with none on nil. A block that raises leaves the take to lapse.
  • Numbers are seconds. lease: 30 is thirty seconds, as with sleep. The Python client reads an integer as milliseconds. Strings ("250ms", "10m", "PT10M") mean what they mean in Java.

Hosts and AI.

  • agentspaces-rails reads config/agentspaces.yml through config_for and loads agents from app/agents. bin/rails agentspaces:work serves them; a web process writes through a lazy, per-process peer that a forked worker restarts.
  • agentspaces-ruby_llm turns the fleet's AgentCards into RubyLLM tools, and AgentSpaces::Lease.keepalive renews a take while a model thinks.
  • agentspaces-mcp serves the same actions as MCP tools.

The Ruby guide has the quick start, the features, and worked examples, and the agentspaces-rb repository has the source.

20.8 Rust: a fleet member, typed entries, and the aspace command

Main documentationThe Rust guide is the main documentation for Rust: how to build agents step by step, the features specific to the language, and complete examples. This section summarizes it for readers who know the Java chapters.

Use agentspaces-rust to write peers in Rust, or to bring scripts, CI jobs, and coding assistants into a fleet with one binary. It is a standalone repository of seven crates that go with AgentSpaces 0.7.0, built from a clone because they are not on crates.io (their Cargo.toml still reads 0.5.0):

  • agentspaces-wire is the protocol core, with no I/O and no runtime: the CBOR codec that writes Java's bytes, identities and certificates, the claim lattice, and the space fold.
  • agentspaces is the peer on Tokio: Fleet, the space verbs, typed entries, workers with AgentCards, remote actions, the fleet catalogue, the fleet YAML, the keystore, and a blocking facade.
  • agentspaces-derive is #[derive(Entry)], which binds a struct to its wire schema.
  • aspace is the command: every verb from a shell with JSON in and out, aspace work to run any program as a worker, aspace daemon, and aspace mcp.
  • agentspaces-mcp is FleetMcpServer, the fleet's catalogue as MCP tools over stdio and Streamable HTTP.
  • agentspaces-pdt is persistent values over the content swarm: map, set, and tree refs, and the file share.
  • spacewalk is a terminal UI that shares files from a local directory into a space and pulls them back, exactly as the Groovy console's file sharing does.

An entry is a serde struct with a schema attribute. rename_all = "camelCase" gives each field the wire name of the matching Java record component. An agent is an async function bound under fleet.agent(name): its reply completes the take, and an error lets the take lapse for another worker.

// agentspaces-rust -- quickstart/src/main.rs, trimmed
#[derive(Debug, Serialize, Deserialize, Entry)]
#[entry(schema = "shop.Order#v1")]
#[serde(rename_all = "camelCase")]
struct Order {
    order_id: String,
    item: String,
}

let fleet = Fleet::join_config(&Config::load("fleet.yaml")?).await?;
let worker = fleet
    .agent("fulfiller")
    .describe("Ships orders")
    .take("orders", Lease::parse("30s")?, ship)   // ship: async fn(Order, TakeContext)
    .action("ship")
    .produces::<Shipment>()
    .bind()
    .await?;
worker.stop_on_signals().await?;                           // until SIGINT or SIGTERM

What it has, and what it does not have yet.

  • Transports. The peer dials tcp and tls (TLS 1.3 with a channel certificate that the identity key endorses). It joins through a seed, any peer that listens. Started with listeners, a Rust peer is itself a listening member that others dial (aspace seed from a shell), so Rust peers can form a group with no other implementation in it. A listening Rust peer does not dial the members it learns of, so members reach one another through it. A plain tcp seed is refused off loopback unless the profile is dev-local.
  • Verbs. Write, read, take, complete, watch, and notify, typed and untyped; remote actions in both directions; and the catalogue that aspace call and MCP hosts use.
  • Not yet. The vote, aggregate, semantic discovery, and connector capabilities; the ordered log; parts of the content swarm and persistent values (no escalation above 4 MiB, no linear swap); session attestation; a full mesh; and the ws, http, QUIC, DTLS, and WebRTC transports. A JVM peer has all of them, and the Rust guide's table of what is not built yet names the other languages that have each.
  • Version. The crates follow the core's version and are at 0.7.0, on wire version 3, with the timing and loop rules of the other 0.7.0 peers. The repository tests them against a scripted Java seed, and against the golden vectors for the features the crates have. They reproduce those vectors byte for byte and refuse the hostile inputs.

The Rust guide has the quick start, the features, and worked examples, and the agentspaces-rust repository has the source.

aspace://guide/appendix

Appendix: how it works and why

This appendix explains how AgentSpaces does what the chapters describe, and why it works that way. You do not need it to use the product. Each part names the chapter it supports and links back to the section.

Quick start

What the BOM manages, and why Spring Boot projects import it

The bill of materials, agentspaces-dependencies, manages the version of the core AgentSpaces modules:

  • the fabric, the transports, and the starter;
  • the console and the A2A gateway;
  • the Embabel extension and the test support.

It also manages the versions of Jackson, Caffeine, Nimbus JOSE+JWT, and BouncyCastle. The bridge projects for Spring AI, Micronaut, and LangChain4j are not in it and carry their own version.

A project that inherits from spring-boot-starter-parent or applies the Spring Boot Gradle plugin still imports this BOM.

Back to the quick start.

One fabric, several ways to build

Longer notes on the pattern table

These notes carry the detail that the pattern table leaves out.

  • Fan-out and within. A join's within only makes the join forget a key whose parts stopped arriving. It fires nothing, which is why a timeout that must act uses the deadline pattern.
  • Route. A where filter is compiled onto the template and judged before a take claims.
  • Running total. The @SpaceReduce accumulator is an entry beside its elements. Each element's own atomic completion advances it, and a ticket serializes the steps per key.
  • Settled estimate. The estimate @OnEstimate watches is the push-sum estimate. A settle step is a gossip round.

Back to the pattern table.

Agents and the binder

Where the space checks tag filters

The binder compiles tag filters onto the method's template. The space therefore judges them after the type comparison and before it decodes the payload.

Back to the conventions they share.

Work: take, notify, bid, ref

How the binder applies field filters

The binder compiles where filters onto the method's template the way it compiles tags. For @SpaceTake, the space judges them before the worker claims anything, which is why a task addressed to another shop is never leased by this worker. For @SpaceNotify, the filters are compiled onto the subscription's template, so the method sees only the entries that pass.

Back to @SpaceTake or @SpaceNotify.

Why the bid, the worker, and the handle share one object

The dining planner is the shape worth studying, because it answers the organizing question directly: the bid function, the worker, and the space handle live in the same object. That is deliberate.

A bid is a statement about what this particular agent would charge. It needs the same state the work needs: the model it would call, the queue it is already sitting on, the region it runs in. Splitting them apart would mean keeping two things in sync for no gain.

Back to @BidFunction.

Decide and sense

What @Ballot replaces in a hand-written panelist

Because the cue is the proposal record, the ballot can never be refused as "unknown proposal". Every hand-written panelist had to defend against a two-entry race. With @Ballot that race does not exist.

Back to @Ballot.

How the binder tracks a decision

Underneath @OnDecision, the binder watches ballots and proposals in the vote space and recomputes the decision on each. That is why a replica that learns of a vote late still fires once, on its first qualifying ballot.

This replaces the decision() poll loop that every consumer of the vote used to write.

Back to @OnDecision.

What @Propose replaces in a hand-written lead

Before @Propose, every lead carried three pieces of code: a VoteCapability field, a proposed set, and a read-before-propose guard. The annotation replaces all three.

Back to @Propose.

How the settle rule runs

The aggregate capability evaluates the settle rule after each of its own rounds, and once more at an epoch's last change plus the span, so no thread polls for a settled value and a quiet epoch still settles. The listener runs on a virtual thread, so a slow reaction never holds the peer's loop.

This replaces the awaitEstimate loop that every supervisor used to carry.

Back to @OnEstimate.

Why the estimate trusts every contribution

The capability never proves convergence, and a settle rule does not detect a poisoned value. Push-sum takes every member's contribution at face value. A member that contributes a wrong number moves every replica's estimate in the same way a right one does.

The design accepts that risk. That is why the main text asks you to size settle for the spread of your contributions, and to put a vote behind any estimate that commits the fleet to an action.

Back to @OnEstimate.

Exactly once and fan-in

How the ordered log decides a take

@OrderedTake routes the take through the space's ordered-log coordinator instead of the space's own claim race. The log's commit order then decides every take identically on every member, so each entry is completed at most once, fleet-wide.

This closes what the space chapter used to call "the one place the annotations cannot reach". The member set is still fixed and still yours to supply; that has not changed. The AtomicReference cycle that wired the log to its coordinator is gone, because OrderedTakes.over(...) does it.

Back to @OrderedTake.

How tickets keep the steps of one key apart

A JoinTicket per key, taken before a drain and completed after it, serializes the steps of one key. A reducer whose ticket is not the key's oldest live one backs off.

Under ORDERED, the ordered log decides which ticket holds the key. Under LEASED, the older-ticket check is exact within one process and best effort across replicas. So only ORDERED guarantees that two reducers never fold one key at once.

This is the third form of reduce. The gather folds a bounded set per key once, and the aggregate folds a number across the fleet. @SpaceReduce folds a stream per key, with a value that is always current, exact, durable, and readable as an entry by any peer or client.

Back to @SpaceReduce.

What the PetClinic slot book replaced

The PetClinic scheduler used to keep its slot book in two AtomicIntegers. A restart reset them, and a second scheduler duplicated them. The flagship's test now runs two schedulers through a restart and books every visit once.

Back to @SpaceReduce.

Embabel integration

Why the bridge generates a class, and why old generations stay

For the GOAP planner, EmbabelRemoteActions generates a class annotated @Agent with one real typed @Action method per remote action. It does this because the planner conditions on method signatures.

Embabel's platform exposes no undeploy in the API this module reaches. So each redeploy registers a new generated agent, and an action that disappears is absent only from the next generation. The previous generation stays registered until the platform restarts.

Back to Inbound: remote actions for the planner.

Why data moves one way, and why a realm names no spaces

A realm and a group have different owners. The realm's side owns the meaning: the type names, the producers, the queries, and the API documents. The group's side owns the operation: the cards its members publish, the flows its reconciler applies, and who may serve what. An import sits between them: it drafts records from the realm, and a person approves them.

An import is therefore a one-way copy. An import that wrote back would let a running fleet change the domain model under the people who own it. Importing the same realm again drafts new versions of the same records, and nothing in force changes until a person approves it.

A realm names no spaces, because a space is a decision about operation. A lane carries a strategy, an admission rule, and its retention, and those belong to the group. The lanes come from the flows the realm's APIs become and from the group's own lanes. One import targets one group and creates none.

The type names are what both sides share. They become entry types under the realm's namespace, so a planner's goal, a flow's cue, and a worker's take name the same IRI. On the JVM, the schema registry gives a record class that name on the wire.

Back to Data in a fleet: realms and the two worlds.

Spring AI integration

How the model service relies on the model and tool-loop split

The design leans on Spring AI 2.0's split between the model and the tool loop. ChatModel.call performs one round-trip and never runs tools. So a server that implements one round-trip for a caller never executes anything on the caller's behalf.

Tool calls come back in the assistant message. The caller's own ToolCallingAdvisor then runs them, with the caller's own tools.

Back to Model access as a fleet service.

Micronaut integration

How enrollment finds beans, and why AOP hides annotations

Micronaut singletons are lazy, so nothing waits for a bean to be created. That is why the library enrolls agents on StartupEvent: it finds the bean definitions itself, instantiates them, and binds them.

The agent is a plain bean on purpose. A Micronaut AOP interceptor binding (@Retryable, @Cacheable, @Transactional, a custom @Around) generates a subclass. The subclass's overriding methods carry none of the fleet annotations, and the binder reads the runtime class. So such a bean fails at startup, saying so.

For beans with only method annotations, the processor maps each core method annotation, by name, to a marker. The marker is @Executable(processOnStartup = true), the way Micronaut's own @Scheduled works, and @ReflectiveAccess. Micronaut then hands every such method to the library before StartupEvent, and the bean is enrolled once.

Back to Agents and enrollment.

Why the bridge applies the tool provider itself

micronaut-langchain4j never looks a ToolProvider up on its own. So the bridge applies FleetToolProvider to every @AiService as the service is built, under tools.auto-apply.

@AgenticService agents receive the provider by themselves, since the agentic factory looks one up by agent name or default.

Back to LangChain4j: three ways to use a model on the fleet.

Why the bridge sets the MCP tools capability

The bridge makes the server advertise the tools capability even when it has no tools of its own at startup. The SDK refuses to add tools to a server built without that capability, and the fleet's tools arrive later, as cards do.

Back to MCP: the fleet's edge, in both directions.

What the library's own tests prove

The library tests its features with ApplicationContext.run(Map) contexts. They prove three things:

  • The fabric, the registry, management, the console, the A2A gateway, the fleet tools, the model service, the capability tools, and the MCP export stay off until their property is set, or switch off with it.
  • An application Embedder replaces the default.
  • The per-service customizer opts one service in.

Flow tests across two peers over TCP on free ports cover the paths that cross the fleet. The examples' tests boot two or three peers in one JVM with scripted models.

Back to Verify the behavior you rely on.

How the library reuses the Spring starter's wiring

The published agentspaces-spring-boot-autoconfigure jar carries no Spring classes; it compiles against provided-scope stubs. Its properties POJO, Authorizers, DirectiveGates, and build methods have no Spring type in their signatures. So the JVM loads them and ignores the Spring annotations it cannot resolve.

A Micronaut @Factory binds the agentspaces subtree of the environment into that POJO and calls those methods. The binding is a Jackson conversion: kebab-case keys to setters, lists of maps to groups and spaces. The transport, TLS, group, space, key-ring, and capability wiring therefore lives in one place for both frameworks.

The suite runs with no Spring on the classpath and pins that assumption. A core release that puts a Spring type in a reused signature fails the library's build before it can reach an application.

Back to How it is built.

LangChain4j on any host

How the runtime reuses the starter's build methods

FleetRuntime builds the peer with the starter's own build methods. Those methods carry no Spring type and run with no Spring present.

The Micronaut bridge does not use the LangChain4jFleet facade. It builds the same parts (the tool provider, the listeners, the model client and server, the usage publisher) as Micronaut beans through its own factory.

Back to LangChain4j on any host.

The wire package name and the golden byte tests

The package stays ai.badmonkey.agentspaces.springai.model.wire, where the records were born. Renaming it would change the schema name on the wire.

WireGoldenTest pins the canonical CBOR bytes of every record in wire-golden.properties, shipped inside the jar. Each consumer's suite reads the same vectors.

Back to The model wire records: agentspaces-model-wire.

The Space API

How arrival order decides a claim

Under LEASE_RACE and AUCTION, a claim is judged partly against what the replica has already merged, so the outcome depends on arrival order.

  • A back-dated first claim on an unclaimed entry holds at every replica it reaches before an honest one.
  • Two replicas that merged different first claims keep different winners, and anti-entropy does not reconcile them.
  • An honest claim arriving from a healed partition is refused where a newer claim merged first.

Narrow TAKE scope, or reach for ORDERED, where strict fairness or convergence on the winner matters.

Back to conflict strategies.

Why repair by entry costs the same at any size, and why a renewal may not shorten a lease

Before 0.7.0 two replicas that disagreed exchanged a digest of the whole space: a line per entry. The cost grew with the space, even when only one entry differed. The fingerprinted tree changes that. Each node of the tree holds a hash of everything under it, so two replicas compare the root, follow only the branches whose hashes differ, and reach the differing entries in a few round trips. Measured on the reference implementation, one audit round for a single difference is 7.5 to 9.4 KB and 5 to 6 round trips, flat in the space's size. A 100,000-entry join over TCP took 11.85 s, against 164 s before.

The byte budget keeps any one answer small. A late joiner asking for a large space gets it in pieces, each answer saying what remains, so one request can never make another member build and send a huge frame.

The per-entry horizon rests on the renewal rule. A withdrawn entry can be forgotten early only if no replica can still hold a copy with a later expiry. Only the issuer renews an entry, and a renewal never shortens it, so the withdrawal carries the largest expiry any copy has. Every present copy has lapsed by that expiry, and five minutes later it is past its own collection horizon. The ten-minute floor also covers a replica whose clock trails by up to the drift ceiling of ten minutes. A member without the hint might renew another way, which is why one such member in view returns every withdrawal to the older, longer horizon, and why the node waits before it takes up the shorter one again.

Back to replication by entry.

Discovery

How the ads stream spreads cards

The ads stream is the group's advertisement gossip. Two mechanisms run on it. Rumor spreads a new card fast, and anti-entropy brings a late joiner up to date.

Back to cards, the ad cache, and the ads stream.

How semantic discovery handles vectors

Vectors are L2-normalized and cached by the text's content hash, so a card is embedded once.

The embedder's identity is advertised on the capability, so a query goes only to peers that rank alike. A fleet therefore never averages two models' notions of similarity.

Back to semantic discovery and embedders.

Capability services

When each service runs

One loop per peer runs the whole stack. Membership probing, gossip, space anti-entropy, and capability protocols each register jobs with it, and each job runs when its deadline comes up or when a frame or a change asks for it. A provider is driven because it is registered, the same way a replicated space converges because constructing it joins that same loop.

Push-sum gossip rounds keep their own pace, so the aggregate's convergence follows its rounds. Convergence takes a few dozen rounds, so the round period is what turns "converges in O(log N) rounds" into a wall-clock number. The aggregate gossips once per PushSumAggregate.ROUND_PERIOD (one second) while any epoch is active, and sleeps until the next eviction once every epoch is quiet.

The other services:

  • The ordered log sends its leader's heartbeat every 250 ms on a deadline of its own, and republishes its card at a role or term change and at half its lease, not on every round.
  • Gossip learning offers each model once a second.
  • Vote and semantic discovery are request/response and need no clock at all. They run only on the card refresh.
  • Key wrap runs when a holder's card changes, when a fetch ends, and at its next rotation.

Back to how a capability is used.

Why the aggregate needs its two rules

Both rules were learned on the wire.

The participant rule exists because push-sum moves mass. A bystander peer, such as a console or a client that has not started the capability, would otherwise swallow mass it would not mix back.

The Settle rule counts only rounds this node took part in, or a quiet epoch, which completes the streak. Halving leaves a node's own ratio untouched, so a node nobody pushes to is stable by construction and says nothing about the fleet. A node with no participant at all judges its own rounds, because its value is the only estimate there is.

Back to the aggregate.

What OrderedTakes and registration do for you

OrderedTakes.over(...) hides a circular wiring that both halves need: the log's apply callback must reach the coordinator. Earlier releases made every consumer write this by hand with an AtomicReference.

On a started node the log keeps its rules in time: a heartbeat every 250 ms and an election timeout of 1.25 to 2.25 s, whatever tick-millis says. The leader lease it advertises is that timeout in wall time, so it is truthful. The log republishes its card at a role or term change and at half its lease, so role=leader is discoverable as soon as the new card spreads after an election, rather than on the next five-minute card refresh.

Every replica authenticates a completion against the holder's own signed claim, which the log carries through unchanged. This includes a replica that holds no claim of its own, like the desk. That is what lets finished work drain everywhere, instead of reappearing when its TAKE lease lapses.

Back to the ordered log.

How pairwise averaging reaches the mean

The mechanism is randomized pairwise averaging, which contracts the spread geometrically. So a fleet lands within tolerance of the mean in O(log N) rounds.

Models travel content-addressed, with a mass-conserving offer-and-accept exchange. Each completed pairwise average preserves the fleet mean, so under pure averaging the answer does not drift. A lost ACCEPT breaks that: it can move mass one-sidedly.

Back to gossip learning.

Large data

How the fetch scheduler picks pieces and holders

The scheduler reads the holdings and asks for the rarest piece first, from every reachable holder. It keeps a window of ranges per holder that grows on success and halves on a timeout, and it prefers direct holders over relayed ones.

Near the end, it requests the last pieces from everyone and cancels the duplicates. It verifies every piece against the manifest, and strikes a holder whose piece fails.

A fetcher seeds from its first verified piece. It tells its sources what it gained between holding refreshes, so a seeder's death does not stop a transfer.

Back to publish and fetch.

Why a tree, and what a delta costs

A block or an artifact is one hash over the whole payload, so two versions of a value share no bytes, and a space seals each payload under a fresh nonce, which hides even equal bytes. A persistent value names every node by the hash of its bytes, so sharing is a property of the layout: a 32-way trie makes an update create about log32(n) nodes, four for a million entries. That is the delta, and it is the same size on the wire as in memory.

Equal values must have equal roots on every peer, so the layouts are canonical. The map is a CHAMP trie (compressed, compacted after every removal) over sha2-256 of the key's canonical bytes, so the shape depends on the key set alone. A dense vector's shape is a function of its count. A blob is cut by FastCDC, so a cut point depends on the bytes around it and an insert moves the cuts only near the edit; the index above the chunks is a prolly tree, whose node boundaries also depend on content, so the same holds one level up.

A reader asks with TREE_WANT, naming up to 64 roots it already holds. A holder walks the new tree breadth first and prunes every subtree it finds under one of those roots, so the bytes it sends are the delta and nothing else. When no holder has a root the reader named, the holder sends the top two levels and the reader continues node by node from what its own store lacks.

A ref keeps its version graph in the heads' base lists, and each head also links a chain of version nodes in the store, so the graph survives a restart. Concurrent heads merge three-way against the lowest common base, with a deterministic rule for a key changed on both sides (the later issued stamp, ties by issuer id), so every reader computes the same value without writing. The store keeps the last 64 versions or an hour per ref as delta bases, and collects the rest from the pinned roots.

A relaxed vector keeps the shape its edits leave, with a size table on each relaxed node, so an edit in the middle copies only its path. Its root therefore depends on its history, which is why equality compares the packed form. A text is a Fugue sequence: every character keeps an id from its replica and a counter, and two replicas' texts merge by the union of their characters in one tree order, so no edit is lost and nothing needs a resolver.

A pushed delta travels on the same gossip tree as every rumour: one eager copy per eager edge, and an announcement by hash on the lazy edges, so a member that misses a bundle asks for it. A follower waits for the bundles a head announces, then fetches what is still missing.

Back to values that change.

How a sealed node stays verifiable

Under sealed-nodes, the writer seals each node deterministically with AES-256-GCM-SIV under a key derived from the epoch's content key, and its nonce is keyed under that key, so the nonce in the clear confirms no guess. The sealed envelope carries the plaintext's links in the clear, and the CID names the envelope. A member without the key can check every node against its CID and walk the tree, and two equal nodes of one epoch seal to the same bytes, which keeps sharing inside an epoch.

Back to values that change.

How stores pin, prove, and reconcile

A pin is a SignedPin entry in the content space. It carries the pin's terms (root, kind, lease, copies, requester, up to eight roots the store may already hold) and a signature over them for this group, with a deadline at most an hour ahead. A store takes it under the space's conflict strategy, the way any take works, and only when the key hashes to the requester and the signature verifies. When the pin asks for more than one copy, the first store writes the requester's own signed pin again with one copy fewer left, so the next store takes it. A store charges only the member who signed the pin.

A challenge is the content swarm's message tag 12. The requester names up to 16 random nodes of the root, or random chunk groups of a blob, and the store answers with the bytes within 2 s plus eight round trips. The requester checks each by its CID, or by the blob's outboard, so a blind store can answer without the key.

Two stores reconcile the sets of roots they hold with negentropy, a range-based set exchange of fingerprints, carried in the tree exchange's reserved sketch field. A small difference can also go in one round as a rateless invertible Bloom lookup table. Each side then fetches what it lacks through the usual tree fetch.

Back to a store for the fleet.

How a verified window checks each group

BLAKE3 hashes a blob in 1 KiB chunks and joins their chaining values pair by pair up to one root, the identity. So the hash of any aligned run of bytes leads to the identity through the parent pairs above it.

The outboard keeps those parent pairs for groups of 16 KiB in bo nodes. A leaf node covers up to 512 groups (8 MiB), and an upper node links up to 16 children.

For a window, the reader fetches the chunks that cover it and the bo nodes on its path. It hashes each group as its bytes arrive, joins that hash with the stored pairs up to the identity, and hands the group over only on a match. A forged group fails on its own, and the reader never needs the rest of the blob.

Back to verified windows.

Peering, identity, and transports

How membership probing and gossip work

Membership is SWIM-style probing with leased membership: a member that stops answering probes drops from the view on its own when its lease lapses, with no one having to remove it. Why the member TTL grows with the group explains how long that lease is.

Two gossip channels carry state. Rumor spreads a change fast. Anti-entropy guarantees completeness, and it is paced by the group's own gossip period. A signed RevocationAdvertisement gossips like any other advertisement, with anti-entropy, so late joiners converge on it.

Back to Peering, identity, and transports.

How DTLS is made reliable and survives address changes

A small recovery sublayer makes each DTLS association reliable and ordered, so nothing above the transport changes. Connection ID (RFC 9146) keeps an association alive when a peer's address changes behind a NAT.

The bare udp binding runs the same recovery sublayer over plaintext UDP.

Back to Peering, identity, and transports.

The frame layout of each scheme, and session attestation

ws carries one binary message per frame under the subprotocol aspace.1. The http and https exchange works in three parts: POST /open, batched frames up under Aspace-Seq, and a 25 s long-poll down under Aspace-Ack.

On an unattested link, both ends in session mode run session attestation inside it. After the hello, frames travel tagged rather than signed.

Back to WebSocket and the HTTP exchange.

How the WebRTC signal travels and attests the remote peer

A signal goes directly when the target is connected. Otherwise it travels inside a RELAY_FRAME through a relay member, which is the one relayed frame a node under require-attestation admits.

Each side signs the DTLS fingerprint of a certificate it generated for the connection into its signal. So the channel attests the remote PeerID.

Back to WebRTC.

Why attested mode saves work

The envelope signature authenticates one hop. When the transport has already authenticated the channel, that signature is repeated work, at roughly a thousand times the cost of serializing the frame. Attested mode drops it on links whose peer the channel attests.

Back to Peering, identity, and transports.

Why replays never strike

Replayed frames and unadmitted peers deliberately never strike. That is what keeps quarantine unweaponizable: nobody can turn it against another peer with frames that do not show a fresh, witnessed violation.

Back to Peering, identity, and transports.

How relays advertise, choose, and forward a path

Until 0.4.0, relaying was one hop. The origin handed the frame to the first relay it could reach, and a relay never forwarded to another relay. So two dial-only members behind different sites' relays could not exchange addressed frames.

Since the large-data revision, the view carries the relay graph:

  • A dial-only member advertises the relays it holds links to under the hint relay.via.
  • A relay advertises the relays it holds links to under relay.links, and relays dial each other.

The origin computes the shortest path over that graph. It starts from the relays it is attached to (or, when none reaches, the relays it could dial) and ends at the relays the target is attached to. It breaks ties on the lowest hash of the path, so every origin converges on the same route to a target.

The origin pins the path per target for the life of the flow. Every send to that target follows the pin, the pipes of every capability and block wants included.

The frame carries path and hop. A relay that cannot deliver forwards once to the next hop, with its own policy and budget applied, and refuses a malformed path. When it drops a frame, it sends the origin an unreachable signal (aspace:cap/relay-signal) through its own ordinary send. The origin consumes the signal before any capability sees it.

Stickiness is what keeps a flow on one route. Without it, a flow would spread across equal-cost relays, reorder, and never trip the relay offload that opens a direct channel.

Back to Relay paths.

How the loop, the watchdog, and the slow-down work

Earlier releases ran every job of every group on a fixed 250 ms tick, plus a second timer that flushed outboxes fifty times a second. An idle node woke about 3,000 times a minute to find nothing to do.

Now each job reports its next deadline, and the node keeps one timer armed at the earliest one. A wake is idempotent: a wake that lands during a run causes exactly one more run, so no wake is lost and none piles up. Every 15 seconds a backstop run asks every job, and counts any that had work due without asking (it ran every second until the 0.7.0 audit showed every wake had a test). The tests assert that count stays at zero, so a missing wake shows up as a failing test, not a stall.

The watchdog does a different job. The backstop lives inside the loop, so it cannot notice a loop that stopped running altogether. The watchdog lives outside on its own platform thread and reads each loop's heartbeat with no lock. It finds a missed timer, a lost wake, a dead thread, and a job stuck for 5 s. A restart moves the queued work to a fresh run under a new generation, and a late run of the old generation changes nothing, so two runs of one loop never overlap.

Loop work runs on its own pool, not on the virtual threads' carriers. A burst of application work on every carrier therefore cannot delay probes. When the pool is at its maximum and runs stay late, the node slows only work no peer judges it by. It renews every lease and re-issues every advertisement with a span that covers the slower pace before it slows, so no peer ever sees a lapse.

Local periods run on a monotonic clock, so a wall-clock step neither expires a whole view nor keeps a silent member. Anything a peer reads, such as stamps, leases, and expiries, stays on wall time. After a suspend the node re-introduces itself and probes each member once.

Back to the node loop.

Why the member TTL grows with the group, and how a dial-only peer is probed

A quiet node probes one member per probe period, so it reaches each member once per cycle. At ten members a quiet cycle is about 36 s. Under a 30 s member TTL, a member heard only through those probes lapsed between them, and measured runs showed most members dropping an idle dial-only peer within 12 minutes.

The member TTL now exceeds the cycle that renews it by half. That is the rule for every TTL in the core: about 1.5 times the cycle that renews it. The probe order is also kept from one cycle to the next, so the gap between two probes of a member is one cycle, not up to two.

A member that sends its own frames, as every Java member does, is renewed far more often than once a cycle, so 45 s suffices for it at any size. The node's own keepalive keeps the 30 s schedule, because peers of other releases and languages still judge it by 30 s. Each side only waits longer. Nobody is dropped sooner.

A dial-only peer has one link, to the member it dialled, and it names that member in its advertisement. A member with no link of its own to the peer once sent a ping that went nowhere, then asked two random members to try, and only one draw in four found the holder. Now it asks the named holder at once. The holder pings the peer over its link and passes the answer back. If that fails, the member asks once more with random members added before it gives up. A node credits a peer only from a relay it asked, so a peer cannot vouch for itself by naming holders.

Back to TTLs and dial-only peers.

Why the redial waits cycle, and why a wake is checked at once

A peer-to-peer node cannot know whether a seed is gone for good or back in a minute, so it never stops trying. The waits come from a short fixed table that wraps, 5, 10, 20, and 30 s, rather than a backoff that grows without end. A seed that comes back is found within 30 s, and a dead one costs one dial every half minute or so.

The table restarts only after a link that held for 5 s. A seed that accepts and then drops at once would otherwise restart the table each time, and the node would dial it in a tight loop.

The 250 ms stagger follows the Happy Eyeballs rule of RFC 8305. A first seed that never answers costs 250 ms, not a whole connect timeout, and when every seed is up the first in your list still wins. Counting a verified frame as the answer, not an open socket, keeps a seed whose kernel accepts connections but whose node is hung from winning.

The monotonic clock does not count a sleep. A renewal or a PING timed on it after a two-hour sleep would come as if no time had passed, while every wall-time lease has run out. So a wake is a signal of its own: the node checks its seed link and every take it holds at once, against the wall clock, and acts on what it finds.

A frozen process is the opposite case. Both clocks count on, so no jump is seen, but the process did nothing for the whole pause. The first timer to fire after it is late by about that long. Treating that lateness as a wake catches the pause, and probing each member before judging it keeps the node from dropping every member it could not hear while it was stopped.

A dial runs on a thread of its own because a connect to an address that never answers waits for the whole connect timeout. On the node's loop that wait would stop every other duty with it.

Back to Seeds, wakes, and takes.

Why lost members retire, and why isolation touches readiness, not liveness

A peer-to-peer node cannot tell a member that is gone for good from one that is back in an hour. So it keeps trying for a long time, 24 hours by default, on a fixed table that ends in a five-minute wait. A member that comes back is found within minutes, and one that is gone costs one dial every few minutes. At most eight lost members are dialed per round, so a node that lost a whole site does not open a storm of connections at once.

A retired member's last address is kept, because a node whose seeds and locator find nobody may still reach a member it once had. It is used only as a last resort, and only when you opt in: by then the address may belong to another host, which would learn of this node from the card it is sent.

Readiness and liveness answer different questions. Readiness asks "should this process get traffic?", and a node that cannot reach its fleet should not. Liveness asks "is this process broken?", and a restart rarely brings a fleet back. Restarting every node of a fleet that is gone only makes them all loop. So isolation turns readiness off and leaves liveness alone, while a broken node loop, which a restart does fix, turns liveness off (loop health).

Back to membership status.

Security

How agent certificates are signed, and why back-dating is possible

The peerSignature in an AgentCertificate is the peer's Ed25519 signature over the rest of the certificate, in canonical CBOR.

A receiver judges a certificate at signing time, so that history stays verifiable after the certificate expires. The cost is the back-dating window. Judging at signing time means a stolen agent key can sign with an old stamp, inside a window that was valid.

The HLC drift bound stops a stolen key from signing into the future. Nothing stops it signing into the past, and that is what revocation with key-compromise is for: it refuses everything the key signs from then on, whatever its claimed time.

Back to Agent certificates.

Where the content-key rotation bound comes from

Random GCM nonces bound one key to about 232 encryptions, and that budget is shared by every writer in the fleet. No node can count other nodes' writes, so the fleet cannot rotate by count. It rotates by period instead, chosen so the whole fleet's write rate stays well below the bound.

Back to Content encryption and rotation.

Why a fleet that never opts in is unaffected by mixed versions

The v0.1.13 fields are appended and omitted when absent, so a fleet that never opts in keeps every byte.

Back to Things to think about.

The fleet console

Why the console needs no instrumentation

The console is a peer like any other. It reads the same replicated state every agent reads, so it needs no instrumentation, no agent, no sidecar, and no export. There is nothing to wire up, because the coordination state is the telemetry.

Back to The fleet console.

Other languages

How wire version 3 encodes signed maps

Wire version 3 is enforced. Every map a signature covers is encoded with its entries in canonical order: shorter UTF-8 keys first, and bytewise between keys of equal length.

So the signed bytes of a structure depend on its content alone, in every language. That is what lets a structure signed in Java verify in Python or TypeScript, and the reverse.

Back to Other languages.

How the Groovy agent DSL and fleet DSL reach the Java binder

The agent DSL writes a Java interface at run time, one annotated method per clause. It compiles the interface once per shape and binds a proxy over it. The binder reads the annotations through the interface exactly as it reads a Clojure reify.

The fleet DSL emits its camel-cased keywords as the kebab-case tree the runtime's loader binds.

Back to Groovy.