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 #[must_use]
62 pub fn direct_conversation_members(id: &str) -> Option<Vec<Self>> {
63 let members = id.strip_prefix(DIRECT_CONVERSATION_PREFIX)?;
64 serde_json::from_str::<Vec<Self>>(members)
65 .ok()
66 .filter(|members| !members.is_empty())
67 }
68
69 #[track_caller]
70 #[must_use]
71 pub fn person(id: impl Into<PersonId>) -> Self {
72 Self::Person(id.into())
73 }
74
75 #[must_use]
78 pub fn parsed_person(id: &str) -> Option<Self> {
79 PersonId::parse(id).ok().map(Self::Person)
80 }
81
82 #[track_caller]
84 #[must_use]
85 pub fn agent(id: impl Into<String>, person: impl Into<PersonId>) -> Self {
86 Self::Agent {
87 id: id.into(),
88 person: person.into(),
89 }
90 }
91
92 #[must_use]
93 pub fn bot(id: impl Into<String>) -> Self {
94 Self::Bot(id.into())
95 }
96
97 #[must_use]
99 pub fn id(&self) -> &str {
100 match self {
101 Self::Person(id) => id.as_str(),
102 Self::Agent { id, .. } | Self::Bot(id) => id,
103 }
104 }
105
106 #[must_use]
107 pub fn agent_id(&self) -> Option<&str> {
108 match self {
109 Self::Agent { id, .. } => Some(id),
110 Self::Person(_) | Self::Bot(_) => None,
111 }
112 }
113
114 #[must_use]
116 pub fn agent_person(&self) -> Option<&PersonId> {
117 match self {
118 Self::Agent { person, .. } => Some(person),
119 Self::Person(_) | Self::Bot(_) => None,
120 }
121 }
122
123 #[must_use]
125 pub fn as_agent(&self) -> Option<(&str, &PersonId)> {
126 match self {
127 Self::Agent { id, person } => Some((id, person)),
128 Self::Person(_) | Self::Bot(_) => None,
129 }
130 }
131
132 #[must_use]
133 pub fn bot_id(&self) -> Option<&str> {
134 match self {
135 Self::Bot(id) => Some(id),
136 Self::Person(_) | Self::Agent { .. } => None,
137 }
138 }
139
140 #[must_use]
142 pub fn as_person(&self) -> Option<&PersonId> {
143 match self {
144 Self::Person(id) => Some(id),
145 Self::Agent { .. } | Self::Bot(_) => None,
146 }
147 }
148
149 #[must_use]
151 pub fn person_id(&self) -> Option<&str> {
152 self.as_person().map(PersonId::as_str)
153 }
154
155 #[must_use]
156 pub const fn is_person(&self) -> bool {
157 matches!(self, Self::Person(_))
158 }
159
160 #[must_use]
161 pub const fn is_agent(&self) -> bool {
162 matches!(self, Self::Agent { .. })
163 }
164
165 #[must_use]
166 pub const fn is_bot(&self) -> bool {
167 matches!(self, Self::Bot(_))
168 }
169
170 #[must_use]
173 pub fn actor_bytes(&self) -> Vec<u8> {
174 match self {
175 Self::Person(id) => id.as_str().as_bytes().to_vec(),
176 Self::Agent { id, person } => {
177 [b"agent:", person.as_str().as_bytes(), b"/", id.as_bytes()].concat()
178 }
179 Self::Bot(id) => [b"bot:", id.as_bytes()].concat(),
180 }
181 }
182
183 #[must_use]
186 pub fn of_actor_bytes(bytes: &[u8]) -> Option<Self> {
187 let text = std::str::from_utf8(bytes).ok()?;
188 let nonempty = |id: &str| (!id.is_empty()).then(|| id.to_owned());
189 if let Some(agent) = text.strip_prefix("agent:") {
190 let (person, id) = agent.split_once('/')?;
191 let person = PersonId::parse(&nonempty(person)?).ok()?;
192 return nonempty(id).map(|id| Self::Agent { id, person });
193 }
194 if let Some(id) = text.strip_prefix("bot:") {
195 return nonempty(id).map(Self::Bot);
196 }
197 nonempty(text).and_then(|id| PersonId::parse(&id).ok().map(Self::Person))
198 }
199}
200
201impl std::fmt::Display for MemberId {
202 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
203 match self {
204 Self::Person(id) => write!(f, "person {}", short(id.as_str())),
205 Self::Agent { id, person } => write!(f, "agent {id} of {}", short(person.as_str())),
206 Self::Bot(id) => write!(f, "bot {}", short(id)),
207 }
208 }
209}
210
211fn short(id: &str) -> &str {
212 id.get(..12).unwrap_or(id)
213}
214
215#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)]
218#[serde(transparent)]
219pub struct AutomationId(pub String);
220
221impl AutomationId {
222 #[must_use]
223 pub fn new(id: impl Into<String>) -> Self {
224 Self(id.into())
225 }
226
227 #[must_use]
228 pub fn as_str(&self) -> &str {
229 &self.0
230 }
231}
232
233#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
236#[serde(transparent)]
237pub struct AgentSessionId(pub String);
238
239impl AgentSessionId {
240 #[must_use]
241 pub fn new(id: impl Into<String>) -> Self {
242 Self(id.into())
243 }
244
245 #[must_use]
246 pub fn as_str(&self) -> &str {
247 &self.0
248 }
249}
250
251#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
253#[serde(transparent)]
254pub struct ResourceId(pub String);
255
256impl ResourceId {
257 #[must_use]
258 pub fn new(id: impl Into<String>) -> Self {
259 Self(id.into())
260 }
261
262 #[must_use]
263 pub fn as_str(&self) -> &str {
264 &self.0
265 }
266}
267
268impl std::fmt::Display for ResourceId {
269 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
270 f.write_str(&self.0)
271 }
272}
273
274#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
276#[serde(rename_all = "snake_case")]
277pub enum Actor {
278 Member(MemberId),
279 Automation(AutomationId),
280 App(AppId),
283 Visitor(String),
287}
288
289impl Actor {
290 #[must_use]
291 pub fn member(member: MemberId) -> Self {
292 Self::Member(member)
293 }
294
295 #[must_use]
296 pub fn automation(id: impl Into<String>) -> Self {
297 Self::Automation(AutomationId::new(id))
298 }
299
300 #[must_use]
303 pub fn grantee(&self) -> Option<crate::Grantee> {
304 Some(crate::granted_to(self.member_id()?))
305 }
306
307 #[must_use]
309 pub fn member_id(&self) -> Option<&MemberId> {
310 match self {
311 Self::Member(member) => Some(member),
312 Self::Automation(_) | Self::App(_) | Self::Visitor(_) => None,
313 }
314 }
315
316 #[must_use]
318 pub fn person_id(&self) -> Option<&str> {
319 self.member_id().and_then(MemberId::person_id)
320 }
321
322 #[must_use]
324 pub fn agent_id(&self) -> Option<&str> {
325 self.member_id().and_then(MemberId::agent_id)
326 }
327
328 #[must_use]
330 pub fn app(&self) -> Option<&AppId> {
331 match self {
332 Self::App(app) => Some(app),
333 Self::Member(_) | Self::Automation(_) | Self::Visitor(_) => None,
334 }
335 }
336
337 #[must_use]
340 pub fn actor_bytes(&self) -> Vec<u8> {
341 match self {
342 Self::Member(member) => member.actor_bytes(),
343 Self::Automation(id) => [b"automation:", id.as_str().as_bytes()].concat(),
344 Self::App(app) => [b"app:", app.as_str().as_bytes()].concat(),
345 Self::Visitor(key) => [b"visitor:", key.as_bytes()].concat(),
346 }
347 }
348
349 #[must_use]
352 pub fn of_actor_bytes(bytes: &[u8]) -> Option<Self> {
353 let nonempty = |id: &[u8]| {
354 std::str::from_utf8(id)
355 .ok()
356 .filter(|id| !id.is_empty())
357 .map(str::to_owned)
358 };
359 if let Some(id) = bytes.strip_prefix(b"automation:") {
360 return nonempty(id).map(|id| Self::Automation(AutomationId(id)));
361 }
362 if let Some(app) = bytes.strip_prefix(b"app:") {
363 return nonempty(app).map(|app| Self::App(AppId::new(app)));
364 }
365 if let Some(key) = bytes.strip_prefix(b"visitor:") {
366 return nonempty(key).map(Self::Visitor);
367 }
368 MemberId::of_actor_bytes(bytes).map(Self::Member)
369 }
370
371 #[must_use]
373 pub fn id(&self) -> &str {
374 match self {
375 Self::Member(member) => member.id(),
376 Self::Automation(id) => id.as_str(),
377 Self::App(app) => app.as_str(),
378 Self::Visitor(key) => key,
379 }
380 }
381}
382
383impl From<Actor> for Acting {
384 fn from(actor: Actor) -> Self {
385 Self {
386 by: actor,
387 agent_session: None,
388 app: None,
389 cause: None,
390 foreign_device: false,
391 handed: false,
392 acted_for: Vec::new(),
393 }
394 }
395}
396
397impl From<MemberId> for Actor {
398 fn from(member: MemberId) -> Self {
399 Self::Member(member)
400 }
401}
402
403impl std::fmt::Display for Actor {
404 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
405 match self {
406 Self::Member(member) => member.fmt(f),
407 Self::Automation(id) => write!(f, "automation {}", id.as_str()),
408 Self::App(app) => write!(f, "app {app}"),
409 Self::Visitor(key) => write!(f, "visitor {}", key.get(..8).unwrap_or(key)),
410 }
411 }
412}
413
414#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
421pub struct Acting {
422 pub by: Actor,
423 #[serde(default)]
425 pub app: Option<AppId>,
426 #[serde(default)]
428 pub agent_session: Option<AgentSessionId>,
429 #[serde(default)]
431 pub cause: Option<ResourceId>,
432 #[serde(default)]
434 pub foreign_device: bool,
435 #[serde(default)]
441 pub handed: bool,
442 #[serde(default, rename = "for")]
444 pub acted_for: Vec<Acting>,
445}
446
447impl Acting {
448 #[must_use]
450 pub fn member(member: MemberId) -> Self {
451 Self {
452 by: Actor::Member(member),
453 agent_session: None,
454 app: None,
455 cause: None,
456 foreign_device: false,
457 handed: false,
458 acted_for: Vec::new(),
459 }
460 }
461
462 #[track_caller]
463 #[must_use]
464 pub fn person(id: impl Into<PersonId>) -> Self {
465 Self::member(MemberId::person(id))
466 }
467
468 #[must_use]
471 pub fn by_app(id: impl Into<AppId>) -> Self {
472 Self {
473 by: Actor::App(id.into()),
474 agent_session: None,
475 app: None,
476 cause: None,
477 foreign_device: false,
478 handed: false,
479 acted_for: Vec::new(),
480 }
481 }
482
483 #[track_caller]
486 #[must_use]
487 pub fn agent(id: impl Into<String>, person: impl Into<PersonId>) -> Self {
488 Self::member(MemberId::agent(id, person))
489 }
490
491 #[must_use]
494 pub fn visitor(key: &[u8; 32]) -> Self {
495 Self::from(Actor::Visitor(hex::encode(key)))
496 }
497
498 #[must_use]
500 pub fn visitor_key(&self) -> Option<[u8; 32]> {
501 match &self.by {
502 Actor::Visitor(key) => hex::decode(key).ok()?.try_into().ok(),
503 _ => None,
504 }
505 }
506
507 #[must_use]
508 pub fn bot(id: impl Into<String>) -> Self {
509 Self::member(MemberId::bot(id))
510 }
511
512 #[must_use]
514 pub fn in_app(mut self, app: impl Into<AppId>) -> Self {
515 self.app = Some(app.into());
516 self
517 }
518
519 #[must_use]
520 pub fn automation(id: impl Into<String>) -> Self {
521 Self {
522 by: Actor::automation(id),
523 agent_session: None,
524 app: None,
525 cause: None,
526 foreign_device: false,
527 handed: false,
528 acted_for: Vec::new(),
529 }
530 }
531
532 #[must_use]
534 pub fn acting_for(mut self, who: Acting) -> Self {
535 self.acted_for.push(who);
536 self
537 }
538
539 #[must_use]
544 pub fn agent_of(mut self, owner: impl Into<PersonId>) -> Self {
545 let owner = owner.into();
546 if !self.people().contains(&owner.as_str()) {
547 self.acted_for.push(Self::person(owner));
548 }
549 self
550 }
551
552 #[must_use]
554 pub fn on_foreign_device(mut self, foreign: bool) -> Self {
555 self.foreign_device = foreign;
556 self
557 }
558
559 #[must_use]
562 #[track_caller]
563 pub fn handed_agent(agent: impl Into<String>, person: impl Into<PersonId>) -> Self {
564 let person = person.into();
565 Self::agent(agent, person.clone())
566 .handed()
567 .acting_for(Self::member(MemberId::Person(person)))
568 }
569
570 #[must_use]
576 pub fn handed_on(self, agent: impl Into<String>) -> Option<Self> {
577 let starter = self.member_id()?.agent_person()?.clone();
578 let mut on = Self::member(MemberId::Agent {
579 id: agent.into(),
580 person: starter,
581 })
582 .handed();
583 if let Some(person) = self.acted_for_person() {
584 on = on.acting_for(Self::person(person.to_owned()));
585 }
586 Some(on.acting_for(self))
587 }
588
589 #[must_use]
592 pub const fn handed(mut self) -> Self {
593 self.handed = true;
594 self
595 }
596
597 #[must_use]
604 pub fn signed_by(mut self, signer: &Self) -> Self {
605 if signer.foreign_device {
609 self.unhand();
610 }
611 let person = signer
612 .direct_person()
613 .filter(|_| !signer.foreign_device)
614 .map(str::to_owned);
615 if let Some(person) = person
617 && self.people().contains(&person.as_str())
618 {
619 return self;
620 }
621 if self.app.is_none() {
622 self.app.clone_from(&signer.app);
623 }
624 self.acting_for(signer.clone())
625 }
626
627 fn unhand(&mut self) {
630 self.handed = false;
631 for node in &mut self.acted_for {
632 node.unhand();
633 }
634 }
635
636 #[must_use]
638 pub fn caused_by(mut self, cause: impl Into<String>) -> Self {
639 self.cause = Some(ResourceId::new(cause));
640 self
641 }
642
643 #[must_use]
645 pub fn in_session(mut self, session: impl Into<String>) -> Self {
646 self.agent_session = Some(AgentSessionId::new(session));
647 self
648 }
649
650 #[must_use]
653 pub fn delegated(&self) -> bool {
654 self.foreign_device
655 || !self.acted_for.is_empty()
656 || !matches!(self.by, Actor::Member(MemberId::Person(_)))
657 }
658
659 #[must_use]
661 pub fn direct(&self) -> bool {
662 !self.delegated()
663 }
664
665 #[must_use]
667 pub fn direct_person(&self) -> Option<&str> {
668 if !self.direct() {
669 return None;
670 }
671 let Actor::Member(MemberId::Person(person)) = &self.by else {
672 return None;
673 };
674 Some(person.as_str())
675 }
676
677 #[must_use]
679 pub fn app(&self) -> Option<&AppId> {
680 self.app.as_ref()
681 }
682
683 #[must_use]
685 pub fn member_id(&self) -> Option<&MemberId> {
686 self.by.member_id()
687 }
688
689 #[must_use]
690 pub fn is_person(&self) -> bool {
691 self.by.member_id().is_some_and(MemberId::is_person)
692 }
693
694 #[must_use]
695 pub fn is_agent(&self) -> bool {
696 self.by.member_id().is_some_and(MemberId::is_agent)
697 }
698
699 #[must_use]
700 pub fn is_bot(&self) -> bool {
701 self.by.member_id().is_some_and(MemberId::is_bot)
702 }
703
704 #[must_use]
705 pub fn is_automation(&self) -> bool {
706 matches!(self.by, Actor::Automation(_))
707 }
708
709 #[must_use]
710 pub fn person_id(&self) -> Option<&str> {
711 self.by.member_id().and_then(MemberId::person_id)
712 }
713
714 #[must_use]
715 pub fn agent_id(&self) -> Option<&str> {
716 self.by.member_id().and_then(MemberId::agent_id)
717 }
718
719 #[must_use]
720 pub fn bot_id(&self) -> Option<&str> {
721 self.by.member_id().and_then(MemberId::bot_id)
722 }
723
724 #[must_use]
726 pub fn acted_for_person(&self) -> Option<&str> {
727 self.acted_for
728 .first()
729 .and_then(|node| node.by.member_id())
730 .and_then(MemberId::person_id)
731 }
732
733 pub fn members(&self) -> Vec<&MemberId> {
735 let mut members: Vec<&MemberId> = self.by.member_id().into_iter().collect();
736 for node in &self.acted_for {
737 members.extend(node.members());
738 }
739 members
740 }
741
742 pub fn nodes(&self) -> Vec<&Self> {
744 std::iter::once(self)
745 .chain(self.acted_for.iter().flat_map(Self::nodes))
746 .collect()
747 }
748
749 pub fn people(&self) -> Vec<&str> {
751 self.nodes()
752 .into_iter()
753 .filter_map(|node| node.by.member_id().and_then(MemberId::person_id))
754 .collect()
755 }
756}
757
758#[must_use]
762pub fn key_agent_id(device_public_key: &[u8; 32]) -> String {
763 format!("{KEY_AGENT_PREFIX}{}", hex::encode(device_public_key))
764}
765
766#[must_use]
769pub fn key_of_agent(agent: &str) -> Option<[u8; 32]> {
770 let hex = agent.strip_prefix(KEY_AGENT_PREFIX)?;
771 hex::decode(hex).ok()?.try_into().ok()
772}
773
774const KEY_AGENT_PREFIX: &str = "grant-";
776
777#[cfg(test)]
778mod tests {
779 use super::*;
780
781 tilo_test_env::scenario! {
782 fn a_member_tree_names_and_writes_its_members;
783
784 phase a_tree_names_every_member_and_person_in_it;
785 {
786 let acting =
787 Acting::agent("claude", "q").acting_for(Acting::person("q").acting_for(Acting::person("x")));
788 assert!(acting.delegated());
789 assert_eq!(acting.direct_person(), None);
790 assert_eq!(
791 acting.members(),
792 [
793 &MemberId::agent("claude", "q"),
794 &MemberId::person("q"),
795 &MemberId::person("x")
796 ]
797 );
798 assert_eq!(acting.people(), vec!["q", "x"]);
799 let person = Acting::person("q");
800 assert!(person.direct());
801 assert_eq!(person.direct_person(), Some("q"));
802 assert!(Acting::person("q").on_foreign_device(true).delegated());
803 }
804
805 phase an_agent_answering_someone_else_is_bounded_by_its_own_person_too;
806 {
807 let for_bo = Acting::handed_agent("scout", "bo").agent_of("ada");
808 assert_eq!(for_bo.people(), vec!["bo", "ada"], "Bo first, Ada bounding it");
809 assert_eq!(for_bo.acted_for_person(), Some("bo"), "it answers Bo");
810 let for_ada = Acting::handed_agent("scout", "ada").agent_of("ada");
811 assert_eq!(for_ada, Acting::handed_agent("scout", "ada"), "its own person once");
812 }
813
814 phase a_sub_agent_is_one_more_actor_in_its_starters_chain;
815 {
818 let starter = Acting::agent("scout", "ada").acting_for(Acting::person("bo")).agent_of("ada");
819 let helper = starter.clone().handed_on("helper").expect("an agent starts it");
820 assert_eq!(helper.member_id(), Some(&MemberId::agent("helper", "ada")), "Ada's agent's");
821 assert_eq!(helper.acted_for_person(), Some("bo"), "it works for Bo");
822 assert!(helper.handed, "with the preset an agent gets for Bo");
823 assert!(helper.people().contains(&"ada"), "Ada bounds it: {helper:?}");
824 assert!(
825 helper.nodes().iter().any(|node| **node == starter),
826 "its starter's whole tree bounds it: {helper:?}"
827 );
828 let signer = Acting::agent("scout", "ada").acting_for(Acting::person("ada"));
831 let signed = helper.signed_by(&signer);
832 assert!(signed.handed, "{signed:?}");
833 }
834
835 phase a_member_is_read_back_from_the_bytes_a_document_names_it_by;
836 {
837 for member in [
838 MemberId::person(PersonId::from_root([5; 32])),
839 MemberId::agent("helper", PersonId::from_root([5; 32])),
840 MemberId::bot("mod"),
841 ] {
842 assert_eq!(
843 MemberId::of_actor_bytes(&member.actor_bytes()),
844 Some(member)
845 );
846 }
847 assert_eq!(MemberId::of_actor_bytes(b"automation:1"), None);
848 assert_eq!(MemberId::of_actor_bytes(b"agent:"), None);
849 assert_eq!(MemberId::of_actor_bytes(b""), None);
850 }
851
852 phase the_tree_is_written_as_it_is_read;
853 {
854 let acting = Acting::automation("1")
855 .acting_for(
856 Acting::agent("claude", "q")
857 .acting_for(Acting::person("q"))
858 .acting_for(Acting::person("x")),
859 )
860 .caused_by("chat.message:m1");
861 let json = serde_json::to_string(&acting).unwrap();
862 assert_eq!(serde_json::from_str::<Acting>(&json).unwrap(), acting);
863 assert!(json.contains("\"for\""), "{json}");
864 }
865 }
866}