ExAgent. Session. TurnPolicy behaviour
(ExAgent v3.0.0)
View Source
Decides the order in which session participants take turns.
Stability — Stable.
A turn policy is a small, stateful module that sequences participants. The
ExAgent.Session owns no scheduling logic of its own — it delegates "who acts
next" and "may this participant act now" to the policy, so the same Session can
drive a round-robin chat, an initiative-ordered combat, or a supervisor that
alternates with workers.
Policy state is a struct whose module implements this behaviour; arbitrary map
or tuple states are not dispatched. Handoff uses an explicit callback, or keeps
state unchanged when the destination is already admitted by can_act?/3.
Custom persistence requires the opt-in versioned data codec callbacks; stored
bytes never select a module to load or execute.
init/1 receives the initial participants in the order supplied by the host.
Later callbacks receive the current roster in context.participants. Its
enumeration order is unspecified. Keep any scheduling order and cursor in
the policy state.
Session can call can_act?/3 to admit the current actor and again to validate
the next actor before saving the turn. Treat it as a repeatable query. Advance
the cursor in the state returned by next_participant/2.
Callbacks
init/1— build the policy state from options.optscarries`:participants` (the initial list) plus any policy-specific keys (e.g. `:order` for initiative).next_participant/2— return{:ok, id, new_state}for the next actor,or `{:done, new_state}` when the sequence is exhausted. `context` carries `%{shared_state: _, participants: _}` for policies that need it.can_act?/3— whetherparticipant_idmay act right now (thepolicy tracks the current actor).participant_joined/2/participant_left/2— keep the policy's roster insync as participants come and go.
Built-in implementations
ExAgent.Session.TurnPolicy.RoundRobin— insertion order, cycling forever.ExAgent.Session.TurnPolicy.Initiative— an explicit:order, cycling forever.ExAgent.Session.TurnPolicy.SupervisorPolicy— a supervisor alternates with workers.
Summary
Callbacks
Override the current actor without advancing the scheduling cursor.
Opt-in JSON data codec for persisted custom policies.
Types
@type context() :: %{ shared_state: term(), participants: [ExAgent.Session.Participant.t()] }
@type id() :: term()
@type state() :: struct()
Callbacks
Override the current actor without advancing the scheduling cursor.
@callback participant_joined(state(), ExAgent.Session.Participant.t()) :: state()
@callback restore_snapshot(pos_integer(), term(), context()) :: {:ok, state()} | {:error, term()}
@callback snapshot(state()) :: {:ok, pos_integer(), term()} | {:error, term()}
Opt-in JSON data codec for persisted custom policies.