### Application Output Example
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/communication.md
Example output from running the ASTRA application, showing agent creation and replication steps up to the limit.
```Text
loading class: Replicator
[agt_0]Created agent with: 1
[agt_1]Created agent with: 2
[agt_2]Created agent with: 3
[agt_3]Created agent with: 4
[agt_4]Created agent with: 5
[agt_4]Limit reached - replication stopped
```
--------------------------------
### Authentication Agent Example
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/interaction.md
An example agent that sends authentication requests and handles responses.
```Agent
agent AuthenticationTest {
module Console C;
initial !init();
rule +!init() {
send(request, "authenticator", validate("rem", "password"));
}
rule @message(refuse, string X, validate(string U)) {
C.println(X + " has refused to validate: " + U);
}
rule @message(agree, string X, validate(string U)) {
C.println(X + " has agreed to validate: " + U);
}
}
```
--------------------------------
### Example Agent Using Debug Module
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/libraries.md
A simple agent demonstrating the use of dumpBeliefs() and dumpBeliefsWithPredicate() from the Debug module.
```astra
agent Example {
types eg {
formula likes(string);
formula has(string);
}
initial likes("icecream"), likes("sausages"), likes("beer");
initial has("icecream"), has("pickles");
module Debug debug;
rule +!main(list args) {
debug.dumpBeliefs();
debug.dumpBeliefsWithPredicate("has");
}
}
```
--------------------------------
### Calculator Output Example
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/modules/calculator.md
Illustrates the output from the Calculator module, showing stored values and memory change notifications.
```text
[main]Memory changed: 4.902209156543167
[main]stored value:
4.90
```
--------------------------------
### Example Agent with Console I/O
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/libraries.md
A simple ASTRA agent demonstrating console input and output. It prompts the user for their name and then prints a greeting.
```astra
agent Example {
module Console console;
rule +!main(list args) {
console.println("Please enter your name: ");
console.read(string name);
console.println("Hello, " + name);
}
}
```
--------------------------------
### Example Build Output
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/modules/terms.md
Sample output from running the Maven build command, showing console messages related to switch state changes and the final 'FINISHED' message.
```Log
[main]switch=on
[main]switch=off
[main]switch=on
[main]switch=off
[main]switch=on
[main]switch=off
[main]FINISHED
```
--------------------------------
### Deploy Docker Image with ASTRA Agent
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/docker/index.md
Example of an ASTRA agent that extends the Docker class to deploy a specific Docker image. It defines an image constant, an initial image belief, and a rule to start a container.
```astra
agent MyAgent extends astra.Docker {
constant string TIC_TAC_TOE = "registry.gitlab.com/mams-ucd/examples/semantic-environments/tic-tac-toe" ;
initial image(TIC_TAC_TOE);
initial binding(TIC_TAC_TOE, "8083:8083");
rule +!main(list args) {
!container(TIC_TAC_TOE, string id);
}
}
```
--------------------------------
### Agent Using ObjectAccess Module
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/libraries.md
An agent demonstrating how to create, set, and get values from Java objects using the ObjectAccess module.
```astra
agent Messager {
module ObjectAccess oa;
module Console C;
module Creator creator;
rule +!main(list args) {
Message m = creator.create();
oa.set(m, "text", "Hello World!");
C.println("m=" + m);
oa.set(m, "text", "Farewell");
C.println("m=" + m);
string text = oa.getString(m, "text");
C.println("the text=" + text);
}
}
```
--------------------------------
### Process list of activities
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/lists.md
A larger example demonstrating how to process a list of functional terms representing activities. It uses recursion to process each activity in the list.
```astra
agent Main {
module System system;
module Console console;
rule +!main(list args) {
!processActivities([move("forward"), turn("right"), dust()]);
system.exit();
}
rule +!processActivities([funct H | list T]) {
!processActivity(H);
if (list_count(T) > 0) !processActivities(T);
}
rule +!processActivity(move(string dir)) {
console.println("Moving: " + dir);
}
rule +!processActivity(turn(string dir)) {
console.println("Turning: " + dir);
}
rule +!processActivity(dust()) {
console.println("Dusting!!!!");
}
rule +!processActivity(funct A) {
console.println("Unexpected Activity: " + A);
system.fail();
}
}
```
--------------------------------
### Example ASTRA Program Output
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/modules/actions.md
This is an example of the output produced when running an ASTRA program that involves switch state changes.
```text
[main]switch=off
[main]switch=on
[main]switch=off
[main]switch=on
[main]switch=off
[main]switch=on
[main]switch=off
[main]FINISHED
```
--------------------------------
### Java Class for ObjectAccess Example
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/libraries.md
A simple Java class with a public String field 'text' used in the ObjectAccess example.
```java
public class Message {
public String text;
public String toString() {
return text;
}
}
```
--------------------------------
### Launch an EIS Environment
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/eis/index.md
Use the `launch` action to start an EIS environment. This action requires a unique identifier for the environment and the relative path to its JAR file. Only one agent should launch an environment.
```astra
agent Example {
module EIS ei;
rule +!main(list args) {
ei.launch("my_id", "/path/to/MyEnvironment.jar");
}
}
```
--------------------------------
### Shuffle and Sort List Example in Astra
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/lists.md
This program demonstrates how to randomly shuffle the elements of a list and then re-sort it in ascending order using Astra's built-in modules.
```Astra
package examples;
agent ShuffleSort {
module Console console;
module System system;
module Prelude prelude;
module Math math;
rule +!main(list args) {
list l = [ "a", "b", "c", "d", "e" ];
!shuffle(l, list l2, 10);
console.println("shuffled: " + l2);
prelude.sort_asc(l2);
console.println("sorted: " + l2);
system.exit();
}
rule +!shuffle(list in, list out, int N) {
out = in;
int i=0;
while (i < N) {
int j = math.randomInt() % prelude.size(out);
int k = math.randomInt() % prelude.size(out);
prelude.swap(out, j, k);
i = i + 1;
}
}
}
```
--------------------------------
### Hello World Agent in ASTRA
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/index.md
A basic ASTRA agent program that prints 'Hello World!' to the console. This example demonstrates agent class structure, module declaration for console I/O, and the main event rule.
```ASTRA
agent Hello {
module Console console;
rule +!main(list args) {
console.println("Hello World!");
}
}
```
--------------------------------
### Foreach Loop Example in ASTRA
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/reference.md
Demonstrates the Foreach loop statement for iterating over variable bindings generated by a guard. The inner statement's execution does not affect the number of iterations.
```ASTRA
agent Eachy {
module Console console;
module System system;
types local {
formula balance(string, double);
formula rate(double);
}
initial !init();
initial rate(1.21);
initial balance("Rem", 1000.0);
initial balance("Bob", 500.0);
rule +!init() : rate(double rate) {
console.println("before loop");
foreach (balance(string name, double amt)) {
-balance(name, amt);
+balance(name, amt*rate);
console.println(name + " change from: " + amt + " to: " + (amt*rate));
}
console.println("after loop");
system.exit();
}
}
```
--------------------------------
### Rule-based loop with increasing counter (fixed iterations)
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/reference.md
An example of a loop that counts up to a fixed number. This approach is less flexible for variable loop lengths compared to the first example.
```ASTRA
agent UpLoopy {
module Console console;
initial !print(1);
rule +!print(int X) : X < 5 {
console.println(X);
!print(X-1);
}
rule +!print(int X) : X == 5 {
console.println(X);
}
}
```
--------------------------------
### AgentSpeak(L) Belief Update Example
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/astra-concepts.md
This code demonstrates adding and removing beliefs to create an infinite loop for toggling a light's state. It includes an initial belief and two rules that trigger each other.
```agentspeak
01 light(on).
02
03 +light(on) <-
04 println(the light is on, turn it off!);
05 -light(on);
06 +light(off).
07
08 +light(off) <-
09 println(the light is off, turn it on!);
10 -light(off);
11 +light(on).
```
--------------------------------
### Rule-based loop with decreasing counter
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/reference.md
This example demonstrates a loop that counts down from a given number using rule contexts and subgoals. It's useful for iterative processes where the number of iterations is not fixed beforehand.
```ASTRA
module Console console;
initial !print(5);
rule +!print(int X) : X > 1 {
console.println(X);
!print(X-1);
}
rule +!print(int X) : X == 1 {
console.println(X);
}
```
--------------------------------
### Forall Loop Example in ASTRA
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/reference.md
Illustrates the Forall loop statement for iterating through elements of a homogeneous list. The variable declared in the statement is scoped to the statement itself.
```ASTRA
agent NameDropper {
module Console C;
rule +!main(list args) {
list names = ["Ringo", "John", "George", "Paul"];
forall(string name : names) {
C.println(name);
}
}
}
```
--------------------------------
### While loop implementation in ASTRA
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/reference.md
This example shows a traditional while loop structure within an ASTRA agent, similar to imperative programming languages. It iterates and prints numbers up to a specified limit.
```ASTRA
agent Whiley {
module Console console;
initial !print(5);
rule +!print(int X) {
int i = 0;
while (i < X) {
console.println(i);
i = i + 1;
}
}
}
```
--------------------------------
### Logical Expression Operators
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/reference.md
Demonstrates the symbols and examples for logical operators (Not, And, Or, Brackets) used in ASTRA.
```astra
|----------|--------|-----------------------------------------------------------------|
| OPERATOR | SYMBOL | EXAMPLE |
|----------|--------|-----------------------------------------------------------------|
| Not | ~ | ~likes(string X, "icecream") |
| | | ~result(int X, int Y, int Z) |
|----------|--------|-----------------------------------------------------------------|
| And | & | likes(string X, "icecream") & is(X, "happy") |
|----------|--------|-----------------------------------------------------------------|
| Or | | | has(X, "icecream") | has(X, "beer") |
|----------|--------|-----------------------------------------------------------------|
| Brackets | () | hungry(string X) & (likes(X, "icecream") | likes(X, "burgers")) |
|----------|--------|-----------------------------------------------------------------|
```
--------------------------------
### Plan Rule with Disjunction
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/reference.md
An example of a plan rule using disjunction (OR operator). The agent will eat food if they like it or tolerate it.
```astra
rule +!eat(string F) : likes(F) | tolerates(F) {
body.eat(F);
}
```
--------------------------------
### Complex Conditional Logic with If-Else If
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/reference.md
This example shows a complex rule using a series of if-else if statements to handle multiple conditions for agent behavior, such as tackling, controlling a ball, or moving to a space.
```ASTRA
rule +!decide() {
if (is("ball", "near") &
has("ball", string X) & is(X, "opposition")) {
!tackle(X);
} else if (is("ball", "near") &
is("ball", "free")) {
!controlBall();
} else if (is("ball", "near") &
has("ball", string X) &
is(X, "team_member")) {
!moveToSpace();
}
}
```
--------------------------------
### Set Initial Beliefs in ASTRA
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/astra-concepts.md
The 'initial' keyword declares the agent's starting beliefs. Multiple beliefs can be declared on separate lines or combined with a comma.
```astra
initial switch("up");
initial light("off");
```
```astra
initial switch("up"), light("off");
```
--------------------------------
### Embedded while loop in an agent
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/reference.md
This snippet embeds a while loop within an agent's initialization process, similar to the EmbLoopy example. It includes console output and system termination.
```ASTRA
agent EmbWhiley {
module Console console;
module System system;
initial !init();
rule +!init() {
console.println("Started program");
!print(5);
console.println("Finished Loop");
system.exit();
}
rule +!print(int X) {
int i = 0;
while (i < X) {
console.println(i);
i = i + 1;
}
}
}
```
--------------------------------
### Conditional Rule Execution for Even Numbers
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/reference.md
A simple example showing a rule that only executes if a condition is met (X % 2 == 0). An empty rule is also provided to handle cases where the condition is not met, demonstrating a basic form of choice or conditional execution.
```astra
initial !printIfEven(5);
rule +!printIfEven(int X) : X % 2 == 0 {
console.println("X = " + X);
}
rule +!printIfEvent(int X) { }
```
--------------------------------
### AgentSpeak(L) Hello World Program
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/astra-concepts.md
A basic 'Hello World' program in AgentSpeak(L) demonstrating initial goal declaration and a plan to handle that goal. Use this for simple agent initialization and output.
```agentspeak
01 !init().
02
03 +!init() <-
04 println(hello world).
```
--------------------------------
### Custom Event Rule Example
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/modules/calculator.md
An example of an ASTRA rule that handles a custom event. Custom event rules are prefixed with a dollar sign ($).
```java
package example.calculator;
agent MyAgent {
module Calculator calc;
module Console C;
types calculator {
formula memory(double);
}
rule +!main(list args) {
calc.store(3+calc.divide(calc.add(1.2, 3.2), 2.3131));
if (calc.hasMemory()) {
C.println("stored value: ");
calc.doublePrint(calc.retrieve(),2);
} else {
C.println("There was no stored value...");
}
}
```
--------------------------------
### Combined and Simplified Rules for !light("on")
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/astra-concepts.md
Shows how to combine specific and default rules for the !light("on") goal, using rule order for selection.
```astra
rule +!light("on") : light("on") {}
rule +!light("on") {
!flipSwitch();
}
```
--------------------------------
### ASTRA 'Hello World' Agent
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/astra-concepts.md
A simple ASTRA agent that prints 'hello world' to the console, demonstrating module usage and initial rule execution.
```astra
01 agent Hello {
02 module Console console;
03
04 initial !init();
05
06 rule +!init() {
07 console.println("hello world");
08 }
09 }
```
--------------------------------
### Deploy ASTRA Project in IntelliJ
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/ides/intellij.md
Execute the deploy target in the Maven tool window to run your ASTRA program. This typically runs the Main.astra file.
```text
HelloWorld->Lifecycle->deploy
```
--------------------------------
### Parent Agent Definition
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/multiple-inheritence.md
Defines a base agent with a 'belief_predicate' formula and a default 'validate' rule. This serves as a parent for single inheritance examples.
```ASTRA
agent Parent {
module Console c;
types parent_ont {
formula belief_predicate(int);
}
rule +!validate(belief_predicate(int v)) {
c.println("Default:"+v);
}
}
```
--------------------------------
### Hello World Agent
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/examples/basic.md
A basic ASTRA agent that prints 'Hello World' to the console using an initial goal and a single rule. Requires the Console module.
```ASTRA
agent Hello {
module Console C;
initial !init();
rule +!init() {
C.println("Hello World");
}
}
```
--------------------------------
### Initial LightSwitch Agent Program
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/astra-concepts.md
Defines the basic structure of the LightSwitch agent with types, initial states, and simple rules for light manipulation.
```astra
agent LightSwitch {
types lightExample {
formula switch(string);
formula light(string);
}
initial switch("up"), light("off");
rule +!light(string X) : light(X) { }
rule +!light("on") {
-light("off");
+light("on");
}
rule +!light("off") {
-light("on");
+light("off");
}
}
```
--------------------------------
### ASTRA Agent Using Calculator Module
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/modules/calculator.md
An example ASTRA agent that utilizes the Calculator module to store a computed value and check if memory has a stored value.
```ASTRA
package example.calculator;
agent MyAgent {
module Calculator calc;
module Console C;
rule +!main(list args) {
calc.store(3+calc.divide(calc.add(1.2, 3.2), 2.3131));
if (calc.hasMemory()) {
C.println("stored value: ");
calc.doublePrint(calc.retrieve(),2);
} else {
C.println("There was no stored value...");
}
}
}
```
--------------------------------
### Maven Command to Clean, Compile, and Deploy ASTRA Application
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/deploying.md
Performs a clean build, compiles the ASTRA code, and deploys the agent program.
```bash
mvn clean compile astra:deploy
```
--------------------------------
### Maven Command to Run Default ASTRA Application
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/deploying.md
Executes the default Maven build goal, which typically compiles and deploys the ASTRA application.
```bash
mvn
```
--------------------------------
### Astra Agent with Subgoals
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/astra-concepts.md
Demonstrates an agent handling an initial goal and adopting a subgoal. The agent uses the Console module for output.
```astra
01 agent Subby {
02 module Console C;
03
04 initial !init();
05
06 rule +!init() {
07 !printHello();
08 }
09
10 rule +!printHello() {
11 C.println("hello world");
12 }
13 }
```
--------------------------------
### Bully Election Algorithm in ASTRA
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/examples/distributed.md
Implements the Bully Election algorithm for decentralized leader election. Subclass the agent and define score and participants beliefs. Invoke !bully_election() to start.
```astra
agent BullyElection {
types core {
formula score(int);
formula participants(list);
formula holding(string);
formula leader(string);
formula elect(string, int);
formula elected(string);
formula result(string);
formula failed_election(string);
}
module System system;
// this rule starts the election
rule +!bully_election() : score(int score) & participants(list agents) {
// believe that we are holding the election
+holding("election");
// drop the belief about the current leader
if (leader(string X)) -leader(X);
// send an elect message to all participants, passing the agents name and score
forall (string receiver : agents) {
if (receiver ~= system.name() | failed_election(receiver)) {
send(request, receiver, elect(system.name(), score));
}
}
// wait for the deadline (2 seconds)
system.sleep(2000);
// check if we are still holding the election
// this belief will not hold if another agent of higher importance has responded.
if (holding("election")) {
// nobody overrode it, so it is elected...
forall (string agt : agents) {
send(inform, agt, elected(system.name()));
}
}
// drop any beliefs about failed elections
foreach(failed_election(string name)) {
-failed_election(name);
}
}
// we received an elect message from another agent
rule @message(request, string sender, elect(string name, int score)) : score(int my_score) {
if (score < my_score) {
// i am more important than the sender so tell the sender
// to stop and start my own election.
+failed_election(name);
send(inform, sender, result("ok"));
if (~holding("election")) {
!!bully_election();
}
}
}
// i received an "ok" from a more important agent, so stop.
rule @message(inform, string sender, result("ok")) : holding("election") {
-holding("election");
}
// a new coordinator has been elected
rule @message(inform, string N, elected(N)) {
+leader(N);
}
}
```
--------------------------------
### Choice Implementation using Multiple Rules
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/reference.md
Illustrates how to implement choice logic by defining multiple ASTRA rules that handle the same goal event (!decide) but have different contextual conditions. The interpreter selects the appropriate rule based on the context.
```astra
rule +!decide() :
is("ball", "near") & has("ball", string X) &
is(X, "opposition") {
!tackle(X);
}
rule +!decide() :
is("ball", "near") & is("ball", "free") {
!controlBall();
}
rule +!decide() :
is("ball", "near") & has("ball", string X) &
is(X, "team_member") {
!moveToSpace();
}
```
--------------------------------
### Compile ASTRA Project in IntelliJ
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/ides/intellij.md
Use the Maven tool window in IntelliJ to compile both Java and ASTRA code for your project.
```text
HelloWorld->Lifecycle->compile
```
--------------------------------
### Registering EventUnifier and Adding Event
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/modules/events.md
Code demonstrating how to register a custom EventUnifier and add a new SwitchEvent within a Module.
```java
public class Switch extends Module {
static {
Unifier.eventFactory.put(SwitchEvent.class, new SwitchEventUnifier());
}
private boolean on = false;
@ACTION
public boolean flip() {
on = !on;
agent.addEvent(new SwitchEvent(
Primitive.newPrimitive(on ? "on":"off")
));
}
}
```
--------------------------------
### Declare Variables in Triggering Event
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/reference.md
Declare variables X and Y within the triggering event of a rule to extract information from the matched event for use in the plan. This example generates a belief containing the result of an addition.
```ASTRA
rule +!addition(int X, int Y) {
+result(X, Y, X+Y);
}
```
--------------------------------
### Launch ASTRA Environment
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/eis/index.md
This snippet shows how to launch a specific ASTRA environment using the `ei.launch` function, referencing the environment JAR file located in the dependency folder.
```astra
agent Example {
module EIS ei;
rule +!main(list args) {
ei.launch("my_id", "dependency/vacuumworld-1.2.0.jar");
}
}
```
--------------------------------
### Print to Console
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/libraries.md
Uses the 'println' action of a declared Console module instance to output a string to the console.
```astra
con.println("Hello World");
```
--------------------------------
### Create ASTRA Project with Archetype
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/modules/terms.md
Use this Maven command to generate a new ASTRA project from a predefined archetype. This sets up the basic project structure and configuration.
```bash
mvn archetype:generate \
-DarchetypeGroupId=com.astralanguage \
-DarchetypeArtifactId=astra-archetype \
-DarchetypeVersion=1.2.0 \
-DgroupId=examples \
-DartifactId=module-terms \
-Dversion=0.1.0
```
--------------------------------
### Basic ASTRA Agent Program
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/deploying.md
A simple ASTRA agent program that prints 'Hello World, ASTRA' to the console. This serves as the default entry point for ASTRA applications.
```astra
agent Main {
module Console C;
rule +!main(list args) {
C.println("Hello World, ASTRA");
}
}
```
--------------------------------
### ASTRA Rule for Goal: Turn Light On (Initial)
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/astra-concepts.md
A basic ASTRA rule to achieve the goal of turning the light on, triggered by the '!light("on")' event.
```astra
rule +!light("on") {
}
```
--------------------------------
### Print Agent Event Queue
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/libraries.md
Use printEventQueue() to display the agent's event queue.
```astra
debug.printEventQueue();
```
--------------------------------
### Main Agent for Replication
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/communication.md
This agent initiates the replication process by creating the first Replicator agent and sending it an initial message.
```Astra
agent Main {
module Console console;
module System system;
types replicate {
formula replicate(int);
}
rule +!main(list args) {
console.println("Starting Replication...");
system.createAgent("agt_0", "Replicator");
send(request, "agt_0", replicate(1));
}
}
```
--------------------------------
### Authentication Agent - Basic Validation with Query
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/interaction.md
Adds a query to check credentials after agreeing to the request, assuming query success implies validation.
```AgentSpeak
agent Authentication {
rule @message(request, string X, validate(string U, string P) {
if (trusted(X)) {
send(agree, X, validate(U));
query(credentials(U, P));
send(inform, X, validated(U));
} else {
send(refuse, X, validate(U));
}
}
}
```
--------------------------------
### Simplify Pass Action Rule with Inference
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/reference.md
Demonstrates simplifying a rule for passing a ball by using an inference rule to define the 'should pass' condition.
```astra
inference should("passTo", string P) :-
has("ball") & is("closed_down") &
near("team_player", P);
rule +!decide() : should("passTo", string P)) {
pass(P);
}
```
--------------------------------
### Alternative Rule for !light("on") Goal
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/astra-concepts.md
Replaces the direct light manipulation rule with a subgoal to flip the switch, abstracting the action.
```astra
rule +!light("on") {
!flipSwitch();
}
```
--------------------------------
### Alternative Docker Authentication Rule
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/docker/index.md
This snippet demonstrates an alternative approach to Docker authentication by creating and applying an AuthConfig directly. It bypasses the need for the credentials module.
```agent
agent Test extends Docker {
rule +?local(string name) {
AuthConfig authConfig = docker.createAuthConfig(
"MY_REPOSITORY",
"MY_USERNAME",
"MY_PASSKEY"
);
docker.auth(authConfig);
+authConfig(name, authConfig);
?local(name);
}
}
```
--------------------------------
### Agent with Switch Module (Event-based)
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/modules/terms.md
This agent program uses events to manage the state of a switch. It includes rules for flipping the switch and handling console output. Note the explicit management of switch state beliefs.
```Astra
agent Main {
module Switch switch;
module Console console;
types switch {
formula switch(string);
}
initial switch("off");
rule +!main(list args) {
!flash(3);
console.println("FINISHED");
}
rule +!flash(int N) : N > 0 {
!switch("on");
!switch("off");
!flash(N-1);
}
rule +!flash(int N) {}
rule +!switch(string state) : ~switch(state) {
switch.flip();
wait(switch(state));
}
rule +!switch(string state) {
console.println("should not happen");
}
rule $switch.state(string state) {
-+switch(state);
console.println("switch=" + state);
}
}
```
--------------------------------
### Join an Existing EIS Environment
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/eis/index.md
Use the `join` action to connect an agent to an already running EIS environment. This action takes the identifier of the environment as a parameter. Multiple agents can join an environment.
```astra
agent Example2 {
module EIS ei;
rule +!main(list args) {
ei.join("my_id");
}
}
```
--------------------------------
### Maven POM Configuration to Set Main Agent
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/deploying.md
Configures the Maven build to specify 'Namey' as the main ASTRA agent program to run.
```xml
Namey
```
--------------------------------
### ASTRA Rule for Goal: Turn Light On (Light Already On)
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/astra-concepts.md
ASTRA rule handling the scenario where the goal to turn the light on is already achieved because the light is currently on. It uses a context to check the light's state.
```astra
rule +!light("on") : light("on") {}
```
--------------------------------
### ASTRA Switch Module - Initial State Management
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/modules/events.md
This Java code defines the Switch module for ASTRA. It initializes the switch state and updates beliefs when the module is set up or the 'flip' action is performed. The 'on' variable tracks the current state of the switch.
```java
package example;
public class Switch extends Module {
private boolean on = false;
private Predicate belief;
public void setAgent(Agent agent) {
super.setAgent(agent);
updateBeliefs();
}
@ACTION
public boolean flip() {
on = !on;
updateBeliefs();
return true;
}
```
--------------------------------
### Maven Build File (pom.xml)
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/modules/terms.md
This is the standard Maven build file for an ASTRA project. It configures the project's dependencies and the ASTRA Maven plugin.
```xml
4.0.0
examples
module-terms
1.4.1
com.astralanguage
astra-base
1.4.1
clean compile astra:deploy
com.astralanguage
astra-maven-plugin
1.4.1
```
--------------------------------
### Master Agent with Timeout Integration
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/interaction.md
Demonstrates integrating a timeout mechanism into agent conversations. The timeout runs in parallel as a spawned goal.
```Agent
package examples;
agent Master {
module Console C;
module System S;
initial !init();
rule +!init() {
S.createAgent("rem", "examples.Slave");
S.sleep(5000);
!add(3, 5);
}
rule @message(inform, string sender, state(string X)) {
C.println(sender + " is alive!");
+slave(sender);
}
rule +!add(int X, int Y) : slave(string slave) {
send(request, slave, add(X, Y));
!!timeout("add", 1000); // timeout set for 1 second...
when(added(X, Y, int Z) | timeout("add")) {
-timeout("add"); // remove timeout flag just in case...
if (added(X, Y, int Z2)) {
C.println("3+5=" + Z2);
}
}
}
rule @message(inform, string sender, added(int X, int Y, int Z)) {
+added(X, Y, Z);
}
rule +!timeout(string id, int length) {
system.sleep(length);
+timeout(id);
}
}
```
--------------------------------
### Instantiate Console Module with Custom Identifier
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/libraries.md
Declares an instance of the astra.lang.Console module with the identifier 'console'. This is a common convention for readability when using a single instance.
```astra
module Console console;
```
--------------------------------
### Command Line to Set Main Agent and Agent Name
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/deploying.md
Executes the ASTRA application using Maven, specifying both the main agent program ('Namey') and the agent's name ('George').
```bash
mvn astra:deploy -Dastra.main=Namey -Dastra.name=George
```
--------------------------------
### Rules for !flipSwitch() Goal
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/astra-concepts.md
Implements the !flipSwitch() goal using two rules to handle different switch states, similar to an if-else structure.
```astra
rule +!flipSwitch() : switch("down") {
!switch("up");
}
rule +!flipSwitch() {
!switch("down");
}
```
--------------------------------
### Switch Module with Initial Belief
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/modules/actions.md
Extends the `Switch` module to set an initial belief about the switch's state when the agent is set.
```java
package example;
public class Switch extends Module {
private boolean on = false;
public void setAgent(Agent agent) {
super.setAgent(agent);
Predicate belief = new Predicate("switch", new Term[] {
Primitive.newPrimitive(on ? "on":"off")
});
agent.beliefs().addBelief(belief);
}
@ACTION
public boolean flip() {
on = !on;
return true;
}
}
```
--------------------------------
### Maven POM Configuration
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/modules/actions.md
This is the standard pom.xml file for an ASTRA project. Ensure the astra-maven-plugin version matches your ASTRA base version.
```xml
4.0.0
examples
module-actions
1.4.1
com.astralanguage
astra-base
1.4.1
clean compile astra:deploy
com.astralanguage
astra-maven-plugin
1.4.1
```
--------------------------------
### Custom Creator Module for ObjectAccess
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/libraries.md
A custom Java module that implements the create() method to instantiate Java objects for use with ObjectAccess.
```java
import astra.core.Module;
public class Creator extends Module {
@TERM
public Message create() {
return new Message();
}
}
```
--------------------------------
### Command Line to Run Specific ASTRA Agent Program
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/deploying.md
Overrides the default main agent program and specifies 'Namey' to be executed via Maven.
```bash
mvn -Dastra.main=Namey
```
--------------------------------
### Maven POM file for ASTRA project
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/multiple.md
This is the standard Maven build file (pom.xml) for an ASTRA project. It includes the ASTRA Maven plugin and sets the default goal for building and deploying ASTRA agents.
```xml
4.0.0
examples
replicator
1.4.1
com.astralanguage
astra-base
1.4.1
clean compile astra:deploy
com.astralanguage
astra-maven-plugin
```
--------------------------------
### Astra Agent with Belief Query
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/astra-concepts.md
Illustrates an agent using the belief query operator and defining custom belief types. The agent queries beliefs to control its execution flow.
```astra
01 agent Query {
02 module Console C;
03
04 types eg {
05 formula is(string, string);
06 }
07
08 initial !init();
09 initial is("rem", "happy");
10
11 rule +!init() {
12 C.println("starting");
13 query(is("rem", "happy"));
14 C.println("first hurdle passed");
15 query(is("rem", "sad"));
16 C.println("ending");
17 }
18 }
```
--------------------------------
### Rules for !switch(X) Goal
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/astra-concepts.md
Handles the !switch(X) goal, including a rule for when the switch is already in the target state and a rule to change the state using transitions.
```astra
// if the switch is already in state X, do nothing
rule +!switch(string X) : switch(X) {}
// if the switch is not is state X, change it to state X
rule +!switch(string X): switch(string Y) & switchTransition(Y, X) {
-switch(Y);
+switch(X);
}
```
--------------------------------
### Launcher Agent for Token Ring
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/examples/distributed.md
The launcher agent creates worker agents, sets up a shared timer, and initiates the token ring by sending the first tokens.
```agent
package benchmarks.tokenring;
agent Launcher {
module Timer timer;
module Console console;
module System system;
rule +!main(list args) {
int WT = 500;
int N = 500000;
console.println("enter number of tokens: ");
console.readInt(int T);
console.println("enter scheduler pool size: ");
console.readInt(int size);
// Create the token ring
int i = 1;
while (i <= WT) {
system.createAgent(""+i, "benchmarks.tokenring.Worker");
send(inform, ""+i, init((i%WT)+1));
i = i + 1;
}
// Start the timer (configuring it for T tokens)
timer.startup(T);
// Send out the initial tokens
i = 1;
while (i <= T) {
send(inform, "" + (i * (WT/T)), token(i, N+1));
i = i + 1;
}
}
}
```
--------------------------------
### Switch Module Implementation
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/modules/terms.md
This Java code defines a custom ASTRA module for a light switch. It includes an action to flip the switch and an event to signal the switch's state change.
```java
public class Switch extends Module {
static {
Unifier.eventFactory.put(SwitchEvent.class, new SwitchEventUnifier());
}
private boolean on = false;
@ACTION
public boolean flip() {
on = !on;
agent.addEvent(new SwitchEvent(
Primitive.newPrimitive(on ? "on":"off")
));
return true;
}
@EVENT( symbols={}, types = {"string"}, signature = "$swe")
public Event event(Term state) {
return new SwitchEvent(state);
}
}
```
--------------------------------
### Agent Using the Switch Module
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/modules/sensors.md
This ASTRA agent code demonstrates how to use the Switch module. It defines rules for flashing the switch and handling switch state changes, interacting with the switch module's flip action.
```astra
agent Main {
module Switch switch;
module Console console;
types switch {
formula switch(string);
}
rule +!main(list args) {
!flash(3);
console.println("FINISHED");
}
rule +!flash(int N) : N > 0 {
!switch("on");
!switch("off");
!flash(N-1);
}
rule +!flash(int N) {}
rule +!switch(string state) : ~switch(state) {
switch.flip();
wait(switch(state));
}
rule +!switch(string state) {
console.println("should not happen");
}
rule +switch(string state) {
console.println("switch=" + state);
}
}
```
--------------------------------
### AgentSpeak(L) Declaring and Handling Subgoals
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/astra-concepts.md
Illustrates the use of subgoals in AgentSpeak(L) by moving the print action into a separate rule. This pattern is useful for modularizing agent behavior.
```agentspeak
01 !init().
02
03 +!init() <-
04 !printHello().
05
06 +!printHello() <-
07 println(hello world).
```
--------------------------------
### Maven Build File (pom.xml)
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/modules/sensors.md
This is the Maven build file for an ASTRA project. It configures the project's dependencies and build process, including the astra-maven-plugin.
```xml
4.0.0
examples
module-sensors
1.4.1
com.astralanguage
astra-base
1.4.1
clean compile astra:deploy
com.astralanguage
astra-maven-plugin
1.4.1
```
--------------------------------
### Pickup Block Rule with 'empty gripper' Inference
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/reference.md
Further simplifies the pickup rule by introducing an inference rule 'empty("gripper")' to check if the gripper is available.
```astra
inference empty("gripper") :- ~holding(string Y);
rule +!holding(string X) : empty("gripper") & free(X) {
pickup(X);
}
```
--------------------------------
### Create ASTRA Project using Maven Archetype
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/deploying.md
Generates a new ASTRA project structure and pom.xml using the ASTRA Maven archetype. Customize groupId, artifactId, and version as needed.
```bash
mvn archetype:generate \
-DarchetypeGroupId=com.astralanguage \
-DarchetypeArtifactId=astra-archetype \
-DarchetypeVersion=1.0.0 \
-DgroupId=examples \
-DartifactId=hello \
-Dversion=0.1.0
```
--------------------------------
### Instantiate Console Module
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/libraries.md
Declares an instance of the astra.lang.Console module with the identifier 'con'. This allows for console input and output operations.
```astra
module Console con;
```
--------------------------------
### Basic Flip Action for a Switch Module
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/modules/actions.md
Defines a simple `flip()` action for a `Switch` module that toggles its internal `on` state.
```java
package example;
public class Switch extends Module {
private boolean on = false;
@ACTION
public boolean flip() {
on = !on;
return true;
}
}
```
--------------------------------
### Compilation Command
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/modules/sensors.md
This command is used to compile and run the ASTRA program using Maven.
```bash
$ mvn
```
--------------------------------
### Configure Main Agent for ASTRA Deployment
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/deploying.md
Sets the main agent program to be deployed by the `astra:deploy` Maven goal. This overrides the default 'Main' agent. The `astra.name` property can also be set to specify the agent's name.
```xml
soccer.Manager
```
--------------------------------
### Embedded rule-based loop in an agent
Source: https://gitlab.com/astra-language/astra-docs/-/blob/master/docs/reference.md
Demonstrates how to embed a rule-based loop within a larger agent structure. The loop is initiated via a subgoal and the main plan waits for its completion. Includes system exit functionality.
```ASTRA
agent EmbLoopy {
module Console console;
module System system;
initial !init();
rule +!init() {
console.println("Started program");
!print(1, 5);
console.println("Finished Loop");
system.exit();
}
rule +!print(int X, int N) : X < N {
console.println(X);
!print(X-1);
}
rule +!print(int X, int N) : X == N {
console.println(X);
}
}
```