Prewritten Protocols
The astra-protocols library contains ready-made implementations of some common interaction protocols. How interaction protocols work, and how to write your own, is explained in Interaction Protocols.
To use the library, add it to your project’s pom.xml:
<dependencies>
<dependency>
<groupId>com.astralanguage</groupId>
<artifactId>astra-protocols</artifactId>
<version>2.8.12</version>
</dependency>
</dependencies>
The request, subscription and auction protocols are agent programs in the astra.protocol package; concession protocols have their own subpackages. You use one by inheriting from it (with extends) and then overriding the plans that decide what your agent does at each step of the protocol. The request, subscription and auction programs contain the plans for both roles: the agent that starts the conversation (the initiator) and the agent that responds to it (the participant). The protocols are written using encapsulated goals, so the plans that handle the replies to a conversation are only active while that conversation is going on.
Protocol |
Program |
Initiator goal |
Participant goal |
|---|---|---|---|
FIPA Request |
|
|
|
FIPA Subscribe |
|
|
|
First-price auction |
|
|
|
Vickrey (second-price) auction |
|
|
|
Bilateral monotonic concession |
|
|
|
Multilateral concession |
|
|
|
FIPA Request
FipaRequest implements the protocol described in Interaction Protocols. Actions are represented as funct terms, such as greet("world").
The participant adopts !monitor_action_requests() and overrides two plans:
Plan |
Purpose |
|---|---|
|
Set |
|
Perform |
The initiator adopts !request_action(target, act) for each request, and can override +!agreed_request(funct act), +!failed_request(funct act) (the request was refused) and +!succeeded_request(funct act, funct outcome) to react to the replies. After a success or refusal, normal completion of the corresponding hook ends !request_action(...) and its caller continues. An execution failure reply instead fails the goal through system.fail(); handle it with try/recover or a goal-failure plan. A missing reply has no built-in conversation timeout in this implementation.
In this example, a Requester asks a Responder to greet the world:
package demo;
agent Responder extends astra.protocol.FipaRequest {
initial !monitor_action_requests();
plan +!evaluate_request(string name, greet(string who), boolean result) {
result = true;
}
plan +!execute_request(string name, greet(string who), funct outcome, boolean result) {
console.println("Hello, " + who + "!");
outcome = greeted(who);
result = true;
}
}
package demo;
agent Requester extends astra.protocol.FipaRequest {
plan +!main(list args) {
system.createAgent("responder", "demo.Responder");
!request_action("responder", greet("world"));
console.println("request finished");
system.exit();
}
plan +!agreed_request(funct act) {
console.println("responder agreed to: " + act);
}
plan +!succeeded_request(funct act, funct outcome) {
console.println(act + " succeeded with outcome: " + outcome);
}
}
[main] responder agreed to: greet("world")
[responder] Hello, world!
[main] greet("world") succeeded with outcome: greeted("world")
[main] request finished
The Responder’s plans only match greet(...) actions; any other request is handled by the default plans, and refused.
FIPA Subscribe
FipaSubscribe lets agents subscribe to channels that another agent publishes information on.
The participant (the publisher) adopts
!monitor_subscriptions(), and has achannel(name)belief for each channel it offers. It can override+!evaluate_subscription(string channel, boolean result)to decide whether to accept a subscription (by default, all are accepted), and adopts!publish(channel, message)to send afunctmessage to every subscriber of a channel.The initiator (the subscriber) adopts
!subscribe(target, channel). It overrides+!handle_content(string channel, funct message)to process the messages it receives, and can override+!subscription_accepted(...),+!subscription_refused(...)and+!subscription_cancelled(...). It adopts!cancel_subscription(target, channel)to unsubscribe.
Auctions
FirstPriceAuction and VickreyAuction implement sealed-bid auctions: the auctioneer sends a call for proposals (cfp) to every participant, waits for a fixed time, and then accepts the best bid. In a first-price auction, the winner pays the amount it bid. In a Vickrey auction, the highest bidder wins but pays the second-highest bid, not its own bid.
Second-price calculation
ASTRA 2.8.11 tracks the two best bids independently, so the payment does not depend on bid evaluation order. For bids 10, 30 and 25, the bidder offering 30 wins and pays 25, whether 25 is evaluated before or after 30. With the default comparison, tied highest bids retain the first encountered winner; the other tied bid makes the second price equal to the winning bid. The compare_bids hook is used for both winner and runner-up ranking when an application customizes the ordering.
Earlier versions: ASTRA 2.8.10 updates the second price only when it finds a new highest bid. For bids evaluated as 10, 30, 25, it can charge 10 instead of 25. Use ASTRA 2.8.11 or later for the corrected calculation.
The correction does not introduce a reserve-price policy. With no bids there is no winner. With only one accepted bid, the existing implementation still uses −1 as the missing-second-price sentinel; applications should require at least two valid bids or supply an explicit single-bid/reserve policy rather than treating −1 as a monetary price.
Using the auction roles
The auctioneer has a
participant(name)belief for each agent that should be invited, and adopts!auction(id, description, configure(timeout)). It can override+!compare_bids(...)to change how bids are compared; by default, the highest bid wins.Each participant adopts
!monitor_for_auctions()and overrides+!generate_bid(string id, funct description, int bid)to set its bid. It can also override+!successful_bid(...)and+!failed_bid(...).
package demo;
agent Auctioneer extends astra.protocol.FirstPriceAuction {
initial participant("alice"), participant("bob");
plan +!main(list args) {
system.createAgent("alice", "demo.Bidder");
system.createAgent("bob", "demo.Bidder");
system.sleep(200);
!auction("lot1", painting("sunflowers"), configure(500));
system.sleep(200);
system.exit();
}
}
package demo;
agent Bidder extends astra.protocol.FirstPriceAuction {
initial !monitor_for_auctions();
plan +!generate_bid(string id, funct description, int bid) {
if (system.name() == "alice") bid = 30;
else bid = 25;
}
}
[main] Starting Auction of: lot1
[main] Waiting for bids
[main] received bid: 25 from: bob
[main] received bid: 30 from: alice
[main] Evaluating bids
[main] winner of: lot1 is: alice with bid: 30
[alice] I AM WINNER of: lot1 with bid: 30
The order in which the bids arrive may vary. The protocols can be tested using the unit testing library; the astra-protocols project includes a test for the FIPA Request protocol.
Concession protocols (2.8.10)
Download the complete example project, extract it, and run mvn test followed by mvn compile astra:run from its directory. It needs no model API key or external messaging service.
These protocols negotiate a single complete agreement. The coordinator manages rounds and messages; participants supply domain-specific offers and utilities. They use FIPA performative names for custom interaction protocols, rather than implementing a standardised FIPA MCP protocol.
Roles and application hooks
Each package (astra.protocol.mcp and astra.protocol.mucp) provides separate
Coordinator and Participant agents. Extend just the role you need, or extend
MonotonicConcessionProtocol / MultilateralConcessionProtocol to inherit both.
Both roles inherit the package’s shared Messages ontology: do not redeclare its
wire formulas when composing roles, because ASTRA rejects duplicate declarations.
The coordinator goals are overloaded by their argument types, so a coordinator
can inherit both packages as the runnable example below does.
Start exactly one initial !monitor_mcp(); or initial !monitor_mucp(); on each
participant. A combined role can coordinate and monitor independently. Incoming
protocol messages are handled inside encapsulated goals; inheriting a participant
without starting its monitor does not make it ready.
Override these plans (replace mcp_ with mucp_ for multilateral participants):
plan +!mcp_proposal(string id, funct issue, int round, funct previous,
funct offer, boolean available) {
offer = price(50);
available = true;
}
plan +!mcp_utility(string id, funct issue, price(int price), double value) {
value = 100.0 - price;
}
plan +!mcp_finished(string coordinator, string id, funct result) {
// Participant notification; delivery is best effort.
}
offer, available and value are output parameters: assign them in the hook
so bindings return to the calling monitor. Do not shadow them with new local
variables. Round zero receives previous = none(); later proposal calls receive
that participant’s own previous offer. The default proposal hook sets
available = false, and the default utility hook fails closed. Override both
strategy hooks for your issue and offer shapes. A failed proposal/utility hook is
recovered by the monitor, leaving the coordinator to report a phase timeout.
Returning available = false also means no offer is sent, not an immediate refusal.
Utilities must be finite (no NaN or infinity), comparable and stable throughout
a session. Re-evaluating the same offer must produce the same value; avoid random
scores, changing market inputs or mutable balances during negotiation. The
protocol trusts the reported comparisons and does not enforce these properties.
The previous argument lets strategies implement concessions; the coordinator
does not generate concessions for them.
Bilateral MCP: a buyer and seller
A coordinator starts a negotiation with:
!start_negotiation("price-1", "mcp-buyer", "mcp-seller",
trade("concede"), 8, 2000);
The two names must differ; round count and timeout must be positive. Rounds are numbered from zero, so eight rounds means rounds 0 through 7. The timeout is in milliseconds per phase, not a deadline for the entire negotiation.
These complete participant agents are included in the runnable concession guide:
package guide;
agent MCPBuyer extends astra.protocol.mcp.Participant {
initial !monitor_mcp();
plan +!mcp_proposal(string id, trade(string mode), int round, funct previous, funct offer, boolean available) {
int price = 10;
if (mode == "concede") { price = 10 + round * 10; }
offer = price(price);
available = true;
}
plan +!mcp_utility(string id, funct issue, price(int price), double value) {
value = 100.0 - price;
}
}
package guide;
agent MCPSeller extends astra.protocol.mcp.Participant {
initial !monitor_mcp();
plan +!mcp_proposal(string id, trade(string mode), int round, funct previous, funct offer, boolean available) {
int price = 90;
if (mode == "concede") { price = 90 - round * 10; }
if (mode == "regress") { price = 90 + round; }
offer = price(price);
available = true;
}
plan +!mcp_utility(string id, trade(string mode), price(int price), double value) {
if (mode == "silent") { system.fail(); }
value = price * 1.0;
}
}
The buyer offers 10, 20, 30, 40, 50 and values a price as 100 - price;
the seller offers 90, 80, 70, 60, 50 and values it as price. Agreement is
agreement(price(50)) at round 4. Modes other than "concede" in these agents
are fixtures for the runnable tests (hold, regress and silent assessment).
In each round the coordinator collects both offers before revealing them for
assessment. Each participant accepts the opponent’s offer when its utility is
at least that of its own offer. From round 1, the opponent’s offer must be at
least as good as its previous offer; strictly greater utility counts as progress.
Any invalid concession takes precedence over acceptance. If the first participant
accepts, the second participant’s offer wins; otherwise, if the second accepts,
the first participant’s offer wins. If both accept, the second participant’s
offer wins deterministically, irrespective of reply arrival order.
If neither accepts and neither reports strict progress after round zero, the
result is conflict(no_concession()).
Multilateral concession: divide 90 units
A coordinator supplies an ordered, fixed membership list:
!start_negotiation("allocation-1", ["mucp-a", "mucp-b", "mucp-c"],
allocation("concede"), 5, 2000);
Membership must contain at least two distinct, nonempty strings; non-string
entries are invalid. Bounds must be positive. Every proposal must describe a
complete candidate agreement, not just the proposing member’s share. Here
shares(a,b,c) divides 90 units, and each agent’s utility is its own share.
The following complete strategy handles the agreement case; the downloadable
MUCPAllocator.astra
also includes tie, majority, timeout and other test modes.
package guide;
agent MUCPAllocator extends astra.protocol.mucp.Participant {
initial !monitor_mucp();
plan +!mucp_proposal(string id, allocation(string mode), int round,
funct previous, funct offer, boolean available) {
int mine = 60 - round * 20;
int other = 15 + round * 10;
if (round > 1) { mine = 30; other = 30; }
if (system.name() == "mucp-a") { offer = shares(mine, other, other); }
if (system.name() == "mucp-b") { offer = shares(other, mine, other); }
if (system.name() == "mucp-c") { offer = shares(other, other, mine); }
available = true;
}
plan +!mucp_utility(string id, allocation(string mode),
shares(int a, int b, int c), double value) {
if (system.name() == "mucp-a") { value = a * 1.0; }
if (system.name() == "mucp-b") { value = b * 1.0; }
if (system.name() == "mucp-c") { value = c * 1.0; }
}
}
At round zero the offers are (60,15,15), (15,60,15), (15,15,60).
At round one they are permutations of (40,25,25); at round two every
participant offers (30,30,30), producing agreement(shares(30,30,30)).
Each concession improves the other members’ shares.
All offers arrive before assessment begins. Every evaluator assesses every
proposer’s candidate, including its own: acceptance requires utility at least
that of the evaluator’s own current offer. All n² assessments must arrive.
From round 1, each other member must value a proposer’s offer at least as highly
as that proposer’s previous offer; self-assessment does not count as concession
progress. Any invalid other-party concession takes precedence over agreement.
Otherwise the first unanimously acceptable proposal in membership-list order
wins. This order, not message arrival, breaks ties. If no proposal is unanimous
and no other-party assessment reports strict improvement after round zero,
the result is conflict(no_concession()).
A majority is insufficient. The runnable "majority" fixture makes A and B value
a + b, while C values c: A and B accept one another’s offers, but C rejects
them and A/B reject C’s. With unchanged offers, round 1 ends in no_concession().
The "tie" fixture assigns every offer utility 1.0; membership order
["mucp-c", "mucp-a", "mucp-b"] therefore selects C’s initial
shares(15,15,60) in round zero.
The monotonicity rule is strong: a proposal must make no other member worse off than its previous proposal. Improvements for some members cannot offset a loss for another. Some otherwise useful trade-offs can therefore stall.
Run both protocols
The example’s complete coordinator is:
package guide;
agent Main extends astra.protocol.mcp.Coordinator, astra.protocol.mucp.Coordinator {
module Console console;
plan +!main(list args) {
system.createAgent("mcp-buyer", "guide.MCPBuyer");
system.createAgent("mcp-seller", "guide.MCPSeller");
system.createAgent("mucp-a", "guide.MUCPAllocator");
system.createAgent("mucp-b", "guide.MUCPAllocator");
system.createAgent("mucp-c", "guide.MUCPAllocator");
// Local demonstration warm-up, not a readiness handshake.
system.sleep(200);
!start_negotiation("price-1", "mcp-buyer", "mcp-seller", trade("concede"), 8, 2000);
!start_negotiation("allocation-1", ["mucp-a", "mucp-b", "mucp-c"], allocation("concede"), 5, 2000);
!start_negotiation("tie-1", ["mucp-c", "mucp-a", "mucp-b"], allocation("tie"), 5, 2000);
!start_negotiation("majority-1", ["mucp-a", "mucp-b", "mucp-c"], allocation("majority"), 5, 2000);
system.terminateAgent("mcp-buyer");
system.terminateAgent("mcp-seller");
system.terminateAgent("mucp-a");
system.terminateAgent("mucp-b");
system.terminateAgent("mucp-c");
system.exit();
}
plan +!mcp_completed(string id, funct result) {
console.println(id + ": " + result);
}
plan +!mucp_completed(string id, funct result) {
console.println(id + ": " + result);
}
}
From docs/code/concession-guide/, run:
mvn clean compile astra:run
mvn test
Use mvn -o when all required artifacts and Maven plugins are already cached.
The POM pins the ASTRA parent, protocols and test library to 2.8.12. Agent class
names passed to createAgent include guide.; runtime participant names remain
mcp-buyer, mucp-a, etc. When adapting default-package tests, update both class
strings and any hard-coded coordinator recipient (the noise fixture uses
guide.MUCPTests). The expected coordinator results are:
price-1: agreement(price(50))
allocation-1: agreement(shares(30,30,30))
tie-1: agreement(shares(15,15,60))
majority-1: conflict(no_concession())
Console prefixes and diagnostic message traces may also appear.
Sessions, readiness, results and failure handling
Choose a fresh session ID for every call on a coordinator, including concurrent
calls; duplicate IDs are a caller error, not a checked admission mechanism.
Use one monitor per participant. Ensure all participant monitors are running
before inviting them. The local example uses a 200 ms warm-up for convenience;
this is not a readiness guarantee. Deployed systems should establish application
readiness before calling start_negotiation, rather than relying on sleeps.
Coordinators accept only the first expected response matching the current
session, member, round and phase. Multilateral votes also match the expected
evaluator/proposer pair. Duplicate, stale and unexpected responses do not fill
pending slots. Bounded wait(condition, timeout) permits message handling while
waiting. Delivery failures are recovered; missing responses become timeouts.
Round state is cleaned between rounds; multilateral membership and previous-offer
state are also removed before its completion hook.
Override mcp_completed(string id, funct result) or
mucp_completed(string id, funct result) on the coordinator to record local
results. The goal returns after invoking that hook. Participants receive
mcp_finished(coordinator, id, result) / mucp_finished(...) from best-effort
notifications; the coordinator completing does not guarantee these hooks have
run. Invalid configurations invoke the local completion hook without invitations.
Both protocols return agreement(offer) or conflict(reason):
Reason |
Meaning |
|---|---|
|
Invalid bounds or membership (bilateral checks distinct names; multilateral also validates names and list size/type). |
|
At least one expected offer did not arrive in the proposal phase. |
|
At least one expected assessment did not arrive in the assessment phase. |
|
At least one other-party concession reduced reported utility. |
|
After round zero, no agreement and no strict other-party improvement. |
|
The maximum number of rounds was exhausted without an earlier result. |
Wire messages and trust limits
Performative |
Bilateral content |
Multilateral content |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Use trusted agents. The coordinator cannot verify private utilities or truthful votes. Participant monitors do not authenticate coordinators, correlate unsolicited assessments/results with invitations, persist sessions or negotiate admission. Session and phase filtering at the coordinator is not authentication. These protocols do not implement cancellation, transport retries or reliable result acknowledgement. Multilateral negotiation also excludes dynamic membership, coalitions and partial agreements, and requires O(n²) assessment messages per round. Validate domain constraints (such as total shares and allowed prices) in your application; the protocol treats offers as opaque terms.