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    DashboardUpdate {
295        expected_revision: u64,
296        values: BTreeMap<String, serde_json::Value>,
297    },
298    DashboardDelete {
299        expected_revision: u64,
300    },
301    Register {
302        name: String,
303        provider: String,
304    },
305    Identity,
306    /// Rename only this authenticated registration, preserving its identity.
307    Rename {
308        name: String,
309        expected_generation: u64,
310    },
311    /// Current relationship with one visible peer; never exposes raw policy.
312    PermissionCheck {
313        peer: String,
314    },
315    PermissionAdminCheck {
316        actor: String,
317        peer: String,
318    },
319    PermissionPreview {
320        changes: Vec<administration::PermissionChange>,
321    },
322    PermissionApply {
323        request_id: String,
324        changes: Vec<administration::PermissionChange>,
325    },
326    PermissionRequest {
327        request_id: String,
328    },
329    PermissionRuleScopes,
330    GroupAdminScopes,
331    GroupMembers {
332        group: String,
333    },
334    GroupPreview {
335        changes: Vec<administration::GroupChange>,
336    },
337    GroupApply {
338        request_id: String,
339        changes: Vec<administration::GroupChange>,
340    },
341    GroupRequest {
342        request_id: String,
343    },
344    PermissionRulePreview {
345        changes: Vec<administration::PermissionRuleChange>,
346    },
347    PermissionRuleApply {
348        request_id: String,
349        changes: Vec<administration::PermissionRuleChange>,
350    },
351    Agents,
352    Resolve {
353        name: String,
354        node: Option<String>,
355        provider: Option<String>,
356    },
357    RequestIds {
358        #[serde(default = "one_request_id")]
359        count: u32,
360    },
361    FilePaths,
362    FileImport {
363        request_id: String,
364        name: String,
365        media_type: String,
366    },
367    FileStatus {
368        file_id: String,
369    },
370    /// Private local RPC preflight; absent from the MCP tool surface.
371    FileReceiveStatus {
372        file: file_objects::IncomingFile,
373    },
374    /// Header for a bounded binary body after the daemon's ready response.
375    FileReceive {
376        file: file_objects::IncomingFile,
377        byte_length: u64,
378        sha256: String,
379    },
380    /// Constructed only by the local transport after receiving the whole body.
381    #[serde(skip)]
382    FileReceiveData {
383        file: file_objects::IncomingFile,
384        bytes: zeroize::Zeroizing<Vec<u8>>,
385    },
386    FileRead {
387        file_id: String,
388        chunk_index: u32,
389    },
390    FileView {
391        file_id: String,
392    },
393    /// Local historical imports explicitly assigned to this authenticated chat.
394    HistoryImports,
395    HistoryMessages {
396        import_id: String,
397        #[serde(default)]
398        after: u64,
399    },
400    HistoryFileRead {
401        import_id: String,
402        message_id: String,
403        file_index: u32,
404        chunk_index: u32,
405    },
406    HistoryFileView {
407        import_id: String,
408        message_id: String,
409        file_index: u32,
410    },
411    FileExport {
412        file_id: String,
413    },
414    Send {
415        recipient: String,
416        request_id: String,
417        text: String,
418        #[serde(default)]
419        files: Vec<FilePart>,
420        #[serde(default, skip_serializing_if = "Vec::is_empty")]
421        file_ids: Vec<String>,
422    },
423    /// Response-required send; uses an isolated relay turn without changing the
424    /// chat's persistent relay selection. MCP waits outside the daemon lock.
425    RequestReply {
426        recipient: String,
427        request_id: String,
428        text: String,
429        #[serde(default)]
430        files: Vec<FilePart>,
431        #[serde(default, skip_serializing_if = "Vec::is_empty")]
432        file_ids: Vec<String>,
433    },
434    Reply {
435        message_id: String,
436        request_id: String,
437        text: String,
438        #[serde(default)]
439        files: Vec<FilePart>,
440        #[serde(default, skip_serializing_if = "Vec::is_empty")]
441        file_ids: Vec<String>,
442    },
443    Inbox,
444    /// Local host adapter operations; not exposed as model-callable MCP tools.
445    WakePending,
446    WakeClaim {
447        message_id: String,
448        attempt_id: String,
449        target: wake::WakeTarget,
450    },
451    /// Recheck an existing claim without creating or renewing submission rights.
452    WakeCheck {
453        message_id: String,
454        attempt_id: String,
455        target: wake::WakeTarget,
456    },
457    WakeSubmitted {
458        message_id: String,
459        attempt_id: String,
460        submission_id: String,
461    },
462    /// Native adapter APIs, deliberately absent from model-callable MCP tools.
463    WakeDirectClaim {
464        message_id: String,
465        attempt_id: String,
466        target: wake::WakeTarget,
467    },
468    WakeDirectPending {
469        target: wake::WakeTarget,
470    },
471    WakeDirectRead {
472        message_id: String,
473        attempt_id: String,
474        target: wake::WakeTarget,
475    },
476    WakeDirectObserve {
477        message_id: String,
478        attempt_id: String,
479        target: wake::WakeTarget,
480        turn_id: String,
481    },
482    WakeDirectComplete {
483        message_id: String,
484        attempt_id: String,
485        target: wake::WakeTarget,
486        turn_id: String,
487        text: String,
488    },
489    WorkStatus {
490        message_id: String,
491    },
492    WorkBegin {
493        message_id: String,
494        #[serde(default)]
495        expect_revision: u64,
496        description: String,
497    },
498    WorkComplete {
499        message_id: String,
500        expect_revision: u64,
501        note: String,
502    },
503    Ack {
504        message_id: String,
505    },
506    MessageStatus {
507        message_id: String,
508    },
509    RelayAttach {
510        target: String,
511        request_id: String,
512    },
513    RelayStatus {
514        attachment_id: Option<String>,
515    },
516    RelayDetach {
517        attachment_id: String,
518    },
519    RelaySend {
520        attachment_id: String,
521        request_id: String,
522        text: String,
523        #[serde(default)]
524        files: Vec<FilePart>,
525        #[serde(default, skip_serializing_if = "Vec::is_empty")]
526        file_ids: Vec<String>,
527    },
528    RelayTurnStatus {
529        turn_id: String,
530        after_message_id: Option<String>,
531    },
532    RelayTurns {
533        after_turn_id: Option<String>,
534    },
535    RelayNext,
536    RelayRespond {
537        turn_id: String,
538        request_id: String,
539        text: String,
540        #[serde(default)]
541        files: Vec<FilePart>,
542        #[serde(default, skip_serializing_if = "Vec::is_empty")]
543        file_ids: Vec<String>,
544        outcome: RelayResponseKind,
545    },
546    RelayCancel {
547        turn_id: String,
548        request_id: String,
549    },
550}
551
552fn one_request_id() -> u32 {
553    1
554}
555
556#[derive(Clone, Debug, Serialize, Deserialize)]
557#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
558pub enum ConfigurationEdit {
559    EnrollNode {
560        request: String,
561        can_configure: bool,
562        invitation: Option<String>,
563    },
564    RemoveNode {
565        node_id: String,
566    },
567    DelegateNode {
568        node_id: String,
569        allow: bool,
570    },
571    /// Administrator-approved chat transport delegation; does not grant configuration access.
572    HostNode {
573        node_id: String,
574        parent: String,
575    },
576    CreateGroup {
577        name: String,
578    },
579    DeleteGroup {
580        name: String,
581    },
582    GroupMembers {
583        group: String,
584        members: Vec<String>,
585        action: administration::GroupAction,
586    },
587    GrantGroupAdmin {
588        grant_id: String,
589        administrator: String,
590        group: String,
591        members: Selector,
592        actions: Vec<administration::GroupAction>,
593        lifetime_seconds: u64,
594    },
595    RevokeGroupAdmin {
596        grant_id: String,
597    },
598    AgentGroups {
599        administrator: String,
600        request_id: String,
601        changes: Vec<administration::GroupChange>,
602    },
603    SetPermissionRule {
604        actor: Selector,
605        peer: Selector,
606        permission: Permission,
607        effect: Option<Effect>,
608    },
609    Policy {
610        policy: Policy,
611    },
612    Replace {
613        cluster_name: String,
614        node_name: String,
615        policy: Policy,
616    },
617    RenameNode {
618        name: String,
619    },
620    /// Rename this enrolled member in signed configuration, independently of the proposer.
621    RenameMember {
622        node_id: String,
623        name: String,
624    },
625    SetReleaseChannel {
626        channel: ReleaseChannel,
627    },
628    Renew,
629    GrantRelay {
630        grant_id: String,
631        intermediary: String,
632        target: String,
633        lifetime_seconds: u64,
634    },
635    RevokeRelay {
636        grant_id: String,
637    },
638    GrantPermissionAdmin {
639        grant_id: String,
640        administrator: String,
641        actor: Selector,
642        peer: Selector,
643        permissions: Vec<Permission>,
644        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
645        selector_rules: bool,
646        lifetime_seconds: u64,
647    },
648    RevokePermissionAdmin {
649        grant_id: String,
650    },
651    /// Internal authenticated proposal; MCP supplies neither administrator nor
652    /// origin node. The owner rechecks both and every grant before accepting it.
653    AgentPermissions {
654        administrator: String,
655        request_id: String,
656        changes: Vec<administration::PermissionChange>,
657    },
658    AgentPermissionRules {
659        administrator: String,
660        request_id: String,
661        changes: Vec<administration::PermissionRuleChange>,
662    },
663}
664
665#[derive(Clone, Debug, Serialize, Deserialize)]
666#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
667pub enum OwnerOp {
668    Dashboards {
669        after: Option<String>,
670    },
671    NotificationPut {
672        notice: notifications::Notice,
673        scope: Option<notifications::Scope>,
674    },
675    NotificationPending {
676        scope: notifications::Scope,
677    },
678    NotificationSent {
679        id: uuid::Uuid,
680    },
681    DashboardClick {
682        agent: String,
683        revision: u64,
684        widget: String,
685        request_id: String,
686    },
687    /// Scoped proof for the hosted checkpoint service; never exports a signing key.
688    WebAdmission {
689        node_id: String,
690        body_hash: [u8; 32],
691    },
692    WebCheckpoint {
693        node_id: String,
694    },
695    WebCommit {
696        node_id: String,
697        revision: u64,
698        #[serde(default, skip_serializing_if = "Option::is_none")]
699        epoch: Option<u64>,
700    },
701    WebLease {
702        node_id: String,
703        seconds: u64,
704    },
705    /// Absolute Unix deadline bounded by the start of the authority request.
706    /// Zero closes the epoch and fences delayed grants for the same session.
707    WebGrant {
708        node_id: String,
709        epoch: u64,
710        expires_at: u64,
711    },
712    RestoreWebNode {
713        node_id: String,
714        home: std::path::PathBuf,
715        checkpoint: std::path::PathBuf,
716        #[serde(default, skip_serializing_if = "Option::is_none")]
717        epoch: Option<u64>,
718    },
719    PreparePeerConfiguration,
720    Groups {
721        name: Option<String>,
722    },
723    GroupAdmins,
724    GroupAdminHistory {
725        administrator: Option<String>,
726        before: Option<u64>,
727    },
728    Configure {
729        request_id: String,
730        edit: ConfigurationEdit,
731    },
732    ConfigurationRequests {
733        request_id: Option<String>,
734    },
735    DelegateConfiguration {
736        node_id: String,
737        allow: bool,
738    },
739    /// Local signing-owner administration, never exposed as a chat tool.
740    RemoveNode {
741        node_id: String,
742    },
743    NodeRemovals {
744        after: Option<String>,
745        pending_only: bool,
746    },
747    ConfirmNodeRemoval {
748        node_id: String,
749        revision: u64,
750    },
751    Status,
752    /// Move a stopped, locally owned web node's retained state into this daemon.
753    PrepareHostedNode {
754        node_id: String,
755        home: std::path::PathBuf,
756    },
757    /// Read-only local-owner diagnostics; never advances clocks or projects files.
758    Diagnose,
759    PermissionRules,
760    PermissionExplain {
761        actor: String,
762        peer: String,
763    },
764    PermissionAdmins,
765    PermissionAdminHistory {
766        administrator: Option<String>,
767        before: Option<u64>,
768    },
769    Nodes,
770    RefreshNodes,
771    Agents,
772    NativeMessageDates,
773    ObserveActivity {
774        agent_id: String,
775        last_activity_at: i64,
776        #[serde(default, skip_serializing_if = "Option::is_none")]
777        last_native_message_at: Option<i64>,
778    },
779    ClearRetiredAgents {
780        dry_run: bool,
781    },
782    Resolve {
783        name: String,
784        node: Option<String>,
785        provider: Option<String>,
786    },
787    Agent {
788        agent_id: String,
789    },
790    RenameAgent {
791        agent_id: String,
792        name: String,
793        expected_generation: u64,
794    },
795    Providers,
796    FilesStatus,
797    HistoryStatus,
798    /// Private recovery evidence. These operations grant no replacement authority.
799    RecoveryChallenge,
800    OwnerHandoffStatus,
801    OwnerTransfer {
802        action: owner_transfer::OwnerTransferOp,
803    },
804    RecoveryObserve {
805        challenge: String,
806    },
807    WorkList {
808        after_message_id: Option<String>,
809    },
810    WakeList {
811        after_message_id: Option<String>,
812    },
813    WakeStatus,
814    /// Owner-only pending recipient IDs; does not expose message content.
815    WakePendingAgents {
816        after: Option<String>,
817    },
818    /// Local supervisor lookup for one retained Codex dispatch. Metadata only.
819    WakeDirectTurnEvidence {
820        /// A second input to a drained queue requires a completed relay request.
821        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
822        completed_relay: bool,
823        agent_credential: String,
824        thread_id: uuid::Uuid,
825        turn: uuid::Uuid,
826    },
827    /// The bound supervisor has corroborated the blocked goal and native history.
828    BabysitterVerifiedBlockedClaim {
829        agent_credential: String,
830        thread_id: uuid::Uuid,
831        goal: String,
832        turn: uuid::Uuid,
833        failed_at: i64,
834        reason: notifications::Failure,
835    },
836    WakeClean {
837        dry_run: bool,
838    },
839    WakeShow {
840        message_id: String,
841    },
842    WorkShow {
843        message_id: String,
844    },
845    WorkReconcile {
846        message_id: String,
847        expect_revision: u64,
848        resolution: work::WorkResolution,
849        note: String,
850    },
851    HistoryImports,
852    AgentRecover {
853        directory: String,
854        manifest_sha256: String,
855        source_agent: String,
856        agent_credential: String,
857        name: String,
858        provider: String,
859    },
860    HistoryImport {
861        directory: String,
862        manifest_sha256: String,
863        source_agent: String,
864        target_agent: String,
865        restore_revision: Option<u64>,
866    },
867    HistoryRemove {
868        import_id: String,
869        expected_revision: u64,
870    },
871    HistoryClean {
872        dry_run: bool,
873    },
874    TransportStatus,
875    WebDeliveryDemand {
876        node_id: String,
877    },
878    WebDeliveryChecked {
879        node_id: String,
880        message_id: String,
881    },
882    TransportClean {
883        dry_run: bool,
884    },
885    FilesClean {
886        dry_run: bool,
887    },
888    RelayGrants,
889    RelayAttachments,
890    SetPolicy {
891        policy: Policy,
892    },
893    Renew,
894    RenameNode {
895        name: String,
896    },
897    Revoke {
898        agent_id: String,
899    },
900    /// Owner-only bootstrap over an independently authenticated private channel.
901    Pair {
902        cluster_id: String,
903        action: PairingOp,
904    },
905    /// Local owner administration; private invitation material is never a chat tool.
906    Invitation {
907        action: InvitationOp,
908    },
909    /// Local administrator request, forwarded over authenticated node streams.
910    NodeInvite {
911        request_id: String,
912        name: String,
913        can_configure: bool,
914        activate: bool,
915    },
916}
917
918#[derive(Clone, Debug, Serialize, Deserialize)]
919#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
920pub enum InvitationOp {
921    Create {
922        request_id: String,
923        can_configure: bool,
924        continuation: Option<String>,
925        #[serde(default, skip_serializing_if = "Option::is_none")]
926        replace_node: Option<String>,
927    },
928    Activate {
929        id: String,
930    },
931    Revoke {
932        id: String,
933    },
934    List,
935}
936
937#[derive(Clone, Debug, Serialize, Deserialize)]
938#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
939pub enum PairingOp {
940    Snapshot,
941    Enroll {
942        request: String,
943    },
944    Configuration {
945        request_id: String,
946        peer: String,
947        key_package: String,
948    },
949    History {
950        revision: u64,
951        digest: [u8; 32],
952    },
953    Data {
954        request_id: String,
955        peer: String,
956        key_package: String,
957        legacy_agents: Vec<String>,
958    },
959    AcceptData {
960        peer: String,
961        packet: String,
962        outgoing_group: String,
963    },
964}
965
966#[derive(Serialize, Deserialize)]
967#[serde(tag = "role", rename_all = "snake_case", deny_unknown_fields)]
968pub enum Request {
969    Agent {
970        credential: String,
971        action: AgentOp,
972    },
973    Owner {
974        credential: String,
975        action: OwnerOp,
976    },
977    /// Private gateway-to-daemon RPC. The node scope is never supplied by MCP.
978    HostedAgent {
979        node_id: String,
980        gateway_credential: String,
981        #[serde(default, skip_serializing_if = "Option::is_none")]
982        epoch: Option<u64>,
983        credential: String,
984        action: AgentOp,
985    },
986    HostedStatus {
987        node_id: String,
988        gateway_credential: String,
989    },
990}
991
992#[derive(Debug, Serialize, Deserialize)]
993#[serde(tag = "status", content = "data", rename_all = "snake_case")]
994pub enum Response {
995    Ok(serde_json::Value),
996    Error(String),
997}
998
999#[cfg(test)]
1000mod tests {
1001    use super::*;
1002    fn agent(id: &str, node: &str) -> Agent {
1003        Agent {
1004            id: id.into(),
1005            node_id: node.into(),
1006            name: id.into(),
1007            provider: "anything".into(),
1008            last_seen: 0,
1009            revoked: false,
1010        }
1011    }
1012    fn allow(policy: &mut Policy, a: &str, b: &str, permission: Permission) {
1013        policy.rules.push(Rule {
1014            actor: Selector::Agent(a.into()),
1015            peer: Selector::Agent(b.into()),
1016            permission,
1017            effect: Effect::Allow,
1018        });
1019    }
1020    #[test]
1021    fn default_deny_and_scoped_reply() {
1022        let (a, b) = (agent("a", "node"), agent("b", "node"));
1023        let mut p = Policy::default();
1024        assert!(!p.can_open(&a, &b));
1025        allow(&mut p, "a", "b", Permission::Enumerate);
1026        allow(&mut p, "b", "a", Permission::Enumerate);
1027        allow(&mut p, "a", "b", Permission::Send);
1028        allow(&mut p, "b", "a", Permission::Receive);
1029        assert!(p.can_open(&a, &b));
1030        assert!(!p.can_open(&b, &a));
1031        assert!(p.can_reply(&b, &a));
1032        p.rules.push(Rule {
1033            actor: Selector::Agent("b".into()),
1034            peer: Selector::Agent("a".into()),
1035            permission: Permission::Send,
1036            effect: Effect::Deny,
1037        });
1038        assert!(p.can_reply(&b, &a));
1039        p.rules.push(Rule {
1040            actor: Selector::Agent("a".into()),
1041            peer: Selector::Agent("b".into()),
1042            permission: Permission::Receive,
1043            effect: Effect::Deny,
1044        });
1045        assert!(!p.can_reply(&b, &a));
1046        assert!(!p.can_open(&a, &b));
1047    }
1048    #[test]
1049    fn denials_override_same_node_grants_and_location_changes() {
1050        let (a, mut b) = (agent("a", "one"), agent("b", "one"));
1051        let mut p = Policy::default();
1052        for permission in [Permission::Enumerate, Permission::Send, Permission::Receive] {
1053            p.rules.push(Rule {
1054                actor: Selector::All,
1055                peer: Selector::SameNode,
1056                permission,
1057                effect: Effect::Allow,
1058            });
1059        }
1060        assert!(p.can_open(&a, &b));
1061        b.node_id = "two".into();
1062        assert!(!p.can_open(&a, &b));
1063        b.node_id = "one".into();
1064        p.rules.insert(
1065            0,
1066            Rule {
1067                actor: Selector::Agent("a".into()),
1068                peer: Selector::All,
1069                permission: Permission::Enumerate,
1070                effect: Effect::Deny,
1071            },
1072        );
1073        assert!(!p.can_open(&a, &b));
1074        assert!(!p.can_reply(&a, &b));
1075    }
1076    #[test]
1077    fn authenticated_groups_and_revocation() {
1078        let (a, mut b) = (agent("a", "one"), agent("b", "two"));
1079        let mut p = Policy::default();
1080        p.groups.insert("team".into(), vec!["a".into(), "b".into()]);
1081        for permission in [Permission::Enumerate, Permission::Send, Permission::Receive] {
1082            p.rules.push(Rule {
1083                actor: Selector::Group("team".into()),
1084                peer: Selector::Group("team".into()),
1085                permission,
1086                effect: Effect::Allow,
1087            });
1088        }
1089        assert!(p.can_open(&a, &b));
1090        b.revoked = true;
1091        assert!(!p.can_open(&a, &b));
1092        assert!(!p.can_reply(&b, &a));
1093    }
1094}