1use serde::{Deserialize, Serialize};
4use tilo_app_id::AppId;
5
6use crate::person::PersonId;
7
8#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
10#[serde(rename_all = "snake_case")]
11pub enum MemberId {
12 Person(PersonId),
14 Agent {
18 id: String,
19 person: PersonId,
20 },
21 Bot(String),
22}
23
24pub const DIRECT_CONVERSATION_PREFIX: &str = "direct:";
27
28impl MemberId {
29 #[must_use]
32 pub fn mark_value(&self) -> String {
33 serde_json::to_string(self).unwrap_or_default()
34 }
35
36 #[must_use]
39 pub fn of_mark_value(value: &str) -> Option<Self> {
40 value
41 .starts_with('{')
42 .then(|| serde_json::from_str(value).ok())
43 .flatten()
44 }
45
46 #[must_use]
51 pub fn direct_conversation(members: impl IntoIterator<Item = Self>) -> String {
52 let mut members: Vec<Self> = members.into_iter().collect();
53 members.sort();
54 members.dedup();
55 let members = serde_json::to_string(&members).unwrap_or_default();
56 format!("{DIRECT_CONVERSATION_PREFIX}{members}")
57 }
58
59 #[track_caller]
60 #[must_use]
61 pub fn person(id: impl Into<PersonId>) -> Self {
62 Self::Person(id.into())
63 }
64
65 #[must_use]
68 pub fn parsed_person(id: &str) -> Option<Self> {
69 PersonId::parse(id).ok().map(Self::Person)
70 }
71
72 #[track_caller]
74 #[must_use]
75 pub fn agent(id: impl Into<String>, person: impl Into<PersonId>) -> Self {
76 Self::Agent {
77 id: id.into(),
78 person: person.into(),
79 }
80 }
81
82 #[must_use]
83 pub fn bot(id: impl Into<String>) -> Self {
84 Self::Bot(id.into())
85 }
86
87 #[must_use]
89 pub fn id(&self) -> &str {
90 match self {
91 Self::Person(id) => id.as_str(),
92 Self::Agent { id, .. } | Self::Bot(id) => id,
93 }
94 }
95
96 #[must_use]
97 pub fn agent_id(&self) -> Option<&str> {
98 match self {
99 Self::Agent { id, .. } => Some(id),
100 Self::Person(_) | Self::Bot(_) => None,
101 }
102 }
103
104 #[must_use]
106 pub fn agent_person(&self) -> Option<&PersonId> {
107 match self {
108 Self::Agent { person, .. } => Some(person),
109 Self::Person(_) | Self::Bot(_) => None,
110 }
111 }
112
113 #[must_use]
115 pub fn as_agent(&self) -> Option<(&str, &PersonId)> {
116 match self {
117 Self::Agent { id, person } => Some((id, person)),
118 Self::Person(_) | Self::Bot(_) => None,
119 }
120 }
121
122 #[must_use]
123 pub fn bot_id(&self) -> Option<&str> {
124 match self {
125 Self::Bot(id) => Some(id),
126 Self::Person(_) | Self::Agent { .. } => None,
127 }
128 }
129
130 #[must_use]
132 pub fn as_person(&self) -> Option<&PersonId> {
133 match self {
134 Self::Person(id) => Some(id),
135 Self::Agent { .. } | Self::Bot(_) => None,
136 }
137 }
138
139 #[must_use]
141 pub fn person_id(&self) -> Option<&str> {
142 self.as_person().map(PersonId::as_str)
143 }
144
145 #[must_use]
146 pub const fn is_person(&self) -> bool {
147 matches!(self, Self::Person(_))
148 }
149
150 #[must_use]
151 pub const fn is_agent(&self) -> bool {
152 matches!(self, Self::Agent { .. })
153 }
154
155 #[must_use]
156 pub const fn is_bot(&self) -> bool {
157 matches!(self, Self::Bot(_))
158 }
159
160 #[must_use]
163 pub fn actor_bytes(&self) -> Vec<u8> {
164 match self {
165 Self::Person(id) => id.as_str().as_bytes().to_vec(),
166 Self::Agent { id, person } => {
167 [b"agent:", person.as_str().as_bytes(), b"/", id.as_bytes()].concat()
168 }
169 Self::Bot(id) => [b"bot:", id.as_bytes()].concat(),
170 }
171 }
172
173 #[must_use]
176 pub fn of_actor_bytes(bytes: &[u8]) -> Option<Self> {
177 let text = std::str::from_utf8(bytes).ok()?;
178 let nonempty = |id: &str| (!id.is_empty()).then(|| id.to_owned());
179 if let Some(agent) = text.strip_prefix("agent:") {
180 let (person, id) = agent.split_once('/')?;
181 let person = PersonId::parse(&nonempty(person)?).ok()?;
182 return nonempty(id).map(|id| Self::Agent { id, person });
183 }
184 if let Some(id) = text.strip_prefix("bot:") {
185 return nonempty(id).map(Self::Bot);
186 }
187 nonempty(text).and_then(|id| PersonId::parse(&id).ok().map(Self::Person))
188 }
189}
190
191impl std::fmt::Display for MemberId {
192 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
193 match self {
194 Self::Person(id) => write!(f, "person {}", short(id.as_str())),
195 Self::Agent { id, person } => write!(f, "agent {id} of {}", short(person.as_str())),
196 Self::Bot(id) => write!(f, "bot {}", short(id)),
197 }
198 }
199}
200
201fn short(id: &str) -> &str {
202 id.get(..12).unwrap_or(id)
203}
204
205#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)]
208#[serde(transparent)]
209pub struct AutomationId(pub String);
210
211impl AutomationId {
212 #[must_use]
213 pub fn new(id: impl Into<String>) -> Self {
214 Self(id.into())
215 }
216
217 #[must_use]
218 pub fn as_str(&self) -> &str {
219 &self.0
220 }
221}
222
223#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
226#[serde(transparent)]
227pub struct AgentSessionId(pub String);
228
229impl AgentSessionId {
230 #[must_use]
231 pub fn new(id: impl Into<String>) -> Self {
232 Self(id.into())
233 }
234
235 #[must_use]
236 pub fn as_str(&self) -> &str {
237 &self.0
238 }
239}
240
241#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
243#[serde(transparent)]
244pub struct ResourceId(pub String);
245
246impl ResourceId {
247 #[must_use]
248 pub fn new(id: impl Into<String>) -> Self {
249 Self(id.into())
250 }
251
252 #[must_use]
253 pub fn as_str(&self) -> &str {
254 &self.0
255 }
256}
257
258impl std::fmt::Display for ResourceId {
259 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
260 f.write_str(&self.0)
261 }
262}
263
264#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
266#[serde(rename_all = "snake_case")]
267pub enum Actor {
268 Member(MemberId),
269 Automation(AutomationId),
270 App(AppId),
273 Visitor(String),
277}
278
279impl Actor {
280 #[must_use]
281 pub fn member(member: MemberId) -> Self {
282 Self::Member(member)
283 }
284
285 #[must_use]
286 pub fn automation(id: impl Into<String>) -> Self {
287 Self::Automation(AutomationId::new(id))
288 }
289
290 #[must_use]
293 pub fn grantee(&self) -> Option<crate::Grantee> {
294 Some(crate::granted_to(self.member_id()?))
295 }
296
297 #[must_use]
299 pub fn member_id(&self) -> Option<&MemberId> {
300 match self {
301 Self::Member(member) => Some(member),
302 Self::Automation(_) | Self::App(_) | Self::Visitor(_) => None,
303 }
304 }
305
306 #[must_use]
308 pub fn person_id(&self) -> Option<&str> {
309 self.member_id().and_then(MemberId::person_id)
310 }
311
312 #[must_use]
314 pub fn agent_id(&self) -> Option<&str> {
315 self.member_id().and_then(MemberId::agent_id)
316 }
317
318 #[must_use]
320 pub fn app(&self) -> Option<&AppId> {
321 match self {
322 Self::App(app) => Some(app),
323 Self::Member(_) | Self::Automation(_) | Self::Visitor(_) => None,
324 }
325 }
326
327 #[must_use]
330 pub fn actor_bytes(&self) -> Vec<u8> {
331 match self {
332 Self::Member(member) => member.actor_bytes(),
333 Self::Automation(id) => [b"automation:", id.as_str().as_bytes()].concat(),
334 Self::App(app) => [b"app:", app.as_str().as_bytes()].concat(),
335 Self::Visitor(key) => [b"visitor:", key.as_bytes()].concat(),
336 }
337 }
338
339 #[must_use]
342 pub fn of_actor_bytes(bytes: &[u8]) -> Option<Self> {
343 let nonempty = |id: &[u8]| {
344 std::str::from_utf8(id)
345 .ok()
346 .filter(|id| !id.is_empty())
347 .map(str::to_owned)
348 };
349 if let Some(id) = bytes.strip_prefix(b"automation:") {
350 return nonempty(id).map(|id| Self::Automation(AutomationId(id)));
351 }
352 if let Some(app) = bytes.strip_prefix(b"app:") {
353 return nonempty(app).map(|app| Self::App(AppId::new(app)));
354 }
355 if let Some(key) = bytes.strip_prefix(b"visitor:") {
356 return nonempty(key).map(Self::Visitor);
357 }
358 MemberId::of_actor_bytes(bytes).map(Self::Member)
359 }
360
361 #[must_use]
363 pub fn id(&self) -> &str {
364 match self {
365 Self::Member(member) => member.id(),
366 Self::Automation(id) => id.as_str(),
367 Self::App(app) => app.as_str(),
368 Self::Visitor(key) => key,
369 }
370 }
371}
372
373impl From<Actor> for Acting {
374 fn from(actor: Actor) -> Self {
375 Self {
376 by: actor,
377 agent_session: None,
378 app: None,
379 cause: None,
380 foreign_device: false,
381 handed: false,
382 acted_for: Vec::new(),
383 }
384 }
385}
386
387impl From<MemberId> for Actor {
388 fn from(member: MemberId) -> Self {
389 Self::Member(member)
390 }
391}
392
393impl std::fmt::Display for Actor {
394 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
395 match self {
396 Self::Member(member) => member.fmt(f),
397 Self::Automation(id) => write!(f, "automation {}", id.as_str()),
398 Self::App(app) => write!(f, "app {app}"),
399 Self::Visitor(key) => write!(f, "visitor {}", key.get(..8).unwrap_or(key)),
400 }
401 }
402}
403
404#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
411pub struct Acting {
412 pub by: Actor,
413 #[serde(default)]
415 pub app: Option<AppId>,
416 #[serde(default)]
418 pub agent_session: Option<AgentSessionId>,
419 #[serde(default)]
421 pub cause: Option<ResourceId>,
422 #[serde(default)]
424 pub foreign_device: bool,
425 #[serde(default)]
431 pub handed: bool,
432 #[serde(default, rename = "for")]
434 pub acted_for: Vec<Acting>,
435}
436
437impl Acting {
438 #[must_use]
440 pub fn member(member: MemberId) -> Self {
441 Self {
442 by: Actor::Member(member),
443 agent_session: None,
444 app: None,
445 cause: None,
446 foreign_device: false,
447 handed: false,
448 acted_for: Vec::new(),
449 }
450 }
451
452 #[track_caller]
453 #[must_use]
454 pub fn person(id: impl Into<PersonId>) -> Self {
455 Self::member(MemberId::person(id))
456 }
457
458 #[must_use]
461 pub fn by_app(id: impl Into<AppId>) -> Self {
462 Self {
463 by: Actor::App(id.into()),
464 agent_session: None,
465 app: None,
466 cause: None,
467 foreign_device: false,
468 handed: false,
469 acted_for: Vec::new(),
470 }
471 }
472
473 #[track_caller]
476 #[must_use]
477 pub fn agent(id: impl Into<String>, person: impl Into<PersonId>) -> Self {
478 Self::member(MemberId::agent(id, person))
479 }
480
481 #[must_use]
484 pub fn visitor(key: &[u8; 32]) -> Self {
485 Self::from(Actor::Visitor(hex::encode(key)))
486 }
487
488 #[must_use]
490 pub fn visitor_key(&self) -> Option<[u8; 32]> {
491 match &self.by {
492 Actor::Visitor(key) => hex::decode(key).ok()?.try_into().ok(),
493 _ => None,
494 }
495 }
496
497 #[must_use]
498 pub fn bot(id: impl Into<String>) -> Self {
499 Self::member(MemberId::bot(id))
500 }
501
502 #[must_use]
504 pub fn in_app(mut self, app: impl Into<AppId>) -> Self {
505 self.app = Some(app.into());
506 self
507 }
508
509 #[must_use]
510 pub fn automation(id: impl Into<String>) -> Self {
511 Self {
512 by: Actor::automation(id),
513 agent_session: None,
514 app: None,
515 cause: None,
516 foreign_device: false,
517 handed: false,
518 acted_for: Vec::new(),
519 }
520 }
521
522 #[must_use]
524 pub fn acting_for(mut self, who: Acting) -> Self {
525 self.acted_for.push(who);
526 self
527 }
528
529 #[must_use]
534 pub fn agent_of(mut self, owner: impl Into<PersonId>) -> Self {
535 let owner = owner.into();
536 if !self.people().contains(&owner.as_str()) {
537 self.acted_for.push(Self::person(owner));
538 }
539 self
540 }
541
542 #[must_use]
544 pub fn on_foreign_device(mut self, foreign: bool) -> Self {
545 self.foreign_device = foreign;
546 self
547 }
548
549 #[must_use]
552 #[track_caller]
553 pub fn handed_agent(agent: impl Into<String>, person: impl Into<PersonId>) -> Self {
554 let person = person.into();
555 Self::agent(agent, person.clone())
556 .handed()
557 .acting_for(Self::member(MemberId::Person(person)))
558 }
559
560 #[must_use]
566 pub fn handed_on(self, agent: impl Into<String>) -> Option<Self> {
567 let starter = self.member_id()?.agent_person()?.clone();
568 let mut on = Self::member(MemberId::Agent {
569 id: agent.into(),
570 person: starter,
571 })
572 .handed();
573 if let Some(person) = self.acted_for_person() {
574 on = on.acting_for(Self::person(person.to_owned()));
575 }
576 Some(on.acting_for(self))
577 }
578
579 #[must_use]
582 pub const fn handed(mut self) -> Self {
583 self.handed = true;
584 self
585 }
586
587 #[must_use]
594 pub fn signed_by(mut self, signer: &Self) -> Self {
595 if signer.foreign_device {
599 self.unhand();
600 }
601 let person = signer
602 .direct_person()
603 .filter(|_| !signer.foreign_device)
604 .map(str::to_owned);
605 if let Some(person) = person
607 && self.people().contains(&person.as_str())
608 {
609 return self;
610 }
611 if self.app.is_none() {
612 self.app.clone_from(&signer.app);
613 }
614 self.acting_for(signer.clone())
615 }
616
617 fn unhand(&mut self) {
620 self.handed = false;
621 for node in &mut self.acted_for {
622 node.unhand();
623 }
624 }
625
626 #[must_use]
628 pub fn caused_by(mut self, cause: impl Into<String>) -> Self {
629 self.cause = Some(ResourceId::new(cause));
630 self
631 }
632
633 #[must_use]
635 pub fn in_session(mut self, session: impl Into<String>) -> Self {
636 self.agent_session = Some(AgentSessionId::new(session));
637 self
638 }
639
640 #[must_use]
643 pub fn delegated(&self) -> bool {
644 self.foreign_device
645 || !self.acted_for.is_empty()
646 || !matches!(self.by, Actor::Member(MemberId::Person(_)))
647 }
648
649 #[must_use]
651 pub fn direct(&self) -> bool {
652 !self.delegated()
653 }
654
655 #[must_use]
657 pub fn direct_person(&self) -> Option<&str> {
658 if !self.direct() {
659 return None;
660 }
661 let Actor::Member(MemberId::Person(person)) = &self.by else {
662 return None;
663 };
664 Some(person.as_str())
665 }
666
667 #[must_use]
669 pub fn app(&self) -> Option<&AppId> {
670 self.app.as_ref()
671 }
672
673 #[must_use]
675 pub fn member_id(&self) -> Option<&MemberId> {
676 self.by.member_id()
677 }
678
679 #[must_use]
680 pub fn is_person(&self) -> bool {
681 self.by.member_id().is_some_and(MemberId::is_person)
682 }
683
684 #[must_use]
685 pub fn is_agent(&self) -> bool {
686 self.by.member_id().is_some_and(MemberId::is_agent)
687 }
688
689 #[must_use]
690 pub fn is_bot(&self) -> bool {
691 self.by.member_id().is_some_and(MemberId::is_bot)
692 }
693
694 #[must_use]
695 pub fn is_automation(&self) -> bool {
696 matches!(self.by, Actor::Automation(_))
697 }
698
699 #[must_use]
700 pub fn person_id(&self) -> Option<&str> {
701 self.by.member_id().and_then(MemberId::person_id)
702 }
703
704 #[must_use]
705 pub fn agent_id(&self) -> Option<&str> {
706 self.by.member_id().and_then(MemberId::agent_id)
707 }
708
709 #[must_use]
710 pub fn bot_id(&self) -> Option<&str> {
711 self.by.member_id().and_then(MemberId::bot_id)
712 }
713
714 #[must_use]
716 pub fn acted_for_person(&self) -> Option<&str> {
717 self.acted_for
718 .first()
719 .and_then(|node| node.by.member_id())
720 .and_then(MemberId::person_id)
721 }
722
723 pub fn members(&self) -> Vec<&MemberId> {
725 let mut members: Vec<&MemberId> = self.by.member_id().into_iter().collect();
726 for node in &self.acted_for {
727 members.extend(node.members());
728 }
729 members
730 }
731
732 pub fn nodes(&self) -> Vec<&Self> {
734 std::iter::once(self)
735 .chain(self.acted_for.iter().flat_map(Self::nodes))
736 .collect()
737 }
738
739 pub fn people(&self) -> Vec<&str> {
741 self.nodes()
742 .into_iter()
743 .filter_map(|node| node.by.member_id().and_then(MemberId::person_id))
744 .collect()
745 }
746}
747
748#[must_use]
752pub fn key_agent_id(device_public_key: &[u8; 32]) -> String {
753 format!("{KEY_AGENT_PREFIX}{}", hex::encode(device_public_key))
754}
755
756#[must_use]
759pub fn key_of_agent(agent: &str) -> Option<[u8; 32]> {
760 let hex = agent.strip_prefix(KEY_AGENT_PREFIX)?;
761 hex::decode(hex).ok()?.try_into().ok()
762}
763
764const KEY_AGENT_PREFIX: &str = "grant-";
766
767impl tilo_presence::WearsHue for MemberId {
769 fn wearer(&self) -> tilo_presence::Wearer<'_> {
770 match self {
771 Self::Agent { id, .. } | Self::Bot(id) => tilo_presence::Wearer::Software(id),
772 Self::Person(person) => tilo_presence::Wearer::Person(person.as_str()),
773 }
774 }
775}
776
777impl tilo_presence::WearsHue for Actor {
779 fn wearer(&self) -> tilo_presence::Wearer<'_> {
780 match self.member_id() {
781 Some(member) => tilo_presence::WearsHue::wearer(member),
782 None => tilo_presence::Wearer::Person(self.id()),
783 }
784 }
785}
786
787#[must_use]
793pub fn identity_color(identity: &str) -> (u8, u8, u8) {
794 match MemberId::of_actor_bytes(identity.as_bytes()) {
795 Some(member) => tilo_presence::member_color(&member),
796 None => tilo_presence::user_color(identity),
797 }
798}
799
800#[cfg(test)]
801mod tests {
802 use super::*;
803
804 tilo_test_env::scenario! {
805 fn a_member_tree_names_and_writes_its_members;
806
807 phase a_tree_names_every_member_and_person_in_it;
808 {
809 let acting =
810 Acting::agent("claude", "q").acting_for(Acting::person("q").acting_for(Acting::person("x")));
811 assert!(acting.delegated());
812 assert_eq!(acting.direct_person(), None);
813 assert_eq!(
814 acting.members(),
815 [
816 &MemberId::agent("claude", "q"),
817 &MemberId::person("q"),
818 &MemberId::person("x")
819 ]
820 );
821 assert_eq!(acting.people(), vec!["q", "x"]);
822 let person = Acting::person("q");
823 assert!(person.direct());
824 assert_eq!(person.direct_person(), Some("q"));
825 assert!(Acting::person("q").on_foreign_device(true).delegated());
826 }
827
828 phase an_agent_answering_someone_else_is_bounded_by_its_own_person_too;
829 {
830 let for_bo = Acting::handed_agent("scout", "bo").agent_of("ada");
831 assert_eq!(for_bo.people(), vec!["bo", "ada"], "Bo first, Ada bounding it");
832 assert_eq!(for_bo.acted_for_person(), Some("bo"), "it answers Bo");
833 let for_ada = Acting::handed_agent("scout", "ada").agent_of("ada");
834 assert_eq!(for_ada, Acting::handed_agent("scout", "ada"), "its own person once");
835 }
836
837 phase a_sub_agent_is_one_more_actor_in_its_starters_chain;
838 {
841 let starter = Acting::agent("scout", "ada").acting_for(Acting::person("bo")).agent_of("ada");
842 let helper = starter.clone().handed_on("helper").expect("an agent starts it");
843 assert_eq!(helper.member_id(), Some(&MemberId::agent("helper", "ada")), "Ada's agent's");
844 assert_eq!(helper.acted_for_person(), Some("bo"), "it works for Bo");
845 assert!(helper.handed, "with the preset an agent gets for Bo");
846 assert!(helper.people().contains(&"ada"), "Ada bounds it: {helper:?}");
847 assert!(
848 helper.nodes().iter().any(|node| **node == starter),
849 "its starter's whole tree bounds it: {helper:?}"
850 );
851 let signer = Acting::agent("scout", "ada").acting_for(Acting::person("ada"));
854 let signed = helper.signed_by(&signer);
855 assert!(signed.handed, "{signed:?}");
856 }
857
858 phase a_member_is_read_back_from_the_bytes_a_document_names_it_by;
859 {
860 for member in [
861 MemberId::person(PersonId::from_root([5; 32])),
862 MemberId::agent("helper", PersonId::from_root([5; 32])),
863 MemberId::bot("mod"),
864 ] {
865 assert_eq!(
866 MemberId::of_actor_bytes(&member.actor_bytes()),
867 Some(member)
868 );
869 }
870 assert_eq!(MemberId::of_actor_bytes(b"automation:1"), None);
871 assert_eq!(MemberId::of_actor_bytes(b"agent:"), None);
872 assert_eq!(MemberId::of_actor_bytes(b""), None);
873 }
874
875 phase the_tree_is_written_as_it_is_read;
876 {
877 let acting = Acting::automation("1")
878 .acting_for(
879 Acting::agent("claude", "q")
880 .acting_for(Acting::person("q"))
881 .acting_for(Acting::person("x")),
882 )
883 .caused_by("chat.message:m1");
884 let json = serde_json::to_string(&acting).unwrap();
885 assert_eq!(serde_json::from_str::<Acting>(&json).unwrap(), acting);
886 assert!(json.contains("\"for\""), "{json}");
887 }
888 }
889}