Skip to main content

gent_protocol/
lib.rs

1//! Portable identities, local RPC types, and endpoint permission semantics.
2use serde::{Deserialize, Serialize};
3use std::collections::BTreeMap;
4pub mod administration;
5pub mod babysitter;
6pub mod configuration_log;
7pub mod dashboard;
8pub mod directory;
9pub mod file_objects;
10pub mod history;
11pub mod hosted_mcp;
12pub mod notifications;
13pub mod owner_transfer;
14pub mod permissions;
15mod release_channel;
16pub mod service;
17pub mod transport_batch;
18pub mod transport_exchange;
19pub mod transport_sweep;
20pub mod transport_watch;
21pub mod transport_wss;
22pub mod wake;
23pub mod web_failover;
24pub mod work;
25pub use release_channel::ReleaseChannel;
26
27pub const MAX_TEXT_BYTES: usize = 64 * 1024;
28pub const MAX_FILE_BYTES: usize = 1024 * 1024;
29pub const MAX_FRAME_BYTES: usize = 6 * 1024 * 1024;
30pub const MAX_EXCHANGE_MESSAGES: u32 = 32;
31pub const EXCHANGE_TTL_SECONDS: i64 = 24 * 60 * 60;
32pub const MAX_RELAY_GRANT_LIFETIME: u64 = 7 * 24 * 60 * 60;
33pub const MAX_REGISTRATION_GENERATION: u64 = (1 << 53) - 1;
34
35#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
36pub struct Agent {
37    pub id: String,
38    pub node_id: String,
39    pub name: String,
40    pub provider: String,
41    pub last_seen: i64,
42    pub revoked: bool,
43}
44
45#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
46#[serde(
47    tag = "kind",
48    content = "id",
49    rename_all = "snake_case",
50    deny_unknown_fields
51)]
52pub enum Selector {
53    All,
54    #[serde(alias = "chat")]
55    Agent(String),
56    Node(String),
57    SameNode,
58    Group(String),
59}
60
61#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
62#[serde(rename_all = "snake_case")]
63pub enum Permission {
64    Enumerate,
65    Receive,
66    Send,
67}
68
69#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
70#[serde(rename_all = "snake_case")]
71pub enum Effect {
72    Allow,
73    Deny,
74}
75
76#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
77#[serde(deny_unknown_fields)]
78pub struct Rule {
79    pub actor: Selector,
80    pub peer: Selector,
81    pub permission: Permission,
82    pub effect: Effect,
83}
84
85#[derive(Clone, Debug, Default, Serialize, Deserialize)]
86#[serde(deny_unknown_fields)]
87pub struct Policy {
88    #[serde(default)]
89    pub rules: Vec<Rule>,
90    /// Signed membership, changed by the owner or a separately delegated chat.
91    #[serde(default)]
92    pub groups: BTreeMap<String, Vec<String>>,
93    /// Legacy relay authorizations, retained to verify existing signed state.
94    /// New relay selections use ordinary messaging permissions alone.
95    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
96    pub relay_grants: BTreeMap<String, RelayGrant>,
97    /// Editing authority is separate from message permissions. Empty maps keep
98    /// previously signed policy bytes unchanged.
99    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
100    pub admin_grants: BTreeMap<String, administration::AdminGrant>,
101    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
102    pub group_admin_grants: BTreeMap<String, administration::GroupAdminGrant>,
103}
104
105#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
106#[serde(deny_unknown_fields)]
107pub struct RelayGrant {
108    pub intermediary: String,
109    pub target: String,
110    pub issued_at: u64,
111    pub expires_at: u64,
112}
113
114#[derive(Clone, Debug, Serialize, Deserialize)]
115#[serde(deny_unknown_fields)]
116pub struct RelayAttachment {
117    pub id: String,
118    pub intermediary: String,
119    pub target: String,
120    /// Present only on selections created by older daemons.
121    #[serde(default, skip_serializing_if = "Option::is_none")]
122    pub grant_id: Option<String>,
123    pub security_mode: RelaySecurityMode,
124    pub created_at: u64,
125    /// New selections last until detached; legacy selections retain their expiry.
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub expires_at: Option<u64>,
128    pub detached: bool,
129}
130
131#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
132#[serde(rename_all = "snake_case")]
133pub enum RelaySecurityMode {
134    LocalDaemon,
135    EncryptedDaemonLink,
136}
137
138/// Authenticated relay context inside the encrypted message, never inferred
139/// from text. Relay access follows messaging policy, not asserted human authorship.
140#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
141#[serde(deny_unknown_fields)]
142pub struct RelayMessage {
143    pub attachment_id: String,
144    /// Retained on legacy turns so their original restrictions and retries survive.
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    pub grant_id: Option<String>,
147    pub turn_id: String,
148    pub kind: RelayMessageKind,
149}
150
151#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
152#[serde(rename_all = "snake_case")]
153pub enum RelayMessageKind {
154    Request,
155    Progress,
156    Complete,
157    Cancel,
158    Cancelled,
159}
160
161#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
162#[serde(rename_all = "snake_case")]
163pub enum RelayResponseKind {
164    Progress,
165    Complete,
166    Cancelled,
167}
168
169impl Policy {
170    fn matches(&self, selector: &Selector, subject: &Agent, other: &Agent) -> bool {
171        match selector {
172            Selector::All => true,
173            Selector::Agent(id) => subject.id == *id,
174            Selector::Node(id) => subject.node_id == *id,
175            Selector::SameNode => subject.node_id == other.node_id,
176            Selector::Group(id) => self
177                .groups
178                .get(id)
179                .is_some_and(|ids| ids.contains(&subject.id)),
180        }
181    }
182
183    /// None means default denial; it is distinct from an explicit denial for reply grants.
184    pub fn decision(&self, actor: &Agent, peer: &Agent, permission: Permission) -> Option<Effect> {
185        if actor.revoked || peer.revoked {
186            return Some(Effect::Deny);
187        }
188        let mut decision = None;
189        for (_, rule) in self.matching_rules(actor, peer, permission) {
190            if rule.effect == Effect::Deny {
191                return Some(Effect::Deny);
192            }
193            decision = Some(Effect::Allow);
194        }
195        decision
196    }
197
198    pub fn visible(&self, actor: &Agent, peer: &Agent) -> bool {
199        self.decision(actor, peer, Permission::Enumerate) == Some(Effect::Allow)
200    }
201
202    pub fn can_open(&self, sender: &Agent, recipient: &Agent) -> bool {
203        self.open_checks(sender, recipient)
204            .all(|(_, allowed)| allowed)
205    }
206
207    /// Call only after verifying an accepted, unexpired exchange and its participants.
208    pub fn can_reply(&self, sender: &Agent, recipient: &Agent) -> bool {
209        self.reply_checks(sender, recipient)
210            .all(|(_, allowed)| allowed)
211    }
212}
213
214#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
215#[serde(deny_unknown_fields)]
216pub struct FilePart {
217    pub name: String,
218    pub media_type: String,
219    pub data_base64: String,
220}
221
222/// Chat-visible attachment metadata. Decryption keys are a separate private
223/// wire type and must never be serialized into a chat RPC or MCP response.
224#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
225#[serde(deny_unknown_fields)]
226pub struct FileDescriptor {
227    pub id: String,
228    pub name: String,
229    pub media_type: String,
230    pub byte_length: u64,
231    pub sha256: String,
232}
233
234#[derive(Clone, Debug, Serialize, Deserialize)]
235#[serde(deny_unknown_fields)]
236pub struct Message {
237    pub id: String,
238    pub exchange_id: String,
239    pub sender: String,
240    pub recipient: String,
241    pub text: String,
242    pub files: Vec<FilePart>,
243    #[serde(default, skip_serializing_if = "Vec::is_empty")]
244    pub attachments: Vec<FileDescriptor>,
245    pub reply_to: Option<String>,
246    pub created_at: i64,
247    pub expires_at: i64,
248    pub acknowledged: bool,
249    #[serde(default, skip_serializing_if = "Option::is_none")]
250    pub relay: Option<RelayMessage>,
251}
252
253#[derive(Clone, Debug, Serialize, Deserialize)]
254#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
255pub enum AgentOp {
256    DashboardGet,
257    Babysit {
258        enabled: Option<bool>,
259    },
260    BabysitterClaim {
261        goal: String,
262        turn: uuid::Uuid,
263        failed_at: i64,
264        reason: notifications::Failure,
265    },
266    BabysitterSubmitted {
267        attempt: uuid::Uuid,
268        scope: Option<notifications::Scope>,
269    },
270    BabysitterCheck {
271        attempt: uuid::Uuid,
272    },
273    BabysitterChatProbe {
274        turn: uuid::Uuid,
275        operator: uuid::Uuid,
276        failed_at: i64,
277    },
278    BabysitterChatClaim {
279        turn: uuid::Uuid,
280        failed_at: i64,
281        reason: notifications::Failure,
282        origin: babysitter::ChatOrigin,
283    },
284    BabysitterChatCheck {
285        attempt: uuid::Uuid,
286    },
287    BabysitterChatSubmitted {
288        attempt: uuid::Uuid,
289    },
290    DashboardDefine {
291        expected_revision: u64,
292        board: dashboard::Board,
293    },
294    DashboardAttachHtml {
295        expected_revision: u64,
296        file_id: uuid::Uuid,
297    },
298    DashboardUpdate {
299        expected_revision: u64,
300        values: BTreeMap<String, serde_json::Value>,
301    },
302    DashboardDelete {
303        expected_revision: u64,
304    },
305    Register {
306        name: String,
307        provider: String,
308    },
309    Identity,
310    /// Rename only this authenticated registration, preserving its identity.
311    Rename {
312        name: String,
313        expected_generation: u64,
314    },
315    /// Current relationship with one visible peer; never exposes raw policy.
316    PermissionCheck {
317        peer: String,
318    },
319    PermissionAdminCheck {
320        actor: String,
321        peer: String,
322    },
323    PermissionPreview {
324        changes: Vec<administration::PermissionChange>,
325    },
326    PermissionApply {
327        request_id: String,
328        changes: Vec<administration::PermissionChange>,
329    },
330    PermissionRequest {
331        request_id: String,
332    },
333    PermissionRuleScopes,
334    GroupAdminScopes,
335    GroupMembers {
336        group: String,
337    },
338    GroupPreview {
339        changes: Vec<administration::GroupChange>,
340    },
341    GroupApply {
342        request_id: String,
343        changes: Vec<administration::GroupChange>,
344    },
345    GroupRequest {
346        request_id: String,
347    },
348    PermissionRulePreview {
349        changes: Vec<administration::PermissionRuleChange>,
350    },
351    PermissionRuleApply {
352        request_id: String,
353        changes: Vec<administration::PermissionRuleChange>,
354    },
355    Agents,
356    Resolve {
357        name: String,
358        node: Option<String>,
359        provider: Option<String>,
360    },
361    RequestIds {
362        #[serde(default = "one_request_id")]
363        count: u32,
364    },
365    FilePaths,
366    FileImport {
367        request_id: String,
368        name: String,
369        media_type: String,
370    },
371    FileStatus {
372        file_id: String,
373    },
374    /// Private local RPC preflight; absent from the MCP tool surface.
375    FileReceiveStatus {
376        file: file_objects::IncomingFile,
377    },
378    /// Header for a bounded binary body after the daemon's ready response.
379    FileReceive {
380        file: file_objects::IncomingFile,
381        byte_length: u64,
382        sha256: String,
383    },
384    /// Constructed only by the local transport after receiving the whole body.
385    #[serde(skip)]
386    FileReceiveData {
387        file: file_objects::IncomingFile,
388        bytes: zeroize::Zeroizing<Vec<u8>>,
389    },
390    FileRead {
391        file_id: String,
392        chunk_index: u32,
393    },
394    FileView {
395        file_id: String,
396    },
397    /// Local historical imports explicitly assigned to this authenticated chat.
398    HistoryImports,
399    HistoryMessages {
400        import_id: String,
401        #[serde(default)]
402        after: u64,
403    },
404    HistoryFileRead {
405        import_id: String,
406        message_id: String,
407        file_index: u32,
408        chunk_index: u32,
409    },
410    HistoryFileView {
411        import_id: String,
412        message_id: String,
413        file_index: u32,
414    },
415    FileExport {
416        file_id: String,
417    },
418    Send {
419        recipient: String,
420        request_id: String,
421        text: String,
422        #[serde(default)]
423        files: Vec<FilePart>,
424        #[serde(default, skip_serializing_if = "Vec::is_empty")]
425        file_ids: Vec<String>,
426    },
427    /// Response-required send; uses an isolated relay turn without changing the
428    /// chat's persistent relay selection. MCP waits outside the daemon lock.
429    RequestReply {
430        recipient: String,
431        request_id: String,
432        text: String,
433        #[serde(default)]
434        files: Vec<FilePart>,
435        #[serde(default, skip_serializing_if = "Vec::is_empty")]
436        file_ids: Vec<String>,
437    },
438    Reply {
439        message_id: String,
440        request_id: String,
441        text: String,
442        #[serde(default)]
443        files: Vec<FilePart>,
444        #[serde(default, skip_serializing_if = "Vec::is_empty")]
445        file_ids: Vec<String>,
446    },
447    Inbox,
448    /// Local host adapter operations; not exposed as model-callable MCP tools.
449    WakePending,
450    WakeClaim {
451        message_id: String,
452        attempt_id: String,
453        target: wake::WakeTarget,
454    },
455    /// Recheck an existing claim without creating or renewing submission rights.
456    WakeCheck {
457        message_id: String,
458        attempt_id: String,
459        target: wake::WakeTarget,
460    },
461    WakeSubmitted {
462        message_id: String,
463        attempt_id: String,
464        submission_id: String,
465    },
466    /// Native adapter APIs, deliberately absent from model-callable MCP tools.
467    WakeDirectClaim {
468        message_id: String,
469        attempt_id: String,
470        target: wake::WakeTarget,
471    },
472    WakeDirectPending {
473        target: wake::WakeTarget,
474    },
475    WakeDirectRead {
476        message_id: String,
477        attempt_id: String,
478        target: wake::WakeTarget,
479    },
480    WakeDirectObserve {
481        message_id: String,
482        attempt_id: String,
483        target: wake::WakeTarget,
484        turn_id: String,
485    },
486    WakeDirectComplete {
487        message_id: String,
488        attempt_id: String,
489        target: wake::WakeTarget,
490        turn_id: String,
491        text: String,
492    },
493    WorkStatus {
494        message_id: String,
495    },
496    WorkBegin {
497        message_id: String,
498        #[serde(default)]
499        expect_revision: u64,
500        description: String,
501    },
502    WorkComplete {
503        message_id: String,
504        expect_revision: u64,
505        note: String,
506    },
507    Ack {
508        message_id: String,
509    },
510    MessageStatus {
511        message_id: String,
512    },
513    RelayAttach {
514        target: String,
515        request_id: String,
516    },
517    RelayStatus {
518        attachment_id: Option<String>,
519    },
520    RelayDetach {
521        attachment_id: String,
522    },
523    RelaySend {
524        attachment_id: String,
525        request_id: String,
526        text: String,
527        #[serde(default)]
528        files: Vec<FilePart>,
529        #[serde(default, skip_serializing_if = "Vec::is_empty")]
530        file_ids: Vec<String>,
531    },
532    RelayTurnStatus {
533        turn_id: String,
534        after_message_id: Option<String>,
535    },
536    RelayTurns {
537        after_turn_id: Option<String>,
538    },
539    RelayNext,
540    RelayRespond {
541        turn_id: String,
542        request_id: String,
543        text: String,
544        #[serde(default)]
545        files: Vec<FilePart>,
546        #[serde(default, skip_serializing_if = "Vec::is_empty")]
547        file_ids: Vec<String>,
548        outcome: RelayResponseKind,
549    },
550    RelayCancel {
551        turn_id: String,
552        request_id: String,
553    },
554}
555
556fn one_request_id() -> u32 {
557    1
558}
559
560#[derive(Clone, Debug, Serialize, Deserialize)]
561#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
562pub enum ConfigurationEdit {
563    EnrollNode {
564        request: String,
565        can_configure: bool,
566        invitation: Option<String>,
567    },
568    RemoveNode {
569        node_id: String,
570    },
571    DelegateNode {
572        node_id: String,
573        allow: bool,
574    },
575    /// Administrator-approved chat transport delegation; does not grant configuration access.
576    HostNode {
577        node_id: String,
578        parent: String,
579    },
580    CreateGroup {
581        name: String,
582    },
583    DeleteGroup {
584        name: String,
585    },
586    GroupMembers {
587        group: String,
588        members: Vec<String>,
589        action: administration::GroupAction,
590    },
591    GrantGroupAdmin {
592        grant_id: String,
593        administrator: String,
594        group: String,
595        members: Selector,
596        actions: Vec<administration::GroupAction>,
597        lifetime_seconds: u64,
598    },
599    RevokeGroupAdmin {
600        grant_id: String,
601    },
602    AgentGroups {
603        administrator: String,
604        request_id: String,
605        changes: Vec<administration::GroupChange>,
606    },
607    SetPermissionRule {
608        actor: Selector,
609        peer: Selector,
610        permission: Permission,
611        effect: Option<Effect>,
612    },
613    Policy {
614        policy: Policy,
615    },
616    Replace {
617        cluster_name: String,
618        node_name: String,
619        policy: Policy,
620    },
621    RenameNode {
622        name: String,
623    },
624    /// Rename this enrolled member in signed configuration, independently of the proposer.
625    RenameMember {
626        node_id: String,
627        name: String,
628    },
629    SetReleaseChannel {
630        channel: ReleaseChannel,
631    },
632    Renew,
633    GrantRelay {
634        grant_id: String,
635        intermediary: String,
636        target: String,
637        lifetime_seconds: u64,
638    },
639    RevokeRelay {
640        grant_id: String,
641    },
642    GrantPermissionAdmin {
643        grant_id: String,
644        administrator: String,
645        actor: Selector,
646        peer: Selector,
647        permissions: Vec<Permission>,
648        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
649        selector_rules: bool,
650        lifetime_seconds: u64,
651    },
652    RevokePermissionAdmin {
653        grant_id: String,
654    },
655    /// Internal authenticated proposal; MCP supplies neither administrator nor
656    /// origin node. The owner rechecks both and every grant before accepting it.
657    AgentPermissions {
658        administrator: String,
659        request_id: String,
660        changes: Vec<administration::PermissionChange>,
661    },
662    AgentPermissionRules {
663        administrator: String,
664        request_id: String,
665        changes: Vec<administration::PermissionRuleChange>,
666    },
667}
668
669#[derive(Clone, Debug, Serialize, Deserialize)]
670#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
671pub enum OwnerOp {
672    DashboardRemoteHtml {
673        boards: Vec<dashboard::HtmlProbe>,
674    },
675    Dashboards {
676        after: Option<String>,
677    },
678    NotificationPut {
679        notice: notifications::Notice,
680        scope: Option<notifications::Scope>,
681    },
682    NotificationPending {
683        scope: notifications::Scope,
684    },
685    NotificationSent {
686        id: uuid::Uuid,
687    },
688    DashboardClick {
689        agent: String,
690        revision: u64,
691        widget: String,
692        request_id: String,
693    },
694    /// Scoped proof for the hosted checkpoint service; never exports a signing key.
695    WebAdmission {
696        node_id: String,
697        body_hash: [u8; 32],
698    },
699    WebCheckpoint {
700        node_id: String,
701    },
702    WebCommit {
703        node_id: String,
704        revision: u64,
705        #[serde(default, skip_serializing_if = "Option::is_none")]
706        epoch: Option<u64>,
707    },
708    WebLease {
709        node_id: String,
710        seconds: u64,
711    },
712    /// Absolute Unix deadline bounded by the start of the authority request.
713    /// Zero closes the epoch and fences delayed grants for the same session.
714    WebGrant {
715        node_id: String,
716        epoch: u64,
717        expires_at: u64,
718    },
719    RestoreWebNode {
720        node_id: String,
721        home: std::path::PathBuf,
722        checkpoint: std::path::PathBuf,
723        #[serde(default, skip_serializing_if = "Option::is_none")]
724        epoch: Option<u64>,
725    },
726    PreparePeerConfiguration,
727    Groups {
728        name: Option<String>,
729    },
730    GroupAdmins,
731    GroupAdminHistory {
732        administrator: Option<String>,
733        before: Option<u64>,
734    },
735    Configure {
736        request_id: String,
737        edit: ConfigurationEdit,
738    },
739    ConfigurationRequests {
740        request_id: Option<String>,
741    },
742    DelegateConfiguration {
743        node_id: String,
744        allow: bool,
745    },
746    /// Local signing-owner administration, never exposed as a chat tool.
747    RemoveNode {
748        node_id: String,
749    },
750    NodeRemovals {
751        after: Option<String>,
752        pending_only: bool,
753    },
754    ConfirmNodeRemoval {
755        node_id: String,
756        revision: u64,
757    },
758    Status,
759    /// Move a stopped, locally owned web node's retained state into this daemon.
760    PrepareHostedNode {
761        node_id: String,
762        home: std::path::PathBuf,
763    },
764    /// Read-only local-owner diagnostics; never advances clocks or projects files.
765    Diagnose,
766    PermissionRules,
767    PermissionExplain {
768        actor: String,
769        peer: String,
770    },
771    PermissionAdmins,
772    PermissionAdminHistory {
773        administrator: Option<String>,
774        before: Option<u64>,
775    },
776    Nodes,
777    RefreshNodes,
778    Agents,
779    NativeMessageDates,
780    ObserveActivity {
781        agent_id: String,
782        last_activity_at: i64,
783        #[serde(default, skip_serializing_if = "Option::is_none")]
784        last_native_message_at: Option<i64>,
785    },
786    ClearRetiredAgents {
787        dry_run: bool,
788    },
789    Resolve {
790        name: String,
791        node: Option<String>,
792        provider: Option<String>,
793    },
794    Agent {
795        agent_id: String,
796    },
797    RenameAgent {
798        agent_id: String,
799        name: String,
800        expected_generation: u64,
801    },
802    Providers,
803    FilesStatus,
804    HistoryStatus,
805    /// Private recovery evidence. These operations grant no replacement authority.
806    RecoveryChallenge,
807    OwnerHandoffStatus,
808    OwnerTransfer {
809        action: owner_transfer::OwnerTransferOp,
810    },
811    RecoveryObserve {
812        challenge: String,
813    },
814    WorkList {
815        after_message_id: Option<String>,
816    },
817    WakeList {
818        after_message_id: Option<String>,
819    },
820    WakeStatus,
821    /// Owner-only pending recipient IDs; does not expose message content.
822    WakePendingAgents {
823        after: Option<String>,
824    },
825    /// Local supervisor lookup for one retained Codex dispatch. Metadata only.
826    WakeDirectTurnEvidence {
827        /// A second input to a drained queue requires a completed relay request.
828        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
829        completed_relay: bool,
830        agent_credential: String,
831        thread_id: uuid::Uuid,
832        turn: uuid::Uuid,
833    },
834    /// The bound supervisor has corroborated the blocked goal and native history.
835    BabysitterVerifiedBlockedClaim {
836        agent_credential: String,
837        thread_id: uuid::Uuid,
838        goal: String,
839        turn: uuid::Uuid,
840        failed_at: i64,
841        reason: notifications::Failure,
842    },
843    WakeClean {
844        dry_run: bool,
845    },
846    WakeShow {
847        message_id: String,
848    },
849    WorkShow {
850        message_id: String,
851    },
852    WorkReconcile {
853        message_id: String,
854        expect_revision: u64,
855        resolution: work::WorkResolution,
856        note: String,
857    },
858    HistoryImports,
859    AgentRecover {
860        directory: String,
861        manifest_sha256: String,
862        source_agent: String,
863        agent_credential: String,
864        name: String,
865        provider: String,
866    },
867    HistoryImport {
868        directory: String,
869        manifest_sha256: String,
870        source_agent: String,
871        target_agent: String,
872        restore_revision: Option<u64>,
873    },
874    HistoryRemove {
875        import_id: String,
876        expected_revision: u64,
877    },
878    HistoryClean {
879        dry_run: bool,
880    },
881    TransportStatus,
882    WebDeliveryDemand {
883        node_id: String,
884    },
885    WebDeliveryChecked {
886        node_id: String,
887        message_id: String,
888    },
889    TransportClean {
890        dry_run: bool,
891    },
892    FilesClean {
893        dry_run: bool,
894    },
895    RelayGrants,
896    RelayAttachments,
897    SetPolicy {
898        policy: Policy,
899    },
900    Renew,
901    RenameNode {
902        name: String,
903    },
904    Revoke {
905        agent_id: String,
906    },
907    /// Owner-only bootstrap over an independently authenticated private channel.
908    Pair {
909        cluster_id: String,
910        action: PairingOp,
911    },
912    /// Local owner administration; private invitation material is never a chat tool.
913    Invitation {
914        action: InvitationOp,
915    },
916    /// Local administrator request, forwarded over authenticated node streams.
917    NodeInvite {
918        request_id: String,
919        name: String,
920        can_configure: bool,
921        activate: bool,
922    },
923}
924
925#[derive(Clone, Debug, Serialize, Deserialize)]
926#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
927pub enum InvitationOp {
928    Create {
929        request_id: String,
930        can_configure: bool,
931        continuation: Option<String>,
932        #[serde(default, skip_serializing_if = "Option::is_none")]
933        replace_node: Option<String>,
934    },
935    Activate {
936        id: String,
937    },
938    Revoke {
939        id: String,
940    },
941    List,
942}
943
944#[derive(Clone, Debug, Serialize, Deserialize)]
945#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
946pub enum PairingOp {
947    Snapshot,
948    Enroll {
949        request: String,
950    },
951    Configuration {
952        request_id: String,
953        peer: String,
954        key_package: String,
955    },
956    History {
957        revision: u64,
958        digest: [u8; 32],
959    },
960    Data {
961        request_id: String,
962        peer: String,
963        key_package: String,
964        legacy_agents: Vec<String>,
965    },
966    AcceptData {
967        peer: String,
968        packet: String,
969        outgoing_group: String,
970    },
971}
972
973#[derive(Serialize, Deserialize)]
974#[serde(tag = "role", rename_all = "snake_case", deny_unknown_fields)]
975pub enum Request {
976    Agent {
977        credential: String,
978        action: AgentOp,
979    },
980    Owner {
981        credential: String,
982        action: OwnerOp,
983    },
984    /// Private gateway-to-daemon RPC. The node scope is never supplied by MCP.
985    HostedAgent {
986        node_id: String,
987        gateway_credential: String,
988        #[serde(default, skip_serializing_if = "Option::is_none")]
989        epoch: Option<u64>,
990        credential: String,
991        action: AgentOp,
992    },
993    HostedStatus {
994        node_id: String,
995        gateway_credential: String,
996    },
997}
998
999#[derive(Debug, Serialize, Deserialize)]
1000#[serde(tag = "status", content = "data", rename_all = "snake_case")]
1001pub enum Response {
1002    Ok(serde_json::Value),
1003    Error(String),
1004}
1005
1006#[cfg(test)]
1007mod tests {
1008    use super::*;
1009    fn agent(id: &str, node: &str) -> Agent {
1010        Agent {
1011            id: id.into(),
1012            node_id: node.into(),
1013            name: id.into(),
1014            provider: "anything".into(),
1015            last_seen: 0,
1016            revoked: false,
1017        }
1018    }
1019    fn allow(policy: &mut Policy, a: &str, b: &str, permission: Permission) {
1020        policy.rules.push(Rule {
1021            actor: Selector::Agent(a.into()),
1022            peer: Selector::Agent(b.into()),
1023            permission,
1024            effect: Effect::Allow,
1025        });
1026    }
1027    #[test]
1028    fn default_deny_and_scoped_reply() {
1029        let (a, b) = (agent("a", "node"), agent("b", "node"));
1030        let mut p = Policy::default();
1031        assert!(!p.can_open(&a, &b));
1032        allow(&mut p, "a", "b", Permission::Enumerate);
1033        allow(&mut p, "b", "a", Permission::Enumerate);
1034        allow(&mut p, "a", "b", Permission::Send);
1035        allow(&mut p, "b", "a", Permission::Receive);
1036        assert!(p.can_open(&a, &b));
1037        assert!(!p.can_open(&b, &a));
1038        assert!(p.can_reply(&b, &a));
1039        p.rules.push(Rule {
1040            actor: Selector::Agent("b".into()),
1041            peer: Selector::Agent("a".into()),
1042            permission: Permission::Send,
1043            effect: Effect::Deny,
1044        });
1045        assert!(p.can_reply(&b, &a));
1046        p.rules.push(Rule {
1047            actor: Selector::Agent("a".into()),
1048            peer: Selector::Agent("b".into()),
1049            permission: Permission::Receive,
1050            effect: Effect::Deny,
1051        });
1052        assert!(!p.can_reply(&b, &a));
1053        assert!(!p.can_open(&a, &b));
1054    }
1055    #[test]
1056    fn denials_override_same_node_grants_and_location_changes() {
1057        let (a, mut b) = (agent("a", "one"), agent("b", "one"));
1058        let mut p = Policy::default();
1059        for permission in [Permission::Enumerate, Permission::Send, Permission::Receive] {
1060            p.rules.push(Rule {
1061                actor: Selector::All,
1062                peer: Selector::SameNode,
1063                permission,
1064                effect: Effect::Allow,
1065            });
1066        }
1067        assert!(p.can_open(&a, &b));
1068        b.node_id = "two".into();
1069        assert!(!p.can_open(&a, &b));
1070        b.node_id = "one".into();
1071        p.rules.insert(
1072            0,
1073            Rule {
1074                actor: Selector::Agent("a".into()),
1075                peer: Selector::All,
1076                permission: Permission::Enumerate,
1077                effect: Effect::Deny,
1078            },
1079        );
1080        assert!(!p.can_open(&a, &b));
1081        assert!(!p.can_reply(&a, &b));
1082    }
1083    #[test]
1084    fn authenticated_groups_and_revocation() {
1085        let (a, mut b) = (agent("a", "one"), agent("b", "two"));
1086        let mut p = Policy::default();
1087        p.groups.insert("team".into(), vec!["a".into(), "b".into()]);
1088        for permission in [Permission::Enumerate, Permission::Send, Permission::Receive] {
1089            p.rules.push(Rule {
1090                actor: Selector::Group("team".into()),
1091                peer: Selector::Group("team".into()),
1092                permission,
1093                effect: Effect::Allow,
1094            });
1095        }
1096        assert!(p.can_open(&a, &b));
1097        b.revoked = true;
1098        assert!(!p.can_open(&a, &b));
1099        assert!(!p.can_reply(&b, &a));
1100    }
1101}