Skip to main content

tilo_actions/remote/
caller.rs

1//! Who sends a request: the acting tree a transport authenticated, and what
2//! it admitted them to.
3
4use tilo_action_policy::Acting;
5
6use super::{ExecutionLease, within};
7
8/// The agent a person's own computer runs under the name `name`: one agent
9/// on every computer of theirs and in every workspace, whichever session it
10/// comes in on. A workspace's record of its agents keeps it under this id
11/// (`agent:<id>`), so its name, colour, permissions and history follow it from
12/// session to session; another name is another agent. The name is compared
13/// without case or surrounding space.
14#[must_use]
15pub fn device_agent_id(person: &[u8; 32], name: &str) -> String {
16    let name = name.trim().to_lowercase();
17    let mut stem: String = name
18        .chars()
19        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
20        .collect();
21    while stem.contains("--") {
22        stem = stem.replace("--", "-");
23    }
24    let stem: String = stem.trim_matches('-').chars().take(40).collect();
25    let stem = if stem.is_empty() {
26        "agent".to_owned()
27    } else {
28        stem
29    };
30    let mut hasher = blake3::Hasher::new();
31    hasher.update(b"tilo device agent\0");
32    hasher.update(person);
33    hasher.update(name.as_bytes());
34    let hash = hasher.finalize();
35    let tag = hex::encode(hash.as_bytes().get(..5).unwrap_or_default());
36    format!("{stem}-{tag}")
37}
38
39/// How a call came to the service that answers it ([`Caller`]).
40#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
41enum Came {
42    /// Over a link.
43    OverALink,
44    /// On the person's plain connection to their own device's daemon.
45    OwnConnection,
46    /// From the device's own code, in process.
47    InProcess,
48    /// From a turn this device's agent engine runs here, as the agent.
49    EngineTurnHere,
50}
51
52/// The authenticated actor behind a request.
53///
54/// Built only by the transport that authenticated the connection — from the
55/// certificate chain a peer presented, or from the admitted identity of a
56/// local connection. It is deliberately not `Deserialize`: a payload cannot
57/// assert who sent it.
58#[derive(Clone, Debug, PartialEq, Eq, Hash)]
59pub struct Caller {
60    pub(super) acting: Acting,
61    pub(super) user_public_key: Option<[u8; 32]>,
62    pub(super) device_public_key: Option<[u8; 32]>,
63    pub(super) workspace: Option<String>,
64    // Transport-issued execution scope, never accepted from request context.
65    // It narrows invocation ownership without changing the acting tree.
66    pub(super) execution: Option<ExecutionLease>,
67    // The person's own device handed this connection to the agent
68    // (`Self::delegated_to`), rather than the agent being admitted as a member
69    // in its own right and acting for them (`Self::acting_for`).
70    pub(super) session_delegated: bool,
71    // How far the invocation this caller's requests continue was admitted
72    // to reach, set by the provider that matched them to it.
73    pub(super) within: within::Within,
74    // The turn an agent acts inside: the person's message in a conversation
75    // that caused it (`Self::agent_turn`). Every op carries it, so the
76    // receiving device checks it against that message and presence can show
77    // what the agent would click.
78    pub(super) turn: Option<tilo_action_policy::turn::Turn>,
79    roster_created_at: Option<i64>,
80    // The roster agent whose approval this caller works under, where that is another agent
81    // than the one acting: a sub-agent its starter started (`Self::working_under`).
82    approved_as: Option<String>,
83    // The person whose message the server's turn answers, as the server read
84    // its cause (`Self::on_roster_turn`).
85    turn_person: Option<[u8; 32]>,
86    // The name an agent goes by, from the key its person certified for it
87    // (`Self::named`): presentation only, what History names it by.
88    pub(super) agent_name: Option<String>,
89    // The key one of the person's own calls came in on (`Self::own_key`), beside the person it
90    // acts as: what listings name the call by. It grants nothing the person does not hold.
91    key: Option<KeyCall>,
92    // What the person asked the agent to do, in a line (`Self::asked`): what
93    // its session is labelled by, where it was asked.
94    pub(super) asked: Option<String>,
95    // The device's operating system (`Self::local_system`), which acts for nobody.
96    system: bool,
97    // How the call came: over a link, on the person's plain connection to their own device's
98    // daemon, which the kernel says is their own account (`Self::own_person`), where their CLI's
99    // own prompt may confirm what the workspace asks them (the call never does), or from the
100    // device's own code in process (`Self::in_process`).
101    came: Came,
102    // The invitation a visitor redeems (`Self::invited`): it acts by its issuer's authority,
103    // which the action checks against the issuer's grant when it runs.
104    invited: Option<Invited>,
105    // The device whose link brought this caller's request, signed by the caller, where it is
106    // another device than the caller's own (`Self::forwarded_by`): a host handing a page action to
107    // the window it placed.
108    forwarded_by: Option<[u8; 32]>,
109    // The grants the transport that admitted this connection holds for it besides its
110    // certificate's: what a device hands an app it started, from its signed manifest.
111    granted: Vec<tilo_action_policy::Grant>,
112    // The app this device's daemon launched and attests this connection's process to be
113    // (`Self::launched`): the one caller that acts as that app itself. No payload, kept caller or
114    // shell link carries it.
115    launched_app: Option<tilo_app_id::AppId>,
116    // The person and records a placed device's certificate names (`Self::placed`): set only by
117    // the transport that read them from the verified certificate.
118    placed: Option<PlacedCaller>,
119    // The step of a Shortcut run whose action the Shortcut's saved rules consent to in advance
120    // (`Self::consented_in_advance`): set only by the runner, in process, never from a frame.
121    consented: bool,
122}
123
124/// The key one of a person's calls came in on, beside the person it acts as
125/// ([`Caller::own_key`]): the member the key is known by everywhere a key is named
126/// ([`tilo_action_policy::key_agent_id`]) and the name the person gave it when they certified it.
127/// Display only: the call is the person's, decided by their grants and narrowed by the key's
128/// certificate, and it is never more.
129#[derive(Clone, Debug, PartialEq, Eq, Hash)]
130pub struct KeyCall {
131    id: String,
132    label: String,
133}
134
135impl KeyCall {
136    /// The member the key is: `grant-` and its device key, hex, as the workspace and History
137    /// name what a key does.
138    #[must_use]
139    pub fn id(&self) -> &str {
140        &self.id
141    }
142
143    /// The name the person gave the key, as the certificate they certified it with says.
144    #[must_use]
145    pub fn label(&self) -> &str {
146        &self.label
147    }
148}
149
150/// What a placed device's certificate says of the caller ([`Caller::placed`]): the person whose
151/// host placed it, whom history names, and the records of its workspace it reaches. The
152/// person is no authority: a placed caller acts as its device's key alone, decided by the
153/// records it reaches.
154#[derive(Clone, Debug, PartialEq, Eq, Hash)]
155pub struct PlacedCaller {
156    person: [u8; 32],
157    channels: Vec<[u8; 32]>,
158}
159
160impl PlacedCaller {
161    /// The root key of the person whose host placed the device: whom history names for
162    /// what it writes. Never whom it acts as.
163    #[must_use]
164    pub const fn person(&self) -> &[u8; 32] {
165        &self.person
166    }
167
168    /// The channel of each record it reaches, in ascending order.
169    #[must_use]
170    pub fn channels(&self) -> &[[u8; 32]] {
171        &self.channels
172    }
173
174    /// Whether the record told by `channel` is one it reaches.
175    #[must_use]
176    pub fn reaches(&self, channel: &[u8; 32]) -> bool {
177        self.channels.binary_search(channel).is_ok()
178    }
179}
180
181/// The authority an invitation carries ([`Caller::invited`]): the signed invitation, and the
182/// device key of whoever issued it, whose grant decides what it admits.
183#[derive(Clone, Debug, PartialEq, Eq, Hash)]
184pub struct Invited {
185    /// The signed invitation, as its issuer handed it over.
186    pub invitation: Vec<u8>,
187    /// The device key that signed it.
188    pub issuer: [u8; 32],
189}
190
191impl Caller {
192    /// `acting`, as the provider admitted it (`keys`: the user and device keys a transport
193    /// verified, if any), with nothing more said of it yet.
194    fn admitted(acting: Acting, keys: Option<([u8; 32], [u8; 32])>) -> Self {
195        Self {
196            acting,
197            user_public_key: keys.map(|(user, _)| user),
198            device_public_key: keys.map(|(_, device)| device),
199            workspace: None,
200            execution: None,
201            session_delegated: false,
202            within: within::Within::NONE,
203            turn: None,
204            roster_created_at: None,
205            approved_as: None,
206            turn_person: None,
207            agent_name: None,
208            key: None,
209            asked: None,
210            system: false,
211            came: Came::OverALink,
212            invited: None,
213            forwarded_by: None,
214            granted: Vec::new(),
215            launched_app: None,
216            placed: None,
217            consented: false,
218        }
219    }
220
221    /// A remote device whose certificate the transport verified to chain to
222    /// `user_public_key`.
223    #[must_use]
224    pub fn authenticated(user_public_key: [u8; 32], device_public_key: [u8; 32]) -> Self {
225        Self::admitted(
226            Acting::person(hex::encode(user_public_key)),
227            Some((user_public_key, device_public_key)),
228        )
229    }
230
231    /// One of the person's own keys, the certificate the transport verified said it is one of
232    /// theirs (`device_label` is the name they gave it): a server key made for their programs,
233    /// whose calls are their own — their grants decide every call, narrowed by the key's
234    /// certificate, and it is never anything more. Beside the person it acts as, the caller
235    /// carries the key ([`KeyCall`]), so a listing says the key's call is the key's.
236    #[must_use]
237    pub fn own_key(user_public_key: [u8; 32], device_public_key: [u8; 32], label: &str) -> Self {
238        let mut caller = Self::authenticated(user_public_key, device_public_key);
239        caller.key = Some(KeyCall {
240            id: tilo_action_policy::key_agent_id(&device_public_key),
241            label: label.trim().to_owned(),
242        });
243        caller
244    }
245
246    /// The key this caller's call came in on ([`Self::own_key`]), where it did: whose name and
247    /// member it is, never a second person's.
248    #[must_use]
249    pub const fn key(&self) -> Option<&KeyCall> {
250        self.key.as_ref()
251    }
252
253    /// A visitor: a key no certificate in the workspace names, known by the key its
254    /// connection proved alone. A page at a workspace's public entry is one, and so is a
255    /// computer being added to a person's devices while it asks to be certified. It acts for
256    /// nobody, so it holds only what the workspace opens to any key
257    /// ([`tilo_action_policy::Grantee::AnyKey`]).
258    #[must_use]
259    pub fn visitor(device_public_key: [u8; 32]) -> Self {
260        let mut caller = Self::admitted(Acting::visitor(&device_public_key), None);
261        caller.device_public_key = Some(device_public_key);
262        caller
263    }
264
265    /// A device placed for records of `workspace`, the `channels` its certificate names, by
266    /// a host for `person`: the transport read them from that verified certificate. It acts as
267    /// its device's key alone, never as the person and never as a member's device: it has no
268    /// person, no user key and nobody it acts for, so nothing that decides by those reaches it,
269    /// and what it may do is decided by the records it reaches ([`Self::placed_records`]).
270    #[must_use]
271    pub fn placed(
272        device_public_key: [u8; 32],
273        person: [u8; 32],
274        workspace: impl Into<String>,
275        channels: impl IntoIterator<Item = [u8; 32]>,
276    ) -> Self {
277        let mut channels: Vec<[u8; 32]> = channels.into_iter().collect();
278        channels.sort_unstable();
279        channels.dedup();
280        let mut caller = Self::visitor(device_public_key).in_workspace(workspace);
281        caller.placed = Some(PlacedCaller { person, channels });
282        caller
283    }
284
285    /// What a placed device's certificate says of this caller ([`Self::placed`]).
286    #[must_use]
287    pub const fn placed_records(&self) -> Option<&PlacedCaller> {
288        self.placed.as_ref()
289    }
290
291    /// A visitor redeeming `invited`: the device `device_public_key` its connection proved,
292    /// acting by the authority of the invitation's issuer and nothing more. The action that
293    /// admits it checks the invitation, and the issuer's grant, when it runs.
294    #[must_use]
295    pub fn invited(device_public_key: [u8; 32], invited: Invited) -> Self {
296        let mut caller = Self::visitor(device_public_key);
297        caller.invited = Some(invited);
298        caller
299    }
300
301    /// The invitation this caller redeems ([`Self::invited`]).
302    #[must_use]
303    pub const fn invitation(&self) -> Option<&Invited> {
304        self.invited.as_ref()
305    }
306
307    /// A person on a connection the provider admitted itself, by the id that
308    /// admission established.
309    #[must_use]
310    pub fn local_person(person: impl Into<tilo_action_policy::PersonId>) -> Self {
311        Self::admitted(Acting::person(person.into()), None)
312    }
313
314    /// The person on a plain connection to their own device's daemon, which the kernel says is
315    /// their own account ([`crate::remote::Caller`]): their calls are their own act, and the
316    /// answer their CLI's own prompt gives on it to what the workspace asks them is their
317    /// confirmation ([`crate::remote::asked`]). Making the call is never that answer.
318    #[must_use]
319    pub fn own_person(person: impl Into<tilo_action_policy::PersonId>) -> Self {
320        Self {
321            came: Came::OwnConnection,
322            ..Self::admitted(Acting::person(person.into()), None)
323        }
324    }
325
326    /// Whether this is the person on their own device's daemon connection
327    /// ([`Self::own_person`]).
328    #[must_use]
329    pub const fn is_own_connection(&self) -> bool {
330        matches!(self.came, Came::OwnConnection)
331    }
332
333    /// The same caller, as the person on their own device's daemon connection.
334    #[must_use]
335    pub const fn on_own_connection(mut self) -> Self {
336        self.came = Came::OwnConnection;
337        self
338    }
339
340    /// The same caller, asked by the device's own code in process rather than over a link:
341    /// only the service that answers it sets this.
342    #[must_use]
343    pub const fn in_process(mut self) -> Self {
344        self.came = Came::InProcess;
345        self
346    }
347
348    /// Whether the device's own code asked this in process ([`Self::in_process`]).
349    #[must_use]
350    pub const fn is_in_process(&self) -> bool {
351        matches!(self.came, Came::InProcess)
352    }
353
354    /// The same caller, calling from a turn this device's agent engine runs here: where the
355    /// call comes from, never what it may do. Its identity stays the agent's, and its calls are
356    /// decided on the agent's grants as any other's. Only the engine that runs the turn sets
357    /// this.
358    #[must_use]
359    pub const fn in_engine_turn_here(mut self) -> Self {
360        self.came = Came::EngineTurnHere;
361        self
362    }
363
364    /// Whether this call comes from a turn this device's agent engine runs here
365    /// ([`Self::in_engine_turn_here`]).
366    #[must_use]
367    pub const fn is_engine_turn_here(&self) -> bool {
368        matches!(self.came, Came::EngineTurnHere)
369    }
370
371    /// The device's operating system on a local connection the provider admitted as its
372    /// superuser: what signs people in at the device and out of it. It acts for nobody, so it
373    /// has nothing in any workspace; only the device's own actions answer it.
374    #[must_use]
375    pub fn local_system() -> Self {
376        Self {
377            system: true,
378            ..Self::admitted(Acting::person(""), None)
379        }
380    }
381
382    /// Whether this is the device's operating system ([`Self::local_system`]).
383    #[must_use]
384    pub const fn is_system(&self) -> bool {
385        self.system
386    }
387
388    /// A delegated agent of `person` on a connection the provider admitted itself, acting for
389    /// them.
390    #[must_use]
391    #[track_caller]
392    pub fn local_agent(
393        agent_id: impl Into<String>,
394        person: impl Into<tilo_action_policy::PersonId>,
395    ) -> Self {
396        let person = person.into();
397        Self::admitted(
398            Acting::agent(agent_id, person.clone()).acting_for(Acting::person(person)),
399            None,
400        )
401    }
402
403    /// An installed bot on a connection the provider admitted itself, by its
404    /// installation: software, never a person, whatever its id spells.
405    #[must_use]
406    pub fn local_bot(installation: impl Into<String>) -> Self {
407        Self::admitted(Acting::bot(installation.into()), None)
408    }
409
410    /// An application on a connection the provider admitted itself, by the
411    /// package id that admission established. It acts as the person whose
412    /// session runs it ([`Self::acting_for`]), in that app; with nobody
413    /// behind it, it acts by itself, with only the grants that name it.
414    #[must_use]
415    pub fn local_app(app_id: impl Into<String>) -> Self {
416        let app: String = app_id.into();
417        Self::admitted(Acting::by_app(app.clone()).in_app(app), None)
418    }
419
420    /// App `app_id`, in the process this device's daemon launched it as and attests to be it
421    /// ([`Self::local_app`]): the one caller that may act as the app itself, with the grants that
422    /// name it. Set only where the daemon attests the process; nothing restored or carried is it.
423    #[must_use]
424    pub fn launched(app_id: impl Into<String>) -> Self {
425        let app: String = app_id.into();
426        Self {
427            launched_app: Some(tilo_app_id::AppId::new(app.clone())),
428            ..Self::local_app(app)
429        }
430    }
431
432    /// The app this device's daemon launched this caller's process as ([`Self::launched`]).
433    #[must_use]
434    pub const fn launched_app(&self) -> Option<&tilo_app_id::AppId> {
435        self.launched_app.as_ref()
436    }
437
438    /// A remote agent device whose certificate the transport verified to
439    /// chain to `user_public_key` and whose root-signed delegation names it
440    /// agent `agent_id`. It is its own member, never the person who
441    /// delegated it.
442    #[must_use]
443    pub fn delegated_agent(
444        agent_id: impl Into<String>,
445        user_public_key: [u8; 32],
446        device_public_key: [u8; 32],
447    ) -> Self {
448        Self::admitted(
449            Acting::agent(agent_id, hex::encode(user_public_key))
450                .acting_for(Acting::person(hex::encode(user_public_key))),
451            Some((user_public_key, device_public_key)),
452        )
453    }
454
455    /// An agent a device handed its session to: `user_public_key`'s root certified the key
456    /// `device_public_key` for `agent_id`, which is the device of `owner`, not the agent's
457    /// person's. The change names the agent acting for its person, and `owner`'s device as the
458    /// one that ran it.
459    #[must_use]
460    pub fn handed_agent(
461        agent_id: impl Into<String>,
462        user_public_key: [u8; 32],
463        device_public_key: [u8; 32],
464        owner: [u8; 32],
465    ) -> Self {
466        Self::admitted(
467            Acting::handed_agent(agent_id.into(), hex::encode(user_public_key))
468                .agent_of(hex::encode(owner)),
469            Some((user_public_key, device_public_key)),
470        )
471    }
472
473    /// The agent `agent_id` of `own` acting inside a turn: `person`'s message in `turn`'s
474    /// conversation caused it, and the agent takes part there. It may do exactly what that person
475    /// may, held to the bound its own record carries, and its reads are decided inside the turn,
476    /// so a conversation's own rules apply to them. Set only by the host that admitted the turn.
477    #[must_use]
478    pub fn agent_turn(
479        (agent_id, own): (impl Into<String>, impl Into<tilo_action_policy::PersonId>),
480        person: impl Into<tilo_action_policy::PersonId>,
481        turn: tilo_action_policy::turn::Turn,
482    ) -> Self {
483        let acting = Acting::agent(agent_id, own).acting_for(Acting::person(person));
484        Self {
485            turn: Some(turn),
486            ..Self::admitted(acting, None)
487        }
488    }
489
490    /// A bot device whose certificate chains to `user_public_key` (its
491    /// installer) and whose root-signed delegation names it installation
492    /// `installation`. It acts for its installer and is never that person.
493    #[must_use]
494    pub fn bot(
495        installation: impl Into<String>,
496        user_public_key: [u8; 32],
497        device_public_key: [u8; 32],
498    ) -> Self {
499        Self::admitted(
500            Acting::bot(installation.into())
501                .acting_for(Acting::person(hex::encode(user_public_key))),
502            Some((user_public_key, device_public_key)),
503        )
504    }
505
506    /// Give an already admitted connection its own execution scope. The provider
507    /// mints the identifier; no payload, display name or history run selects it.
508    /// This changes invocation ownership, never the caller's permissions.
509    #[must_use]
510    pub fn in_new_execution(mut self) -> Self {
511        self.execution = Some(ExecutionLease::mint());
512        self
513    }
514
515    /// Retain a provider-issued execution when projecting the same transport into
516    /// another verified action API. A lease conveys ownership and lifetime,
517    /// never certificate ownership or additional permissions.
518    #[must_use]
519    pub fn in_execution(mut self, execution: ExecutionLease) -> Self {
520        self.execution = Some(execution);
521        self
522    }
523
524    /// Provider-issued execution identity. An identifier alone conveys no authority.
525    #[must_use]
526    pub fn execution_id(&self) -> Option<uuid::Uuid> {
527        self.execution.as_ref().map(|lease| lease.id)
528    }
529
530    #[must_use]
531    pub fn execution_lease(&self) -> Option<ExecutionLease> {
532        self.execution.clone()
533    }
534
535    #[must_use]
536    pub fn execution_is_live(&self) -> bool {
537        self.execution.as_ref().is_some_and(ExecutionLease::is_live)
538    }
539
540    /// Whether this caller may follow, ask again or cancel an invocation `owner` started: it is
541    /// `owner`, or `owner`'s connection ended and this is the same caller on a connection admitted
542    /// after that. A device or key whose connection dropped in the middle of a long import (one does,
543    /// now and then) keeps the invocations it started; a second live connection of the same device still
544    /// borrows none of the first's.
545    #[must_use]
546    pub fn continues(&self, owner: &Self) -> bool {
547        // The name an agent goes by is presentation only ([`Self::named`]): a client that
548        // names its session names the calls it makes, and the caller following them names
549        // nothing, so ownership reads the callers without their names. The name is display
550        // only and grants nothing either way.
551        let (mine, theirs) = (self.unnamed(), owner.unnamed());
552        if mine == theirs {
553            return true;
554        }
555        let replaced = match (&self.execution, &owner.execution) {
556            (Some(own), Some(ended)) => own.replaced(ended),
557            _ => false,
558        };
559
560        replaced && {
561            let mut same = mine;
562            same.execution.clone_from(&owner.execution);
563            same == theirs
564        }
565    }
566
567    /// Whether this caller may follow or cancel an invocation `owner` started: as
568    /// [`Self::continues`], or it is the device that brought `owner`'s call, in the run it brought
569    /// it in, which hands the caller what became of the call as it handed them its first receipt.
570    /// Never whether it may ask the invocation again as its own.
571    #[must_use]
572    pub fn follows(&self, owner: &Self) -> bool {
573        self.continues(owner)
574            || (self.forwarded_by.is_none()
575                && owner
576                    .forwarded_by
577                    .is_some_and(|by| self.device_public_key == Some(by))
578                && self.execution == owner.execution)
579    }
580
581    /// This caller without the name it goes by, which is presentation only
582    /// ([`Self::named`]): what ownership compares.
583    #[must_use]
584    fn unnamed(&self) -> Self {
585        let mut bare = self.clone();
586        bare.agent_name = None;
587        bare
588    }
589
590    /// A transport ends its own run; retained caller clones cannot reopen it.
591    pub fn retire_execution(&self) {
592        if let Some(lease) = &self.execution {
593            lease.close();
594        }
595    }
596
597    /// Mark whether the caller acts from a foreign device: a Tilo runtime on
598    /// an operating system Tilo does not control, as its certificate says.
599    /// Workspaces it does not govern cap such a caller's role.
600    #[must_use]
601    pub fn from_foreign_device(mut self, foreign: bool) -> Self {
602        self.acting = self.acting.on_foreign_device(foreign);
603        self
604    }
605
606    /// The caller acts for `person`: an agent or an app the person started.
607    /// Set only by the provider that admitted the delegation, never from a
608    /// payload. It names who the actor works for in presence and history; it
609    /// widens nothing.
610    #[must_use]
611    pub fn acting_for(mut self, person: impl Into<tilo_action_policy::PersonId>) -> Self {
612        let person = person.into();
613        self.acting = if let Some(app) = self.acting.app.clone() {
614            Acting::person(person).in_app(app)
615        } else {
616            let mut acting = self.acting;
617            acting.acted_for = vec![Acting::person(person)];
618            acting
619        };
620        self
621    }
622
623    /// The caller, acting through the app `app` the provider admitted its connection for: an app
624    /// process acting as its person. Set only by that provider, never from a payload. The one
625    /// reader bounds what such a caller keeps open of a record by what the app declares.
626    #[must_use]
627    pub fn through_app(mut self, app: impl Into<String>) -> Self {
628        self.acting = self.acting.in_app(app.into());
629        self
630    }
631
632    /// This person's own device hands the connection to agent `agent_id`, acting for them: a
633    /// program in the workspace's machine its person let in, which has no key of its own yet.
634    /// The agent is the actor, and it may do only what both the person and the delegation a
635    /// device gives its agents allow. A caller that is not a person is returned as it is.
636    #[must_use]
637    pub fn delegated_to(mut self, agent_id: impl Into<String>) -> Self {
638        let Some(person) = self.acting.person_id().map(str::to_owned) else {
639            return self;
640        };
641        self.session_delegated = true;
642        self.acting = Acting::handed_agent(agent_id, person);
643        self
644    }
645
646    /// Mark this agent caller as one a device handed its session to: the mark
647    /// [`Self::delegated_to`] sets, for a caller whose certificate the transport verified and
648    /// whose admission said a member's own session runs it. Set only by that admission, never
649    /// from a payload; changes nothing for a caller that is not an agent.
650    #[must_use]
651    pub fn session_handed(mut self) -> Self {
652        if self.acting.is_agent() && self.device_public_key.is_some() {
653            self.session_delegated = true;
654            // What it writes says so, as [`Self::delegated_to`]'s does: every device that admits
655            // the write decides it with the delegation the person's device handed it, the one
656            // this device decided it with, never as an agent nobody delegated.
657            self.acting = self.acting.handed();
658        }
659        self
660    }
661
662    /// An agent caller named `name`, as the certificate the transport
663    /// verified for its key says (`device_label`): what History names its
664    /// changes by. Names nothing for a caller that is not an agent.
665    #[must_use]
666    pub fn named(mut self, name: &str) -> Self {
667        let name = name.trim();
668        if self.acting.is_agent() && !name.is_empty() {
669            self.agent_name = Some(name.to_owned());
670        }
671        self
672    }
673
674    /// An agent caller as `message` says the session it works in is called: by that name
675    /// ([`super::InvokeRequest::said_session_name`]), where its client named one, and by the name it
676    /// went by else. One name for everything the agent does here: the window it opens, the
677    /// message it writes, its History rows and the questions it puts to its person. Display
678    /// only, like the session's name itself; it grants nothing and changes no member id.
679    #[must_use]
680    pub fn in_named_session(self, message: &super::RemoteActionMessage) -> Self {
681        let super::RemoteActionMessage::Invoke(request) = message else {
682            return self;
683        };
684        self.in_session_of(request)
685    }
686
687    /// [`Self::in_named_session`] for the call `request`.
688    #[must_use]
689    pub fn in_session_of(self, request: &super::InvokeRequest) -> Self {
690        match request.said_session_name() {
691            Some(session) => self.named(&session),
692            None => self,
693        }
694    }
695
696    /// An agent caller working in the agent session `session`: what its
697    /// changes are grouped and taken back by. Set only by the provider that
698    /// admitted the session; names nothing for a caller that is not an agent.
699    #[must_use]
700    pub fn in_agent_session(mut self, session: impl Into<String>) -> Self {
701        if self.acting.is_agent() {
702            self.acting = self.acting.in_session(session);
703        }
704        self
705    }
706
707    /// An agent caller working on `request`, the words of the person that
708    /// started its session (their message, what they sent it): its first line,
709    /// trimmed and bounded, labels the session ([`Self::agent_session`]). A
710    /// blank request leaves the session labelled by the agent's name.
711    #[must_use]
712    pub fn asked(mut self, request: &str) -> Self {
713        self.asked = crate::context::one_line(request, crate::context::MAX_LABEL_CHARS);
714        self
715    }
716
717    /// What an agent caller is called: its name ([`Self::named`]), else its id.
718    #[must_use]
719    pub fn agent_called(&self) -> Option<&str> {
720        self.agent_name().or_else(|| self.acting.agent_id())
721    }
722
723    /// The name an agent caller goes by ([`Self::named`]).
724    #[must_use]
725    pub fn agent_name(&self) -> Option<&str> {
726        self.agent_name.as_deref()
727    }
728
729    /// Bind a certified agent caller to the hosted roster entry it was
730    /// approved as, answering `person`: the author of the message whose turn
731    /// it answers, as its provider read it. The agent's own key still signs:
732    /// every call is decided for `person`, bounded by the agent and by the
733    /// person it belongs to ([`Acting::agent_of`],
734    /// [`tilo_action_policy::Acting::signed_by`]), so the turn does only what
735    /// both the agent and `person` may, whoever the agent belongs to. The
736    /// workspace service must verify this binding.
737    #[must_use]
738    pub fn on_roster(mut self, created_at: i64, person: [u8; 32]) -> Self {
739        if !self.session_delegated && self.acting.is_agent() && self.device_public_key.is_some() {
740            self.roster_created_at = Some(created_at);
741            self.turn_person = Some(person);
742            self.acting.acted_for = vec![Acting::person(hex::encode(person))];
743            if let Some(owner) = self.user_public_key.map(hex::encode) {
744                self.acting = self.acting.clone().agent_of(owner);
745            }
746        }
747        self
748    }
749
750    /// This agent caller as the agent of `owner`, the person it belongs to, answering whoever
751    /// it acts for ([`Acting::agent_of`]): where that is someone else, `owner` bounds it too.
752    /// Set only by the provider that runs the agent, from the agent's own record. Changes
753    /// nothing for a caller that is not an agent.
754    #[must_use]
755    pub fn agent_of(mut self, owner: impl Into<tilo_action_policy::PersonId>) -> Self {
756        if self.acting.is_agent() {
757            self.acting = self.acting.agent_of(owner);
758        }
759        self
760    }
761
762    /// A caller bound to its roster entry ([`Self::on_roster`]), inside `turn`. Changes nothing
763    /// for a caller that is not so bound.
764    #[must_use]
765    pub fn on_roster_turn(mut self, turn: tilo_action_policy::turn::Turn) -> Self {
766        if self.roster_created_at.is_some() {
767            self.turn = Some(turn);
768        }
769        self
770    }
771
772    /// The agent `agent_id`, named `name`, working under this roster agent's approval: a
773    /// sub-agent its starter started. It acts as itself, so what it writes and says is its
774    /// own, for the same person, as one more actor in its starter's chain
775    /// ([`Acting::handed_on`]): the starter, the person its turn answers and the person the
776    /// starter belongs to all bound it. Every change it makes is signed by the starter's key,
777    /// whose approval bounds that tree too ([`Acting::signed_by`]). It holds no approval of
778    /// its own. Changes nothing for a caller not bound to its roster entry
779    /// ([`Self::on_roster`]).
780    #[must_use]
781    pub fn working_under(mut self, agent_id: impl Into<String>, name: &str) -> Self {
782        let Some(approved) = self.approved_agent().map(str::to_owned) else {
783            return self;
784        };
785        if self.acting.acted_for_person().is_none() {
786            return self;
787        }
788        let Some(acting) = self.acting.clone().handed_on(agent_id) else {
789            return self;
790        };
791        self.acting = acting;
792        self.approved_as = Some(approved);
793        self.agent_name = None;
794        self.named(name)
795    }
796
797    /// The roster agent whose approval a caller bound to its roster entry acts under
798    /// ([`Self::on_roster`]): the acting agent itself, or the starter of a sub-agent
799    /// ([`Self::working_under`]). `None` for any other caller.
800    #[must_use]
801    pub fn approved_agent(&self) -> Option<&str> {
802        self.roster_created_at?;
803        self.approved_as
804            .as_deref()
805            .or_else(|| self.acting.agent_id())
806    }
807
808    /// The person a roster agent works for ([`Self::on_roster`]).
809    #[must_use]
810    pub const fn turn_person(&self) -> Option<&[u8; 32]> {
811        self.turn_person.as_ref()
812    }
813
814    /// The creation time of the roster entry the provider bound this turn to.
815    #[must_use]
816    pub const fn roster_created_at(&self) -> Option<i64> {
817        self.roster_created_at
818    }
819
820    /// Whether this is an agent a person's own device runs with a key of its own, outside a
821    /// roster turn: an MCP client, a local assistant. Its key's certificate names its person
822    /// ([`Self::user_public_key`]) and every invocation it makes is signed by that key, so this
823    /// reads nothing a payload says.
824    #[must_use]
825    pub fn is_device_agent(&self) -> bool {
826        self.acting.is_agent()
827            && self.device_public_key.is_some()
828            && self.roster_created_at.is_none()
829            && self.acting.acted_for_person().is_some()
830    }
831
832    /// Whether this agent is one the person's own device handed its session to
833    /// ([`Self::delegated_to`]): it carries the delegation a device gives its
834    /// agents. An agent admitted as a member that acts for a person
835    /// ([`Self::acting_for`]) carries only what the workspace grants it.
836    #[must_use]
837    pub fn is_session_delegated(&self) -> bool {
838        self.session_delegated
839    }
840
841    /// The turn this agent acts inside ([`Self::agent_turn`]), when it was
842    /// admitted as one: the message whose conversation caused its ops, which
843    /// every API it reaches decides it against.
844    #[must_use]
845    pub fn turn(&self) -> Option<&tilo_action_policy::turn::Turn> {
846        self.turn.as_ref()
847    }
848
849    /// The person this caller acts for, when it is not that person.
850    #[must_use]
851    pub fn acting_for_person(&self) -> Option<&str> {
852        self.acting.acted_for_person().or_else(|| {
853            self.acting
854                .app()
855                .and_then(|_| self.acting.person_id())
856                .filter(|person| !person.is_empty())
857        })
858    }
859
860    /// The caller's invocations are the steps of Shortcut `id`'s run: still
861    /// the person's authority (bounded by the Shortcut's own grants, which
862    /// the runner applies), but the Shortcut is who acts, for the person.
863    /// Set only by the provider's Shortcut runner.
864    #[must_use]
865    pub fn running_shortcut(mut self, id: impl Into<String>) -> Self {
866        let person = self
867            .acting
868            .person_id()
869            .or_else(|| self.acting.acted_for_person())
870            .unwrap_or_default()
871            .to_owned();
872        let mut acting = Acting::automation(id).acting_for(Acting::person(person));
873        acting.app.clone_from(&self.acting.app);
874        acting.foreign_device = self.acting.foreign_device;
875        self.acting = acting;
876        self
877    }
878
879    /// The step of a Shortcut run ([`Self::running_shortcut`]) whose action the rules the person
880    /// saved with the Shortcut consent to in advance: the yes they gave when they saved it, which
881    /// answers this step's ask. Set only by the runner, after it checked those rules name this
882    /// very action; a caller that runs no Shortcut is left as it was.
883    #[must_use]
884    pub fn consented_in_advance(mut self) -> Self {
885        self.consented = matches!(self.acting.by, tilo_action_policy::Actor::Automation(_));
886        self
887    }
888
889    /// Whether the person's saved Shortcut consents to this step in advance
890    /// ([`Self::consented_in_advance`]).
891    #[must_use]
892    pub const fn is_consented_in_advance(&self) -> bool {
893        self.consented
894    }
895
896    /// Who an action this caller invokes is decided for, as the transport
897    /// admitted it ([`tilo_action_policy::Acting`]).
898    #[must_use]
899    pub const fn acting(&self) -> &Acting {
900        &self.acting
901    }
902
903    /// The grants this caller's certificate names for the agent it is in `workspace`
904    /// ([`tilo_action_policy::roles::certified_agent`]): its person's default delegation, which
905    /// the workspace's own grants naming the agent then narrow. Nothing for a caller no
906    /// certificate names as an agent: it holds only what the workspace grants it.
907    ///
908    /// The certificate delegates to an agent a device **handed** its session
909    /// ([`Self::delegated_to`]) or a workspace's **roster** bound ([`Self::on_roster`]): a caller
910    /// that only says it is an agent acting for a person, on that person's key, is named by no
911    /// session and no roster, and is offered nothing.
912    #[must_use]
913    pub fn certified(&self, workspace: &str) -> Vec<tilo_action_policy::Grant> {
914        let (Some((agent, own)), Some(person)) = (
915            self.acting
916                .member_id()
917                .and_then(tilo_action_policy::MemberId::as_agent),
918            self.acting.acted_for_person(),
919        ) else {
920            return Vec::new();
921        };
922        if self.device_public_key.is_none()
923            || (self.roster_created_at.is_none() && !self.session_delegated)
924        {
925            return Vec::new();
926        }
927        tilo_action_policy::roles::certified_agent(workspace, (agent, own.as_str()), person)
928    }
929
930    /// The grants made for this caller's software: its certificate's ([`Self::certified`]),
931    /// the one place an agent's rights become grants, so every host and every receiver decides
932    /// an agent alike. Asked in no workspace (its person's list of them), the certificate gives
933    /// the delegation at the root.
934    #[must_use]
935    pub fn granted(&self) -> Vec<tilo_action_policy::Grant> {
936        let mut held = self.granted.clone();
937        held.extend(self.certified(self.workspace.as_deref().unwrap_or_default()));
938        held
939    }
940
941    /// This caller with `grants` too, which the transport that admitted it holds for it: what a
942    /// device hands an app it started, from its signed manifest. Never accepted from a request.
943    #[must_use]
944    pub fn granting(mut self, grants: Vec<tilo_action_policy::Grant>) -> Self {
945        self.granted.extend(grants);
946        self
947    }
948
949    /// The group a session named `id` is, as this caller's provider admitted
950    /// it: called by what the session was asked ([`Self::asked`]), else by the
951    /// name the provider knows the agent by ([`Self::named`]). History groups
952    /// its changes, Activity lists it and undo takes it back whole.
953    #[must_use]
954    pub fn session_group(&self, id: impl Into<String>) -> crate::WorkGroup {
955        crate::WorkGroup {
956            id: id.into(),
957            label: self
958                .asked
959                .clone()
960                .or_else(|| self.agent_name().map(str::to_owned)),
961            kind: crate::context::AGENT_SESSION_GROUP.to_owned(),
962            declared_id: None,
963            session: None,
964        }
965    }
966
967    /// The session this caller's actions are part of, as the provider that
968    /// admitted it says: an agent (or a key it holds) in an execution the
969    /// provider minted for its connection works in one session
970    /// ([`Self::session_group`]), whatever the client says of itself. `None`
971    /// for anyone else.
972    #[must_use]
973    pub fn agent_session(&self) -> Option<crate::WorkGroup> {
974        self.acting.agent_id()?;
975        let id = match &self.acting.agent_session {
976            Some(session) => session.as_str().to_owned(),
977            None => format!(
978                "{}:{}",
979                crate::context::AGENT_SESSION_GROUP,
980                self.execution_id()?
981            ),
982        };
983        Some(self.session_group(id))
984    }
985
986    /// The request reached here over the link of `device`, which forwarded it for this caller,
987    /// who signed it. Set only by the transport that verified both, never from a payload.
988    #[must_use]
989    pub const fn forwarded_by(mut self, device: [u8; 32]) -> Self {
990        self.forwarded_by = Some(device);
991        self
992    }
993
994    /// The device whose link brought this caller's request, when another device than its own
995    /// did ([`Self::forwarded_by`]).
996    #[must_use]
997    pub const fn forwarder(&self) -> Option<&[u8; 32]> {
998        self.forwarded_by.as_ref()
999    }
1000
1001    /// Confine the caller to one workspace: the connection was admitted to that
1002    /// workspace only, so nothing outside it is offered or reachable.
1003    #[must_use]
1004    pub fn in_workspace(mut self, workspace: impl Into<String>) -> Self {
1005        self.workspace = Some(workspace.into());
1006        self
1007    }
1008
1009    /// The workspace this caller is confined to, if any.
1010    #[must_use]
1011    pub fn workspace(&self) -> Option<&str> {
1012        self.workspace.as_deref()
1013    }
1014
1015    /// The user root a remote device chains to.
1016    #[must_use]
1017    pub const fn user_public_key(&self) -> Option<&[u8; 32]> {
1018        self.user_public_key.as_ref()
1019    }
1020
1021    #[must_use]
1022    pub const fn is_foreign_device(&self) -> bool {
1023        self.acting.foreign_device
1024    }
1025
1026    /// The remote device that sent the request.
1027    #[must_use]
1028    pub const fn device_public_key(&self) -> Option<&[u8; 32]> {
1029        self.device_public_key.as_ref()
1030    }
1031
1032    /// This caller as the host keeps it beside a call that waits for its person's yes, to admit
1033    /// the call again for it after a restart ([`KeptCaller`]). The execution it ran in is not
1034    /// kept: it ended with the process.
1035    #[must_use]
1036    pub fn kept(&self) -> KeptCaller {
1037        // A placed caller is kept as the key it is and nothing more: restored, it is a visitor,
1038        // never its person.
1039        if self.placed.is_some() {
1040            return KeptCaller {
1041                acting: Acting::visitor(&self.device_public_key.unwrap_or_default()),
1042                user_public_key: None,
1043                device_public_key: self.device_public_key,
1044                workspace: self.workspace.clone(),
1045                session_delegated: false,
1046                within: None,
1047                turn: None,
1048                roster_created_at: None,
1049                approved_as: None,
1050                turn_person: None,
1051                agent_name: None,
1052                asked: None,
1053                system: false,
1054            };
1055        }
1056        KeptCaller {
1057            acting: self.acting.clone(),
1058            user_public_key: self.user_public_key,
1059            device_public_key: self.device_public_key,
1060            workspace: self.workspace.clone(),
1061            session_delegated: self.session_delegated,
1062            within: self.ceiling().map(|reach| (reach.kind, reach.privileged)),
1063            turn: self.turn.clone(),
1064            roster_created_at: self.roster_created_at,
1065            approved_as: self.approved_as.clone(),
1066            turn_person: self.turn_person,
1067            agent_name: self.agent_name.clone(),
1068            asked: self.asked.clone(),
1069            system: self.system,
1070        }
1071    }
1072}
1073
1074/// A [`Caller`] as a host keeps it in its own state, beside a call that waits for its
1075/// person's yes: everything the transport admitted of it but the execution it ran in. A caller
1076/// is made of it again only for the call it was kept with ([`KeptCaller::restored`]), or by the
1077/// person's shell for a call its own device's daemon hands it on the link the daemon made for it
1078/// ([`KeptCaller::carried`]), so a payload from anyone else still cannot say who sent it.
1079#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1080#[serde(deny_unknown_fields)]
1081pub struct KeptCaller {
1082    acting: Acting,
1083    user_public_key: Option<[u8; 32]>,
1084    device_public_key: Option<[u8; 32]>,
1085    workspace: Option<String>,
1086    session_delegated: bool,
1087    within: Option<(tilo_action_policy::ActionKind, bool)>,
1088    turn: Option<tilo_action_policy::turn::Turn>,
1089    roster_created_at: Option<i64>,
1090    approved_as: Option<String>,
1091    turn_person: Option<[u8; 32]>,
1092    agent_name: Option<String>,
1093    asked: Option<String>,
1094    system: bool,
1095}
1096
1097impl KeptCaller {
1098    /// The caller the device's daemon admitted a call of a provider the shell serves for, as the
1099    /// daemon says it on the shell's link: the one place a shell reads who called it.
1100    #[must_use]
1101    pub fn carried(self) -> Caller {
1102        self.restored()
1103    }
1104
1105    /// The caller this was kept from, with no execution of its own.
1106    #[must_use]
1107    pub fn restored(self) -> Caller {
1108        Caller {
1109            acting: self.acting,
1110            user_public_key: self.user_public_key,
1111            device_public_key: self.device_public_key,
1112            workspace: self.workspace,
1113            execution: None,
1114            session_delegated: self.session_delegated,
1115            within: within::Within::of(
1116                self.within
1117                    .map(|(kind, privileged)| tilo_action_policy::Reach { kind, privileged }),
1118            ),
1119            turn: self.turn,
1120            roster_created_at: self.roster_created_at,
1121            approved_as: self.approved_as,
1122            turn_person: self.turn_person,
1123            agent_name: self.agent_name,
1124            // The key a call came in on is not kept: a kept caller is admitted again for the
1125            // call it waits with, by the person's authority, and the ask it waits in names the
1126            // key it came on ([`super::asked::AskedFacts::by`]).
1127            key: None,
1128            asked: self.asked,
1129            system: self.system,
1130            // A kept call is admitted again for what it was made for, never as a live
1131            // connection's own act.
1132            came: Came::OverALink,
1133            // A redemption never waits for a person's yes, so no kept call carries one.
1134            invited: None,
1135            forwarded_by: None,
1136            granted: Vec::new(),
1137            // Only the daemon's own attestation of the process it launched makes a caller the
1138            // app itself; a kept or carried caller is never that.
1139            launched_app: None,
1140            placed: None,
1141            // A kept call is asked again for what it was made for.
1142            consented: false,
1143        }
1144    }
1145}
1146
1147#[cfg(test)]
1148mod tests {
1149    use super::{Caller, device_agent_id};
1150    use crate::context::{AGENT_SESSION_GROUP, ActionContext, WorkGroup};
1151    use crate::remote::{ActionAddress, InvokeArgument, InvokeRequest, RemoteActionTarget};
1152
1153    /// A call made in the session `session` names, in a work group of `kind`.
1154    fn call_in(kind: &str, session: Option<&str>) -> InvokeRequest {
1155        InvokeRequest {
1156            invocation: crate::InvocationId::new(),
1157            target: RemoteActionTarget {
1158                provider: "chat".into(),
1159                address: ActionAddress::new("chat.messages", "post"),
1160            },
1161            argument: InvokeArgument::Text(String::new()),
1162            context: Some(ActionContext {
1163                group: Some(WorkGroup {
1164                    id: "visit-1".into(),
1165                    label: None,
1166                    kind: kind.into(),
1167                    declared_id: None,
1168                    session: session.map(str::to_owned),
1169                }),
1170                ..ActionContext::default()
1171            }),
1172            confirmation: None,
1173            revision: None,
1174            on_behalf_of: None,
1175            wait_ms: None,
1176            appearance: None,
1177            signed: None,
1178        }
1179    }
1180
1181    /// Ada's approved agent answers Bo: it acts for Bo, bounded by Ada. A sub-agent it starts
1182    /// on that turn works for Bo under Ada's agent's approval, and records the whole chain, so
1183    /// whatever decides its changes is bounded by Ada's agent and Ada as well.
1184    #[test]
1185    fn a_sub_agent_on_another_members_turn_carries_its_starters_whole_chain() {
1186        let (ada, bo) = ([1; 32], [2; 32]);
1187        let (ada_id, bo_id) = (hex::encode(ada), hex::encode(bo));
1188        let scout = Caller::delegated_agent("scout", ada, [3; 32]).on_roster(7, bo);
1189        assert_eq!(scout.acting().acted_for_person(), Some(bo_id.as_str()));
1190        assert_eq!(
1191            scout.acting().people(),
1192            vec![bo_id.as_str(), ada_id.as_str()]
1193        );
1194        assert_eq!(scout.turn_person(), Some(&bo));
1195
1196        let helper = scout.clone().working_under("helper", "Helper");
1197        let acting = helper.acting();
1198        assert_eq!(acting.agent_id(), Some("helper"));
1199        assert_eq!(
1200            acting.acted_for_person(),
1201            Some(bo_id.as_str()),
1202            "it works for Bo"
1203        );
1204        assert!(acting.people().contains(&ada_id.as_str()), "{acting:?}");
1205        assert!(
1206            acting.nodes().iter().any(|node| *node == scout.acting()),
1207            "its starter's whole tree: {acting:?}"
1208        );
1209        assert_eq!(helper.approved_agent(), Some("scout"));
1210
1211        // Ada's own turn records her once.
1212        let hers = Caller::delegated_agent("scout", ada, [3; 32]).on_roster(7, ada);
1213        assert_eq!(hers.acting().people(), vec![ada_id.as_str()]);
1214    }
1215
1216    /// An agent's certificate gives it its person's default delegation in the workspace, which
1217    /// the workspace's own grants naming it then narrow. The certificate reaches an agent a
1218    /// device handed its session to or a roster bound: a caller that only says it is an agent
1219    /// for a person is named by neither and holds nothing, and neither does a person.
1220    #[test]
1221    fn an_agents_certificate_gives_it_its_default_delegation() {
1222        use tilo_action_policy::Grantee;
1223        let (ada, device) = ([1; 32], [3; 32]);
1224        let person = hex::encode(ada);
1225        let expected = tilo_action_policy::roles::certified_agent("w", ("scout", &person), &person);
1226        assert!(!expected.is_empty());
1227        // An agent its workspace's roster bound carries the certificate's delegation.
1228        let bound = Caller::delegated_agent("scout", ada, device)
1229            .in_workspace("w")
1230            .on_roster(7, ada);
1231        assert_eq!(bound.certified("w"), expected, "the certificate's own");
1232        assert_eq!(bound.granted(), expected, "nothing else narrows it");
1233        assert!(
1234            expected
1235                .iter()
1236                .all(|grant| grant.grantee == Grantee::agent("scout", person.as_str()))
1237        );
1238        assert!(
1239            expected
1240                .iter()
1241                .all(|grant| grant.granted_by == Grantee::person(person.clone()))
1242        );
1243        // A handed agent of the person's own device carries the same delegation, and so does a
1244        // listed agent a member's own session admitted.
1245        let handed = Caller::authenticated(ada, [4; 32])
1246            .delegated_to("scout")
1247            .in_workspace("w");
1248        assert_eq!(handed.certified("w"), expected);
1249        let joined = Caller::delegated_agent("scout", ada, device)
1250            .session_handed()
1251            .in_workspace("w");
1252        assert_eq!(joined.certified("w"), expected);
1253        // What either writes names that delegation, so every device admitting the write decides
1254        // it as this one did.
1255        let preset = handed.acting().handed_preset("w");
1256        assert!(!preset.is_empty());
1257        assert_eq!(joined.acting().handed_preset("w"), preset);
1258        // An agent that only says it is one for a person is named by no session and no roster.
1259        let bare = Caller::delegated_agent("scout", ada, device).in_workspace("w");
1260        assert!(bare.acting().handed_preset("w").is_empty());
1261        assert!(
1262            bare.certified("w").is_empty(),
1263            "no session and no roster: {:?}",
1264            bare.certified("w")
1265        );
1266        // A person, and an agent no certificate names, hold nothing of their own.
1267        assert!(Caller::local_person("ada").certified("w").is_empty());
1268        assert!(
1269            Caller::local_agent("scout", "ada")
1270                .certified("w")
1271                .is_empty()
1272        );
1273    }
1274
1275    /// An agent goes by the name of the session its client named for the call, and by its own
1276    /// name where none was named; a person is named by no session.
1277    #[test]
1278    fn an_agent_goes_by_its_sessions_name() {
1279        let claude = || Caller::local_agent("claude-code", "ada").named("Claude Code");
1280        let named = |caller: Caller, request| {
1281            caller
1282                .in_session_of(&request)
1283                .agent_called()
1284                .map(str::to_owned)
1285        };
1286        assert_eq!(
1287            named(claude(), call_in(AGENT_SESSION_GROUP, Some("Release prep"))).as_deref(),
1288            Some("Release prep")
1289        );
1290        assert_eq!(
1291            named(claude(), call_in(AGENT_SESSION_GROUP, Some("   "))).as_deref(),
1292            Some("Claude Code")
1293        );
1294        assert_eq!(
1295            named(claude(), call_in("issue", Some("Release prep"))).as_deref(),
1296            Some("Claude Code")
1297        );
1298        let ada = Caller::local_person("ada")
1299            .in_session_of(&call_in(AGENT_SESSION_GROUP, Some("Release prep")));
1300        assert_eq!(ada.agent_called(), None);
1301    }
1302
1303    /// A call that names its session names the caller, and the connection following the
1304    /// invocation it started names nothing of it: what an agent is called is presentation
1305    /// only, so both continue the same invocations. Another session borrows none of them.
1306    #[test]
1307    fn an_agents_session_name_does_not_change_who_continues_its_invocations() {
1308        let caller = || Caller::local_agent("claude-code", "ada").named("Claude Code");
1309        let named = caller().in_session_of(&call_in(AGENT_SESSION_GROUP, Some("Release prep")));
1310        assert_eq!(named.agent_called(), Some("Release prep"));
1311        assert!(
1312            caller().continues(&named),
1313            "the connection follows what it started"
1314        );
1315        assert!(named.continues(&caller()));
1316        let another = Caller::local_agent("claude-code", "ada")
1317            .in_new_execution()
1318            .named("Claude Code");
1319        assert!(
1320            !another.continues(&named),
1321            "another live connection of the same agent borrows nothing"
1322        );
1323    }
1324
1325    /// An agent session names itself by what it was asked, and by the agent's name where it was
1326    /// asked nothing.
1327    #[test]
1328    fn an_agent_sessions_label_is_what_it_was_asked_else_the_agents_name() {
1329        let session = Caller::local_agent("claude-code", "ada")
1330            .in_new_execution()
1331            .named("Claude Code")
1332            .in_agent_session("visit-1");
1333        let label = |caller: &Caller| caller.agent_session().and_then(|session| session.label);
1334        assert_eq!(label(&session).as_deref(), Some("Claude Code"));
1335        let asked = session.asked("Fill Jane's application");
1336        assert_eq!(label(&asked).as_deref(), Some("Fill Jane's application"));
1337    }
1338
1339    /// A placed device's caller is its key and nothing more: no person it acts as, no user key,
1340    /// nobody it acts for, and nothing whose decisions read the person reaches it. Its person is
1341    /// only named, for history. Kept and restored, it is a plain visitor.
1342    #[test]
1343    fn a_placed_device_is_never_its_person() {
1344        let (device, person) = ([7; 32], [1; 32]);
1345        let placed = Caller::placed(device, person, "w", [[3; 32], [2; 32], [3; 32]]);
1346        assert_eq!(placed.user_public_key(), None);
1347        assert_eq!(placed.acting().person_id(), None);
1348        assert_eq!(placed.acting_for_person(), None);
1349        assert_eq!(placed.acting().visitor_key(), Some(device));
1350        assert_eq!(placed.device_public_key(), Some(&device));
1351        assert_eq!(placed.workspace(), Some("w"));
1352        assert!(!placed.is_system());
1353        assert_eq!(placed.approved_agent(), None);
1354        assert_eq!(placed.turn_person(), None);
1355        let records = placed
1356            .placed_records()
1357            .expect("the placed records are said");
1358        assert_eq!(records.person(), &person);
1359        assert_eq!(records.channels(), &[[2; 32], [3; 32]]);
1360        assert!(records.reaches(&[2; 32]) && records.reaches(&[3; 32]));
1361        assert!(!records.reaches(&[4; 32]));
1362        assert_ne!(
1363            placed,
1364            Caller::authenticated(person, device).in_workspace("w")
1365        );
1366        let restored = placed.kept().restored();
1367        assert_eq!(restored.placed_records(), None);
1368        assert_eq!(restored.user_public_key(), None);
1369        assert_eq!(restored.acting().person_id(), None);
1370        assert_eq!(restored.acting().visitor_key(), Some(device));
1371    }
1372
1373    /// One person's agent under one name is one agent, however the name is typed; another name
1374    /// or another person's agent is another.
1375    #[test]
1376    fn a_persons_agent_is_one_agent_by_its_name() {
1377        let ada = [1; 32];
1378        let claude = device_agent_id(&ada, "Claude Code");
1379        assert!(claude.starts_with("claude-code-"), "{claude}");
1380        assert_eq!(claude, device_agent_id(&ada, "  claude code "));
1381        assert_ne!(claude, device_agent_id(&ada, "Reviewer"));
1382        assert_ne!(claude, device_agent_id(&[2; 32], "Claude Code"));
1383        assert!(device_agent_id(&ada, "…").starts_with("agent-"));
1384    }
1385
1386    /// The person's own connection is made only where the daemon admits them from its own
1387    /// socket: no kept call and no frame carries it. A call admitted again from its asked record
1388    /// asks as any other, and a frame that names the flag is refused rather than read.
1389    #[test]
1390    fn a_kept_caller_is_never_the_persons_own_connection() {
1391        let person = "a".repeat(64);
1392        let own = Caller::own_person(person);
1393        assert!(own.is_own_connection());
1394        let kept = own.kept();
1395        assert!(!kept.clone().restored().is_own_connection());
1396        assert!(!kept.clone().carried().is_own_connection());
1397        let carried = serde_json::to_value(&kept).expect("a kept caller is written");
1398        assert!(
1399            carried.get("own_connection").is_none(),
1400            "nothing kept says it: {carried}"
1401        );
1402        let mut named = carried;
1403        named["own_connection"] = serde_json::json!(true);
1404        assert!(
1405            serde_json::from_value::<super::KeptCaller>(named).is_err(),
1406            "a frame that names the flag is refused"
1407        );
1408    }
1409}