Skip to content
Kavachकवच

Agents: Declaring an agent

● Intermediate2 min

agent Name { … } declares an agent: its model, its can, its limits and approvals, and its on handlers.

type EmailError = NotSent | Denied(reason: String)

capability Email {
    fn send(to: String) ! EmailError
}

type Outbox: Email {
    fn send(self, to: String) ! EmailError {
        print("sent to {to}")
    }
}

agent Greeter {
    can Email.send

    limit Email.send {
        count <= 2 per day
    }

    on welcome(to: String) ! EmailError {
        try Email.send(to)
    }
}

fn main() {
    const bot = Greeter.start(Email: Outbox())
    bot.welcome("asha@example.com") catch e => print("refused: {e}")
    bot.welcome("omar@example.com") catch e => print("refused: {e}")
    bot.welcome("zoe@example.com") catch e => print("refused: {e}")
}

The program ran and printed:

kavach run greeter.kav

sent to asha@example.comsent to omar@example.comrefused: Denied(reason: "limit broken: count <= 2 per day")
greeter.kav: Kavach code, then what running it prints

The agent uses a capability, here Email, and gets an implementation of it when it starts (see Running an Agent).

Like any declaration, an agent is private to its module. Write pub agent and other modules can start it and call its handlers: bots.Picker.start(). See Modules › pub. tested