use serde::{Deserialize, Serialize};
use tilo_app_id::AppId;
use crate::person::PersonId;
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MemberId {
Person(PersonId),
Agent {
id: String,
person: PersonId,
},
Bot(String),
}
pub const DIRECT_CONVERSATION_PREFIX: &str = "direct:";
impl MemberId {
#[must_use]
pub fn mark_value(&self) -> String {
serde_json::to_string(self).unwrap_or_default()
}
#[must_use]
pub fn of_mark_value(value: &str) -> Option<Self> {
value
.starts_with('{')
.then(|| serde_json::from_str(value).ok())
.flatten()
}
#[must_use]
pub fn direct_conversation(members: impl IntoIterator<Item = Self>) -> String {
let mut members: Vec<Self> = members.into_iter().collect();
members.sort();
members.dedup();
let members = serde_json::to_string(&members).unwrap_or_default();
format!("{DIRECT_CONVERSATION_PREFIX}{members}")
}
#[track_caller]
#[must_use]
pub fn person(id: impl Into<PersonId>) -> Self {
Self::Person(id.into())
}
#[must_use]
pub fn parsed_person(id: &str) -> Option<Self> {
PersonId::parse(id).ok().map(Self::Person)
}
#[track_caller]
#[must_use]
pub fn agent(id: impl Into<String>, person: impl Into<PersonId>) -> Self {
Self::Agent {
id: id.into(),
person: person.into(),
}
}
#[must_use]
pub fn bot(id: impl Into<String>) -> Self {
Self::Bot(id.into())
}
#[must_use]
pub fn id(&self) -> &str {
match self {
Self::Person(id) => id.as_str(),
Self::Agent { id, .. } | Self::Bot(id) => id,
}
}
#[must_use]
pub fn agent_id(&self) -> Option<&str> {
match self {
Self::Agent { id, .. } => Some(id),
Self::Person(_) | Self::Bot(_) => None,
}
}
#[must_use]
pub fn agent_person(&self) -> Option<&PersonId> {
match self {
Self::Agent { person, .. } => Some(person),
Self::Person(_) | Self::Bot(_) => None,
}
}
#[must_use]
pub fn as_agent(&self) -> Option<(&str, &PersonId)> {
match self {
Self::Agent { id, person } => Some((id, person)),
Self::Person(_) | Self::Bot(_) => None,
}
}
#[must_use]
pub fn bot_id(&self) -> Option<&str> {
match self {
Self::Bot(id) => Some(id),
Self::Person(_) | Self::Agent { .. } => None,
}
}
#[must_use]
pub fn as_person(&self) -> Option<&PersonId> {
match self {
Self::Person(id) => Some(id),
Self::Agent { .. } | Self::Bot(_) => None,
}
}
#[must_use]
pub fn person_id(&self) -> Option<&str> {
self.as_person().map(PersonId::as_str)
}
#[must_use]
pub const fn is_person(&self) -> bool {
matches!(self, Self::Person(_))
}
#[must_use]
pub const fn is_agent(&self) -> bool {
matches!(self, Self::Agent { .. })
}
#[must_use]
pub const fn is_bot(&self) -> bool {
matches!(self, Self::Bot(_))
}
#[must_use]
pub fn actor_bytes(&self) -> Vec<u8> {
match self {
Self::Person(id) => id.as_str().as_bytes().to_vec(),
Self::Agent { id, person } => {
[b"agent:", person.as_str().as_bytes(), b"/", id.as_bytes()].concat()
}
Self::Bot(id) => [b"bot:", id.as_bytes()].concat(),
}
}
#[must_use]
pub fn of_actor_bytes(bytes: &[u8]) -> Option<Self> {
let text = std::str::from_utf8(bytes).ok()?;
let nonempty = |id: &str| (!id.is_empty()).then(|| id.to_owned());
if let Some(agent) = text.strip_prefix("agent:") {
let (person, id) = agent.split_once('/')?;
let person = PersonId::parse(&nonempty(person)?).ok()?;
return nonempty(id).map(|id| Self::Agent { id, person });
}
if let Some(id) = text.strip_prefix("bot:") {
return nonempty(id).map(Self::Bot);
}
nonempty(text).and_then(|id| PersonId::parse(&id).ok().map(Self::Person))
}
}
impl std::fmt::Display for MemberId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Person(id) => write!(f, "person {}", short(id.as_str())),
Self::Agent { id, person } => write!(f, "agent {id} of {}", short(person.as_str())),
Self::Bot(id) => write!(f, "bot {}", short(id)),
}
}
}
fn short(id: &str) -> &str {
id.get(..12).unwrap_or(id)
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)]
#[serde(transparent)]
pub struct AutomationId(pub String);
impl AutomationId {
#[must_use]
pub fn new(id: impl Into<String>) -> Self {
Self(id.into())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct AgentSessionId(pub String);
impl AgentSessionId {
#[must_use]
pub fn new(id: impl Into<String>) -> Self {
Self(id.into())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ResourceId(pub String);
impl ResourceId {
#[must_use]
pub fn new(id: impl Into<String>) -> Self {
Self(id.into())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for ResourceId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Actor {
Member(MemberId),
Automation(AutomationId),
App(AppId),
Visitor(String),
}
impl Actor {
#[must_use]
pub fn member(member: MemberId) -> Self {
Self::Member(member)
}
#[must_use]
pub fn automation(id: impl Into<String>) -> Self {
Self::Automation(AutomationId::new(id))
}
#[must_use]
pub fn grantee(&self) -> Option<crate::Grantee> {
Some(crate::granted_to(self.member_id()?))
}
#[must_use]
pub fn member_id(&self) -> Option<&MemberId> {
match self {
Self::Member(member) => Some(member),
Self::Automation(_) | Self::App(_) | Self::Visitor(_) => None,
}
}
#[must_use]
pub fn person_id(&self) -> Option<&str> {
self.member_id().and_then(MemberId::person_id)
}
#[must_use]
pub fn agent_id(&self) -> Option<&str> {
self.member_id().and_then(MemberId::agent_id)
}
#[must_use]
pub fn app(&self) -> Option<&AppId> {
match self {
Self::App(app) => Some(app),
Self::Member(_) | Self::Automation(_) | Self::Visitor(_) => None,
}
}
#[must_use]
pub fn actor_bytes(&self) -> Vec<u8> {
match self {
Self::Member(member) => member.actor_bytes(),
Self::Automation(id) => [b"automation:", id.as_str().as_bytes()].concat(),
Self::App(app) => [b"app:", app.as_str().as_bytes()].concat(),
Self::Visitor(key) => [b"visitor:", key.as_bytes()].concat(),
}
}
#[must_use]
pub fn of_actor_bytes(bytes: &[u8]) -> Option<Self> {
let nonempty = |id: &[u8]| {
std::str::from_utf8(id)
.ok()
.filter(|id| !id.is_empty())
.map(str::to_owned)
};
if let Some(id) = bytes.strip_prefix(b"automation:") {
return nonempty(id).map(|id| Self::Automation(AutomationId(id)));
}
if let Some(app) = bytes.strip_prefix(b"app:") {
return nonempty(app).map(|app| Self::App(AppId::new(app)));
}
if let Some(key) = bytes.strip_prefix(b"visitor:") {
return nonempty(key).map(Self::Visitor);
}
MemberId::of_actor_bytes(bytes).map(Self::Member)
}
#[must_use]
pub fn id(&self) -> &str {
match self {
Self::Member(member) => member.id(),
Self::Automation(id) => id.as_str(),
Self::App(app) => app.as_str(),
Self::Visitor(key) => key,
}
}
}
impl From<Actor> for Acting {
fn from(actor: Actor) -> Self {
Self {
by: actor,
agent_session: None,
app: None,
cause: None,
foreign_device: false,
handed: false,
acted_for: Vec::new(),
}
}
}
impl From<MemberId> for Actor {
fn from(member: MemberId) -> Self {
Self::Member(member)
}
}
impl std::fmt::Display for Actor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Member(member) => member.fmt(f),
Self::Automation(id) => write!(f, "automation {}", id.as_str()),
Self::App(app) => write!(f, "app {app}"),
Self::Visitor(key) => write!(f, "visitor {}", key.get(..8).unwrap_or(key)),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Acting {
pub by: Actor,
#[serde(default)]
pub app: Option<AppId>,
#[serde(default)]
pub agent_session: Option<AgentSessionId>,
#[serde(default)]
pub cause: Option<ResourceId>,
#[serde(default)]
pub foreign_device: bool,
#[serde(default)]
pub handed: bool,
#[serde(default, rename = "for")]
pub acted_for: Vec<Acting>,
}
impl Acting {
#[must_use]
pub fn member(member: MemberId) -> Self {
Self {
by: Actor::Member(member),
agent_session: None,
app: None,
cause: None,
foreign_device: false,
handed: false,
acted_for: Vec::new(),
}
}
#[track_caller]
#[must_use]
pub fn person(id: impl Into<PersonId>) -> Self {
Self::member(MemberId::person(id))
}
#[must_use]
pub fn by_app(id: impl Into<AppId>) -> Self {
Self {
by: Actor::App(id.into()),
agent_session: None,
app: None,
cause: None,
foreign_device: false,
handed: false,
acted_for: Vec::new(),
}
}
#[track_caller]
#[must_use]
pub fn agent(id: impl Into<String>, person: impl Into<PersonId>) -> Self {
Self::member(MemberId::agent(id, person))
}
#[must_use]
pub fn visitor(key: &[u8; 32]) -> Self {
Self::from(Actor::Visitor(hex::encode(key)))
}
#[must_use]
pub fn visitor_key(&self) -> Option<[u8; 32]> {
match &self.by {
Actor::Visitor(key) => hex::decode(key).ok()?.try_into().ok(),
_ => None,
}
}
#[must_use]
pub fn bot(id: impl Into<String>) -> Self {
Self::member(MemberId::bot(id))
}
#[must_use]
pub fn in_app(mut self, app: impl Into<AppId>) -> Self {
self.app = Some(app.into());
self
}
#[must_use]
pub fn automation(id: impl Into<String>) -> Self {
Self {
by: Actor::automation(id),
agent_session: None,
app: None,
cause: None,
foreign_device: false,
handed: false,
acted_for: Vec::new(),
}
}
#[must_use]
pub fn acting_for(mut self, who: Acting) -> Self {
self.acted_for.push(who);
self
}
#[must_use]
pub fn agent_of(mut self, owner: impl Into<PersonId>) -> Self {
let owner = owner.into();
if !self.people().contains(&owner.as_str()) {
self.acted_for.push(Self::person(owner));
}
self
}
#[must_use]
pub fn on_foreign_device(mut self, foreign: bool) -> Self {
self.foreign_device = foreign;
self
}
#[must_use]
#[track_caller]
pub fn handed_agent(agent: impl Into<String>, person: impl Into<PersonId>) -> Self {
let person = person.into();
Self::agent(agent, person.clone())
.handed()
.acting_for(Self::member(MemberId::Person(person)))
}
#[must_use]
pub fn handed_on(self, agent: impl Into<String>) -> Option<Self> {
let starter = self.member_id()?.agent_person()?.clone();
let mut on = Self::member(MemberId::Agent {
id: agent.into(),
person: starter,
})
.handed();
if let Some(person) = self.acted_for_person() {
on = on.acting_for(Self::person(person.to_owned()));
}
Some(on.acting_for(self))
}
#[must_use]
pub const fn handed(mut self) -> Self {
self.handed = true;
self
}
#[must_use]
pub fn signed_by(mut self, signer: &Self) -> Self {
if signer.foreign_device {
self.unhand();
}
let person = signer
.direct_person()
.filter(|_| !signer.foreign_device)
.map(str::to_owned);
if let Some(person) = person
&& self.people().contains(&person.as_str())
{
return self;
}
if self.app.is_none() {
self.app.clone_from(&signer.app);
}
self.acting_for(signer.clone())
}
fn unhand(&mut self) {
self.handed = false;
for node in &mut self.acted_for {
node.unhand();
}
}
#[must_use]
pub fn caused_by(mut self, cause: impl Into<String>) -> Self {
self.cause = Some(ResourceId::new(cause));
self
}
#[must_use]
pub fn in_session(mut self, session: impl Into<String>) -> Self {
self.agent_session = Some(AgentSessionId::new(session));
self
}
#[must_use]
pub fn delegated(&self) -> bool {
self.foreign_device
|| !self.acted_for.is_empty()
|| !matches!(self.by, Actor::Member(MemberId::Person(_)))
}
#[must_use]
pub fn direct(&self) -> bool {
!self.delegated()
}
#[must_use]
pub fn direct_person(&self) -> Option<&str> {
if !self.direct() {
return None;
}
let Actor::Member(MemberId::Person(person)) = &self.by else {
return None;
};
Some(person.as_str())
}
#[must_use]
pub fn app(&self) -> Option<&AppId> {
self.app.as_ref()
}
#[must_use]
pub fn member_id(&self) -> Option<&MemberId> {
self.by.member_id()
}
#[must_use]
pub fn is_person(&self) -> bool {
self.by.member_id().is_some_and(MemberId::is_person)
}
#[must_use]
pub fn is_agent(&self) -> bool {
self.by.member_id().is_some_and(MemberId::is_agent)
}
#[must_use]
pub fn is_bot(&self) -> bool {
self.by.member_id().is_some_and(MemberId::is_bot)
}
#[must_use]
pub fn is_automation(&self) -> bool {
matches!(self.by, Actor::Automation(_))
}
#[must_use]
pub fn person_id(&self) -> Option<&str> {
self.by.member_id().and_then(MemberId::person_id)
}
#[must_use]
pub fn agent_id(&self) -> Option<&str> {
self.by.member_id().and_then(MemberId::agent_id)
}
#[must_use]
pub fn bot_id(&self) -> Option<&str> {
self.by.member_id().and_then(MemberId::bot_id)
}
#[must_use]
pub fn acted_for_person(&self) -> Option<&str> {
self.acted_for
.first()
.and_then(|node| node.by.member_id())
.and_then(MemberId::person_id)
}
pub fn members(&self) -> Vec<&MemberId> {
let mut members: Vec<&MemberId> = self.by.member_id().into_iter().collect();
for node in &self.acted_for {
members.extend(node.members());
}
members
}
pub fn nodes(&self) -> Vec<&Self> {
std::iter::once(self)
.chain(self.acted_for.iter().flat_map(Self::nodes))
.collect()
}
pub fn people(&self) -> Vec<&str> {
self.nodes()
.into_iter()
.filter_map(|node| node.by.member_id().and_then(MemberId::person_id))
.collect()
}
}
#[must_use]
pub fn key_agent_id(device_public_key: &[u8; 32]) -> String {
format!("{KEY_AGENT_PREFIX}{}", hex::encode(device_public_key))
}
#[must_use]
pub fn key_of_agent(agent: &str) -> Option<[u8; 32]> {
let hex = agent.strip_prefix(KEY_AGENT_PREFIX)?;
hex::decode(hex).ok()?.try_into().ok()
}
const KEY_AGENT_PREFIX: &str = "grant-";
impl tilo_presence::WearsHue for MemberId {
fn wearer(&self) -> tilo_presence::Wearer<'_> {
match self {
Self::Agent { id, .. } | Self::Bot(id) => tilo_presence::Wearer::Software(id),
Self::Person(person) => tilo_presence::Wearer::Person(person.as_str()),
}
}
}
impl tilo_presence::WearsHue for Actor {
fn wearer(&self) -> tilo_presence::Wearer<'_> {
match self.member_id() {
Some(member) => tilo_presence::WearsHue::wearer(member),
None => tilo_presence::Wearer::Person(self.id()),
}
}
}
#[must_use]
pub fn identity_color(identity: &str) -> (u8, u8, u8) {
match MemberId::of_actor_bytes(identity.as_bytes()) {
Some(member) => tilo_presence::member_color(&member),
None => tilo_presence::user_color(identity),
}
}
#[cfg(test)]
mod tests {
use super::*;
tilo_test_env::scenario! {
fn a_member_tree_names_and_writes_its_members;
phase a_tree_names_every_member_and_person_in_it;
{
let acting =
Acting::agent("claude", "q").acting_for(Acting::person("q").acting_for(Acting::person("x")));
assert!(acting.delegated());
assert_eq!(acting.direct_person(), None);
assert_eq!(
acting.members(),
[
&MemberId::agent("claude", "q"),
&MemberId::person("q"),
&MemberId::person("x")
]
);
assert_eq!(acting.people(), vec!["q", "x"]);
let person = Acting::person("q");
assert!(person.direct());
assert_eq!(person.direct_person(), Some("q"));
assert!(Acting::person("q").on_foreign_device(true).delegated());
}
phase an_agent_answering_someone_else_is_bounded_by_its_own_person_too;
{
let for_bo = Acting::handed_agent("scout", "bo").agent_of("ada");
assert_eq!(for_bo.people(), vec!["bo", "ada"], "Bo first, Ada bounding it");
assert_eq!(for_bo.acted_for_person(), Some("bo"), "it answers Bo");
let for_ada = Acting::handed_agent("scout", "ada").agent_of("ada");
assert_eq!(for_ada, Acting::handed_agent("scout", "ada"), "its own person once");
}
phase a_sub_agent_is_one_more_actor_in_its_starters_chain;
{
let starter = Acting::agent("scout", "ada").acting_for(Acting::person("bo")).agent_of("ada");
let helper = starter.clone().handed_on("helper").expect("an agent starts it");
assert_eq!(helper.member_id(), Some(&MemberId::agent("helper", "ada")), "Ada's agent's");
assert_eq!(helper.acted_for_person(), Some("bo"), "it works for Bo");
assert!(helper.handed, "with the preset an agent gets for Bo");
assert!(helper.people().contains(&"ada"), "Ada bounds it: {helper:?}");
assert!(
helper.nodes().iter().any(|node| **node == starter),
"its starter's whole tree bounds it: {helper:?}"
);
let signer = Acting::agent("scout", "ada").acting_for(Acting::person("ada"));
let signed = helper.signed_by(&signer);
assert!(signed.handed, "{signed:?}");
}
phase a_member_is_read_back_from_the_bytes_a_document_names_it_by;
{
for member in [
MemberId::person(PersonId::from_root([5; 32])),
MemberId::agent("helper", PersonId::from_root([5; 32])),
MemberId::bot("mod"),
] {
assert_eq!(
MemberId::of_actor_bytes(&member.actor_bytes()),
Some(member)
);
}
assert_eq!(MemberId::of_actor_bytes(b"automation:1"), None);
assert_eq!(MemberId::of_actor_bytes(b"agent:"), None);
assert_eq!(MemberId::of_actor_bytes(b""), None);
}
phase the_tree_is_written_as_it_is_read;
{
let acting = Acting::automation("1")
.acting_for(
Acting::agent("claude", "q")
.acting_for(Acting::person("q"))
.acting_for(Acting::person("x")),
)
.caused_by("chat.message:m1");
let json = serde_json::to_string(&acting).unwrap();
assert_eq!(serde_json::from_str::<Acting>(&json).unwrap(), acting);
assert!(json.contains("\"for\""), "{json}");
}
}
}