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