Agent / Tools from a state machine's transitions

Send a different Message, or limit who may call

Pass an object instead of a description when the Message your app handles has a different shape from the transition's input, or when only some callers may use the tool. Here a Paid Message also records where the payment came from, and only a teller allowed to pay may call it; your update would apply Withdraw for Paid as it does above. The second type given to Agent.forModel is the caller's type, which your host reports as its principal (the package page shows how):

This block continues the file above and reuses Account, Usd, Model, AccountMachine, defineMessageUnion, Schema, Agent and machineTools:

ts
interface Teller {
  readonly canPay: boolean
}
const PayMessage = defineMessageUnion({ Paid: { amount: Usd, source: Schema.Literal('Agent') } })
const TellerAgent = Agent.forModel<Model, Teller>()
const TellerTools = machineTools({
  agent: TellerAgent,
  machine: AccountMachine,
  state: model => model.account,
})

const TellerContract = TellerAgent.make({
  messages: TellerAgent.expose(PayMessage, {
    Paid: TellerTools.Withdraw({
      name: 'pay',
      description: 'Pay out of the account',
      toMessage: ({ amount }) => ({ amount, source: 'Agent' as const }),
      authorize: ({ principal }) => principal.canPay,
    }),
  }),
})
  • name replaces the default tool name.
  • toMessage makes the Message's fields from the decoded input. Without it, the input is sent as the Message's fields unchanged.
  • authorize receives that caller as principal, typed as Teller, and runs before the guard. With it the tool is never hidden: hiding pay while the account is frozen would show the account's state to callers who may not pay.

Next