Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Agent State

Agent fields are private state. They’re initialized when the agent is summoned and can be accessed throughout the agent’s lifetime.

Declaring Fields

Agent state uses record-style field declarations:

agent Person {
    name: String
    age: Int
}

Fields must have explicit type annotations.

Initializing Fields

When summoning an agent, provide values for all fields:

let p = summon Person { name: "Alice", age: 30 };

Missing fields cause a compile error:

// Error: missing field `age` in summon
let p = summon Person { name: "Alice" };

Accessing Fields

Use self.fieldName inside the agent:

agent Greeter {
    name: String

    on start {
        print("Hello, " ++ self.name ++ "!");
        yield(0);
    }
}

Fields Are Immutable

Fields cannot be reassigned after initialization:

agent Counter {
    count: Int

    on start {
        // This won't work — fields are immutable
        // self.count = self.count + 1;

        // Use a local variable instead
        let count = self.count;
        count = count + 1;
        yield(count);
    }
}

Entry Agent Fields

The entry agent (the one in run) cannot have required fields:

// Error: entry agent cannot have required fields
agent Main {
    config: String

    on start {
        yield(0);
    }
}

run Main;  // How would we provide `config`?

Design Pattern: Configuration

Use fields to configure agent behavior:

agent Fetcher {
    url: String
    timeout: Int

    on start {
        // Use self.url and self.timeout
        yield("done");
    }
}

agent Main {
    on start {
        let f1 = summon Fetcher {
            url: "https://api.example.com/a",
            timeout: 5000
        };
        let f2 = summon Fetcher {
            url: "https://api.example.com/b",
            timeout: 3000
        };

        let r1 = try await f1;
        let r2 = try await f2;
        yield(0);
    }

    on error(e) {
        yield(1);
    }
}

run Main;