Agent / Tools from a state machine's transitions
Turn each transition into a tool
Your app keeps the account in its Model and has one Message per transition. Its update applies the transition through the machine, so the rule that runs is the one the tools were made from:
import { defineMessageUnion } from 'foldkit/message'
const Model = Schema.Struct({ account: Account })
type Model = typeof Model.Type
const Message = defineMessageUnion({ Withdraw: { amount: Usd }, Freeze: {} })
type Message = typeof Message.Type
const update = (model: Model, message: Message): Model => {
const [account] = Message.match(message, {
Withdraw: input => AccountMachine.update(model.account, { _tag: 'Withdraw', input }),
Freeze: () => AccountMachine.update(model.account, { _tag: 'Freeze', input: {} }),
})
return account === model.account ? model : { account }
}AccountMachine.update(state, { _tag, input }) returns a pair: the next state, then the list of records the transition emits (empty here). When the guard refuses, the state is the one you gave it, so update returns the Model unchanged. defineMessageUnion declares the Messages, and Message.match picks the arm for the Message's tag.
machineTools takes your agent builder (Agent.forModel<Model>(), which fixes your Model's type for every callback), the machine, and a function that reads the machine's state out of your Model. It returns one function per transition, named as the machine names them. Call one with a description and put the result under the Message it sends:
import { Agent } from 'foldkit-agent'
import { machineTools } from 'foldkit-agent/metakit'
const BankAgent = Agent.forModel<Model>()
const Tools = machineTools({
agent: BankAgent,
machine: AccountMachine,
state: model => model.account,
})
const BankContract = BankAgent.make({
messages: BankAgent.expose(Message, {
Withdraw: Tools.Withdraw('Withdraw money from the account'),
Freeze: Tools.Freeze('Freeze the account'),
}),
})The contract now has two tools, withdraw and freeze. Their names are the transition keys in snake_case; a misspelled key such as Tools.Withdrw does not compile. A tool placed under a Message whose fields differ from the transition's input does not compile either, unless you say how to make that Message (below).
An agent's call is decoded with no services, so every transition's input Schema must need none. If one decodes through a service (a transformation that yields one), machineTools does not compile, and the error ends with that service "is not assignable to type 'never'". A transition you typed by hand without the fifth type argument does not say what its input needs and is refused the same way.