Agent / Tools from a state machine's transitions
Write the rules as a metakit machine
metakit writes a rule as an expression your code can inspect, rather than a function it can only run. A transition is one step from one state to the next. It has an input Effect Schema, a guard (when) that says when the step is allowed, and the writes it makes. A machine groups the transitions over one state. Below, Money.make('USD') is a Schema for an integer number of cents that remembers its currency, and Expr.refine adds a rule (here, "greater than 0") that both decoding and metakit can read. Eq and Num are metakit's equality and number operations, and Transition.set is a write:
ts
import { Schema } from 'effect'
import { Eq, Expr, Num, Transition } from '@doeixd/metakit'
import { Money } from '@doeixd/metakit/domain'
import * as Machine from '@doeixd/metakit/machine'
const Usd = Money.make('USD')
const Account = Schema.Struct({ balance: Usd, status: Schema.Literals(['open', 'frozen']) })
const AccountMachine = Machine.make({
state: Account,
transitions: {
Withdraw: Transition.make({
state: Account,
input: Schema.Struct({ amount: Usd.pipe(Expr.refine($ => Num.gt($, 0))) }),
when: ({ state, input }) =>
Expr.all(Eq.is(state.status, 'open'), Num.lte(input.amount, state.balance)),
apply: ({ state, input }) => [
Transition.set(state.balance, Money.sub(state.balance, input.amount)),
],
}),
Freeze: Transition.make({
state: Account,
input: Schema.Struct({}),
when: ({ state }) => Eq.is(state.status, 'open'),
apply: ({ state }) => [Transition.set(state.status, 'frozen')],
}),
},
})